teleren/devto huggingface dataset:
How to resolve a Cross-Origin Resource Sharing (CORS) error?
Tags: javascript, cors, http, beginners
Published: 2022-04-16 21:02:26

You must have already been through the situation of trying to log in to some application, type your data, click send and nothing happens on the page. The first thing a developer does is inspect the page and then open the browser console (by clicking the F12 button or pressing the right mouse button, then Inspect).

You get the error "blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, edge, https, chrome-untrusted." or similar.

![Console cors error](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cg73sy3nvtw5agp57ti7.png)

But do you know what causes it?

## Same-origin policy

The same-origin policy is a security mechanism that restricts the way a document or script from one origin interacts with a resource from another origin. And what is it for? Helps to prevent malicious attacks.

Two URLs share the same origin if the protocol, port (if specified), and host are the same. 

how do we handle situations where our frontend needs to consume an API with different url without having issues with CORS? As in case we want to connect an API running on port 8000 with a React application running on port 3000?

When sending a request to a different origin API, the server needs to return a header called Access-Control-Allow-Origin. Inside it, it is necessary to inform the different origins that will be allowed, such as: Access-Control-Allow-Origin: http://localhost:3000/.

It is possible to allow access from any origin using the *asterisk symbol: `Access-Control-Allow-Origin: `.** This is not a recommended measure as it allows unknown origins to access the server, unless it is intentional as in case of a public API.

## After all, what is CORS?

CORS (Cross-origin Resource Sharing) is a mechanism used to add HTTP headers that tell browsers to allow a web application to run on one origin and access resources from a different origin. This type of action is called a cross-origin HTTP request.

It is used to enable cross-site requests for XMLHttpRequest or FetchAPI calls (cross different origins), web fonts (@font from CSS), WebGL textures, and drawing frames using drawImage().
Hello World - My Coding Journey So Far
Published: 2022-04-16 20:57:41

Hi my name is Steven, age 46, partner 5 kids, working part time from New Zealand. My goals are to learn to code Web3 so I can build my sustainable projects and my gaming metaverse on blockchain with Signum, Hive, Eth, Sol, Wax to name a few. What a daunting task that I gave myself, well I love challenges 💪💪💪 - me before I started lol.

Well weeks and months have past and what an up and down journey that it has been. I have to say this, if you are an aspiring learner, a lot of the youtube video's that teach you how to build just dont work and the biggest take away here is - that in most cases they dont work is because the version they are using has upgraded. The tech space moves incredibly quick so ensure you have the latest version of what ever the content creator is using and you have the add info to the code if need be. I think the content creators are awesome and I have loved trying to understand and if I get stuck most content creators answer my questions or I head over to stack over flow if they dont to find the answer. 

Also while I have been watching these youtube tutorials and reading awesome content on Devto because this platform in my opinion covers a wide scope of topics I am trying to learn in one place - I have been reading HeadFirst HTML and CSS which has given me a really good understanding of the basics of coding. I would like to say that looking at all the lesson I have done and read 99% use some form of HTML and CSS which I have been able to understand. If you dont understand the basics its really hard to understand the concepts in my opinion.

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

So every week I will give you all a catch up post and next week I will go over some basic HTML and CSS that is widely used in coding that I have noticed to give all those learning a code a clearer understanding of the work flow of coding.
Day 8: time flies
Tags: productivity, journaling
Published: 2022-04-16 20:41:45

Hi! 
Do you know that feeling when you look back to the past few days and you can't notice anything meaningful you did? that's when you realize how faster time flies.
it happened to me today with this past week I know I was everyday busy at something but I couldn't find results at least presentable ones. so what's happening?
today had to be a lazy one, it's a weekend I almost forgot about today's writing even as much as I can't afford to break my streak but motivation will be a problem as I see it
I don't think I will be able to do anything (code related) with family work scheduled tomorrow which is very important too But I will have to make a plan and a reflection on the past week to prepare for the upcoming one 

let's keep pushing
signing off...
My simple chat app with Flutter
Tags: appwritehack, flutter, webdev, opensource
Published: 2022-04-16 20:39:09

### Overview of My Submission
I create a simple chat app with Flutter for Android and Web Platforms, the app itself used [Appwrite Flutter SDK](https://pub.dev/packages/appwrite) to help me build the app, and with default state management from Flutter itself. 
The app also uses some other packages like Go Router ( because I want to deploy it into a web app ) and Secure Storage ( it helps me with auth ). 
The inspiration behind the idea is I'm working on several projects ( small projects ) that require feature chat, and I know Appwrite has a real-time database on it, then I give it a try to test it out. ( FYI: it was amazing :) )

### Submission Category: 
Web2 Wizards, Mobile Moguls


### Link to Code
{% embed https://github.com/Indieapps-Studio/chat.salingtanya.com %}


### Additional Resources / Info
#### Open source projects that I used
- [Dart-lang](https://github.com/dart-lang)
- [Appwrite](https://github.com/appwrite)
- [Flutter](https://github.com/flutter/flutter)
- [Flutter Secure Storage](https://github.com/mogol/flutter_secure_storage)
- [Flutter SVG](https://github.com/dnfield/flutter_svg)
- [Go Router](https://github.com/csells/go_router)
- [intl](https://github.com/dart-lang/intl)
- [Logger](https://github.com/leisim/logger)

#### Info
- [Demo video on youtube](https://youtu.be/HAntid8njag)
- [Demo video download](https://drive.google.com/file/d/1VG0oWh6cSIEVTkNoZpm-SO2g8BYG0mjP/view?usp=sharing)
- [Screenshot Image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cae0uqqwssm1qbf6qs0.png)
- [Deployed Web Link](https://chat.salingtanya.com/)
Why 🗜️ 👈 is the one of the most powerful css function?
Tags: css, html
Published: 2022-04-16 20:26:45

> Fun fact: 🗜️ is the emoji for clamp according to [emojipedia](https://emojipedia.org/clamp/)

## Lets talk about css `clamp()` function. 

If you have ever wondered how you can define range to a css property e.g minimum, preferred or/and maximum value, then `clamp` is the go to function.

Here is how you can use. 

`clamp(MIN,PREF,MAX)`

You give a minimum value, a preferred value and a maximum value. 

One of the most common use of `clamp()` is in creating fluid/responsive typography. Your `font-size` will change based on the viewport size **without writing any additional media queries**. You can give a minimum/maximum `font-size` but everything in-between will be fluid if you use viewport units like `vw` or `vh`;

Here an example ( try to resize the result tab )

{% codepen https://codepen.io/hunzaboy/pen/BaJGPpv default-tab=css,result%}

You can use clamp function for lengths, percentages, angles etc. You can read about it more [here](https://developer.mozilla.org/en-US/docs/Web/CSS/clamp).

{% embed https://dev.to/hunzaboy %}
Deja de usar el tipo de dato Any en Typescript
Tags: typescript, webdev, beginners
Published: 2022-04-16 20:25:34

Cuando utilizamos `Typescript` es para: tener un constante análisis del código que vamos desarrollando, tener un tipado fuerte, trabajar con un lenguaje de alto nivel, disminuir la cantidad de bugs que solemos generar.

Pero en el transcurso del tiempo en desarrollo de lo que estamos creando, nos encontramos en ocasiones con la necesidad o comodidad de colocar tipos `any` a variables. Y esto desactiva esa funcionalidad tan querida de TS de estar verificando nuestro código; vuelves a estar trabajando con JS puro cuando se trata de esa variable y lo dejas vulnerable a bugs.

Hoy aprendí que es mejor utilizar el type `unknown` a usar `any`. Y este es el por qué...

Cuando declaras una variable de tipo `any`. Puedes asignarle cualquier valor de cualquier tipo. 

```jsx
let anyVar: any;
anyVar = true;
anyVar = undefined;
anyVar = null;
anyVar = 1;
anyVar = 'vale';
anyVar = [];
anyVar = {};
```

*Esa variable será tratada como si de JS puro se tratara.* 

*Ej. Si `anyVar` almacena un texto. Puedes ejecutar un `toUpperCase()` en el momento que desees sin que te salte alguna alerta. (porque estás trabajando con JS tal cuál). El problema es que si deseas ejecutar un método `doSomething()` que es un método inexistente, tampoco saltará un error, porque no se verificará ese código.*

Aquí entra la alternativa a usar para evitar esto y prevenir futuros `bugs`.

### Unknown Type

---

Este tipo de dato también puede inicializarse con datos de cualquier tipo. 

```jsx
let unknownVar: unknown;
unknownVar = true;
unknownVar = undefined;
unknownVar = null;
unknownVar = 1;
unknownVar = 'vale';
unknownVar = [];
unknownVar = {};
```

Sin embargo, cuando quieras tratar un tipo Unknown type con cualquier otro, tendrás que verificarlo primero antes de poder usarlo o te saltarán alertas.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yct7lb62cy4591yamqf9.png)
Ej. `toUpperCase()` es un método de `string`. Pero al ser de tipo `unknown`. No puedes tratarlo como `string` sin antes una verificación de tipo. Cosa que con `any` no pediría, simplemente intentaría ejecutar ese método a ciegas, y a expectativa de que sí sea un `string`. 

Ahora, el método `doSomething` tampoco existe. Por lo que nos marca un error. Cosa que no sucede si fuera de tipo `any`. Intentaría ejecutarlo aunque no existe y eso ocasionaría un error en tiempo de ejecución.

Entonces, ¿cómo ejecutar el método `toUpperCase()`?

Tenemos que verificar que sí es un `string` el tipo de dato que contiene la variable `unknown`

```jsx
if (typeof unknownVar === 'string') {
    unknownVar.toUpperCase();
}
```

Se verifica con la función `typeof` y dentro de ese scope se podrá ejecutar la función, sin problema alguno.

Usar el tipo `unknown` nos ayuda a minimizar futuros errores, siempre obligándonos a verificar que el tipo de dato que contiene dentro esa variable `unknown` es del tipo de dato como queremos tratarla.

Siempre que puedas evitar usar `any`, hazlo.

Notas del Curso de Typescript: Tipos Avanzados y Funciones - @Platzi
Command Query Responsibility Segregation (CQRS)
Tags: ddd, cqrs, microservices, database
Published: 2022-04-16 20:17:38

CQRS standing for command query responsibility segregation. it divides a system actions into commands ( writing ) and queries ( reading ), seeks an even more aggressive separation of concerns splitting the model in two:
- the write model:
 also known as the command model, it performs the writes and takes responsibility for the true domain behavior.
- the read model:
 it takes responsibility of the reads within the application and treats them as something that should be out of the domain model.

every time someone triggers a command to the write model, this performs the write to the desired data store. additionally, it triggers the read model update, in order to display the latest changes on the read model.
this strict separation causes another problem "eventual consistency".
the consistency of the read model is now subject to the commands performed by the write model. in other words, the read model is eventually consistent. that is, every time the write model performs a command, it will pull up a process that will be responsible for updating the read model according to the last updates on the write model.
think about a caching system in front of a web application. every time the database is updated with new information, the data on the cache layer may potentially be invalid, so every time it gets updated, there should be a process that updates the cache system. cache systems are eventually consistent.


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

pros:-
- separating write activity from ready activities allows you to use the best database technology for the task at hand, for example, sql database for writing and a nosql database for reading.
- read activity tends to be more frequent than writing, thus you can reduce response latency by placing read data sources in strategic geolocations for better performance.

cons:-
- supporting the CQRS pattern requires expertise in a variety of database technologies.
- using the CQRS patterns means that more database technologies are required hence there is more inherent cost either in terms of hardware or if a cloud provider is used.
- ensuring data consistency requires special consideration.
- using a large number of databases means more points of failure.
Cloudfront origin failover
Tags: aws, awsbuilders, writing
Published: 2022-04-16 19:13:05

This new article, we are speaking about CloudFront origin failover, it allows us to create a high avaliavility solutions when primary origin is unavailable.

Basic view:


![CloudFront Origin Failover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eom5jb6hzptk8vv4quu8.png)

If you don't have new cloudfront distribution please visit this site:[Amazon Web Site](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-console.html) for creating a new distribution

Then we should create an origin groups, it will be used for rerouting our request in the case that  primary origin will have a failure.

An item important is CloudFront fails over to the secondary origin only when the HTTP method of the viewer request is GET, HEAD, or OPTIONS.

Creating an origin group:

1- Sign in to the AWS Management Console and open the CloudFront console at https://console.aws.amazon.com/cloudfront/v3/home

2- Choose the Origins tab.

3- Make sure the distribution has more than one origin. If it doesn’t, add a second origin.

4- On the Origins tab, in the Origin groups pane, choose Create origin group.

5- Choose the origins for the origin group. After you add origins, use the arrows to set the priority—that is, which origin is primary and which is secondary.

6- Enter a name for the origin group.

7- Choose the HTTP status codes to use as failover criteria. You can choose any combination of the following status codes: 400, 403, 404, 416, 500, 502, 503, or 504. When CloudFront receives a response with one of the status codes that you specify, it fails over to the secondary origin.

8- Create Origin Group

![CreateOriginGroup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gs9xvdjrufogg7qstlm.png)

About origin timeouts and attempts:

By default, CF tries to connect to the primary origin for as long as 30 seconds (3 connection attempts of 10 seconds each) before moving to secondary origin. These values can be changed to timeouts between 1 and 10 seconds, attempts between 1 and 3 times
Linux History Overview
Published: 2022-04-16 18:22:48

Linux is an open source computer operating system, initially developed on and for Intel x86-based personal computers. It has been subsequently ported to an astoundingly long list of other hardware platforms, from tiny embedded appliances to the world's largest supercomputers.

**Linux History**

Linus Torvalds was a student in Helsinki, Finland, in 1991, when he started a project: writing his own operating system kernel. He also collected together and/or developed the other essential ingredients required to construct an entire operating system with his kernel at the center. It wasn't long before this became known as the Linux kernel. 

In 1992, Linux was re-licensed using the General Public License (GPL) by GNU (a project of the Free Software Foundation or FSF, which promotes freely available software), which made it possible to build a worldwide community of developers. By combining the kernel with other system components from the GNU project, numerous other developers created complete systems called Linux distributions in the mid-90’s.

**More About Linux History**
The Linux distributions created in the mid-90s provided the basis for fully free (in the sense of freedom, not zero cost) computing and became a driving force in the open source software movement. In 1998, major companies like IBM and Oracle announced their support for the Linux platform and began major development efforts as well.

Today, Linux powers more than half of the servers on the Internet, the majority of smartphones (via the Android system, which is built on top of Linux), more than 90 percent of the public cloud workload, and all of the world’s most powerful supercomputers.

**Linux Philosophy**
Linux borrows heavily from the well-established UNIX operating system. It was written to be a free and open source system to be used in place of UNIX, which at the time was designed for computers much more powerful than PCs and was quite expensive. Files are stored in a hierarchical filesystem, with the top node of the system being the root or simply "/". Whenever possible, Linux makes its components available via files or objects that look like files. Processes, devices, and network sockets are all represented by file-like objects, and can often be worked with using the same utilities used for regular files. Linux is a fully multitasking (i.e. multiple threads of execution are performed simultaneously), multiuser operating system, with built-in networking and service processes known as daemons in the UNIX world.
Website using Canva in 10 mins
Tags: website, webdev, canva, tutorial
Published: 2022-04-16 18:57:55

You can now create websites like [Demo 1](https://adarshgoyal.my.canva.site/) [Demo 2](https://adarshgoyal.my.canva.site/2) within 10 mins so go ahead

1. Create an account on **[canva](https://www.canva.com/).**

2. Go to 
> Templates > Business > Websites
![canva](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsk4cg2tgs2lmer0cw33.png)

3. Choose a template that suits your requirement.
![canva](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ahm1e4y12vgmuqc0r9to.png)

4. Click on any template you like and then click on **Customize this template** button.
![canva](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j9tbcayl05by98esios9.png)

5. You can edit the template as you want add links and images etc.

6. At last you can click on **Publish as Website** button to deploy the website.
![canva](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m2ryyqzfo4dkd2yudsqa.png)

7. You can either choose the domain provided by canva or can use yours if you have one.
![canva](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6u0ecn0sszogyo6ity2w.png)


You have a ready website in just 10 mins! That's great!
![gif](https://media.giphy.com/media/RGSZqSCNGs5tKWHXiR/giphy.gif)

Follow me [here](https://linktr.ee/adarshgoyal)
Find the second largest number in an unsorted array without any built-in method in JavaScript
Tags: javascript, algorithms, webdev, tutorial
Published: 2022-04-16 18:51:22

I am sure some of you have faced this question in an interview,When asked the same question in a sorted array or if we can use built-in method, this is  definitely an easy question to crack, But this is little tricky without these.


But solution is very simple, first finding maximum number then  to find second maximum  when the array element is maximum we will just skip that element,


```javascript
<script>
    let array = [10, 30, 35, 20, 30, 25, 90, 89];

    function secondLargestNumber(array) {
        let max = 0;
        let secondMax = 0;

        for (let i = 0; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }

        for (let i = 0; i < array.length; i++) {
            if (array[i] > secondMax && array[i] !== max) {
                secondMax = array[i];
            }
        }
        return secondMax;
    }
    console.log(secondLargestNumber(array));
</script>
```
Cinemify Appwrite X Dev hackathon
Tags: appwritehack
Published: 2022-04-16 18:15:37


### Overview of My Submission
Everything was going great. Then Covid hit! Every industry got disrupted but few were affected the most. Theatre was one of them. So we wanted to do something so that we could bring this industry back on track! So we created cinemify


### Submission Category: 

Web2 Wizards

### Link to Code
https://github.com/kevalvavaliya/cinemify
[Note]: # (Our markdown editor supports pretty embeds. Try this syntax: `{% embed link_to_your_repo %}` to share a GitHub repository)


### Additional Resources / Info
#### Screenshots/demo videos
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wmoakfsg1v0jkkld641t.PNG)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yntepw97iije07fp11lv.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pip2yx5ebjn1lhjb7enw.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/eh9hp5ane3wsoqcw86t6.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y27f09zc8nbqteab4pwe.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s2eqz66n517rbpfxilbl.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wpqlpi5iy3ka2uceuq4x.jpg)
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z87gfadpket7jdo1p8zm.jpg)