teleren/devto huggingface dataset:
Help my browser API's stopped working in Angular Universal
Tags: angular
Published: 2021-02-15 10:46:04

Yesterday we looked at introducing [Angular Universal to our Angular application](https://daily-dev-tips.com/posts/converting-a-regular-angular-application-into-angular-universal/).
But if you're like me and used some browser API's for specific tasks, you might be regretting the choice since they stopped working.

No fear, we can make them work!

Some more background as to what's happening, we added Angular Universal, so our application is first being served server-side, and the server has no idea about browser API's.

Hence we need to make him aware or temporarily stop these browser API's from executing on the server-side.

## Converting browser API's in Angular Universal server

So let's introduce a simple browser API in our application to see if it will break.

We'll introduce a simple window command to open a URL.
So let's open `welcome.component.ts` and add the following function.

```js
openLink(): void {
	window.open("https://daily-dev-tips.com", "_blank");
}
```

> Note: This is a very basic example, but it should give you an understanding of what will go wrong and how we can fix it.

Now we need to add a button to the `welcome.component.html` file.

```html
<button (click)="openLink()">Open link</button>
```

Now, this could give us an error as such:

```bash
window is not defined
```

Or something like:

```bash
document is not defined
```

And it makes sense. These are browser API's, so Node has no idea what we are talking about.

We can however, install `domino`, which is a browser for Node.

```bash
npm install domino 
```

And then, we can add the missing elements to our `server.ts` file as such.

```js
const domino = require('domino');
const fs = require('fs');
const path = require('path');

// Mock a temporary browser
const template = fs.readFileSync(path.join("dist/browser", "index.html")).toString();

// Define all the global elements
const window = domino.createWindow(template);
global["window"] = window;
global["document"] = window.document;
global["branch"] = null;
global["object"] = window.object;
```

And there you go, we can now use the native `window` or `document` calls again!

Do note in our example app that the script is so small that you hardly get to see the server-side rendering, so it might not throw errors at runtime.

You can find today's code in the following [GitHub repo](https://github.com/rebelchris/angular-starter-demo/tree/feature/browser-api).

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Svelte, nuevo chico en la oficina
Tags: svelte, javascript, framework
Published: 2021-02-15 10:44:23

## ¿Qué es Svelte?

**Svelte** es un framework para JavaScript, similar a otros frameworks como pueden ser Vue, React o Angular. Sin embargo, a diferencia de estos frameworks populares que necesitan incluir su propia lógica con tu aplicación, en Svelte no se incluye nada (o casi nada) adicional, dejando el código final producido de tu aplicación mucho más ligero.

_Ventajas_ de Svelte:

-   Más rápido que otros frameworks
-   Simplicidad de código
-   Curva de aprendizaje muy baja
-   Reactividad
-   Menor tamaño de la app generada

## Hola Mundo con Svelte 🌍

Svelte utiliza el principio de SFC (Single File Component), lo que significa que el HTML, JS y CSS va todo en un mismo archivo. Esto lo ha popularizado mucho Vue y, en Svelte, podemos ver que es incluso un poco más sencillo.

Así pues... ¿cómo escribiríamos un Hola Mundo con este framework? ¡Fácil!

```html
<script>
	let name = 'World';
</script>

<h1>Hello {name}!</h1>
```

Con este ejemplo tan básico ya se pueden ver las primeras diferencias si lo comparamos, por ejemplo, con React. Fíjate.

```javascript
import React from 'react';

export default () => {
	let name = 'World';
	return <h1>Hello {name}!</h1>;
};
```

Diferencias:

-   No se importa la libraría _svelte_. Al ser compilado, Svelte lo hará por nosotros.
-   Más declarativo al no tener que indicarle que queremos exportar ese componente ni el marcado que queremos renderizar.
-   Separación de conceptos. El marcado y el comportamiento e inicialización de datos están separados.

Queda **más limpio con Svelte**, ¿verdad?

## ¿Quieres añadirle estilos? 🎨

Muy fácil. Recuerda que es SFC. Entonces le añades los estilos que necesites:

```html
<style>
	h1 {
		color: #ff0;
		text-transform: uppercase;
	}
</style>
```

Por lo que el ejemplo completo sería:

```html
<script>
	let name = 'World';
</script>

<h1>Hello {name}!</h1>

<style>
	h1 {
		color: #ff0;
		text-transform: uppercase;
	}
</style>
```

## Conclusiones

Este artículo es sólo la punta del iceberg de lo que es capaz de hacer Svelte. Te recomiendo que visites la [web oficial](https://svelte.dev/) porque, sin duda, dará más de que hablar.

Por cierto, ésta web se ha hecho con Svelte 🤪. Escribiré como la hice, que además, el blog está hecho con documentos _Markdown_.
Launching My New Site (Triple E)!
Tags: showdev, gatsby, webdev
Published: 2021-02-15 10:42:25

I recently launched my new blog called [Triple E](https://www.triplee.tech/). The tagline for Triple E is "Taking the Byte out of Eight Bits" which intends to take light at the fact that learning computing concepts doesn't have to be difficult.

I used Gatsby and ReactJS to build the site, along with AWS to deploy it, Cloudflare to distribute it using their CDN offering and GitHub actions for continuous integration and deployment.

Over the next few months I intend to touch on topics such as cyber security, reverse engineering (my personal favourite), concurrent programming and my experience in the software industry as a junior engineer. I hope you stop by at https://triplee.tech and let me know on this post if you have any feedback!
How to Install Deno on Ubuntu 20.04
Tags: deno, ubuntu, linux, javascript
Published: 2021-02-15 10:37:21

In this article, we’ll explain how to install Deno on Ubuntu 20.04.

Deno is a JavaScript/TypeScript runtime with simple, modern, secure defaults and a great developer experience. It’s built on V8, Rust, and Tokio.

####Features:
Secure by default. No file, network, or environment access (unless explicitly enabled).
Supports TypeScript out of the box.
Ships a single executable (deno).
Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
Has a set of reviewed (audited) standard modules that are guaranteed to work with Deno.
Scripts can be bundled into a single JavaScript file.

####Prerequisites:
A Ubuntu 20.04 installed dedicated server or KVM VPS.
A root user access or normal user with administrative privileges.

<a href="https://www.hostnextra.com/kb/how-to-install-deno-on-ubuntu-20-04/">Install Deno on Ubuntu 20.04</a>

####Step 1 - Keep the server updated
 
 # apt update -y && apt upgrade -y

####Step 2 - Install required package

We need to install unzip as it is required during the installation process.

 # apt install unzip -y

####Step 3 - Install Deno

There is one-line command to install Deno on system.

 # curl -fsSL https://deno.land/x/install/install.sh | sh

Once the installation gets complete, run following command to move deno environment file to /usr/bin directory.

 # mv /root/.deno/bin/deno /usr/bin/

####Step 4 - Verify the installation

We can verify the installation by checking the version using following command:

 # deno --version

Output:

deno 1.7.4 (release, x86_64-unknown-linux-gnu)
v8 9.0.123
typescript 4.1.4

####Step 5 - Run simple command

Try running a simple program using following command:

 # deno run https://deno.land/std/examples/welcome.ts

Or a more complex one:

import { serve } from "https://deno.land/std@0.87.0/http/server.ts";

const s = serve({ port: 8000 });

console.log("http://localhost:8000/");

for await (const req of s) {

req.respond({ body: "Hello World\n" });

}

Here you can find document page

That’s it. The installation has been completed successfully.
Some small Css tips #006
Tags: webdev, css, html, beginners
Published: 2021-02-15 10:36:56

---
title: Some small Css tips #006
published: true
description: I try to tweet a small css tip every day. Here is a collection of some of them.
canonical_url: https://since1979.dev/some-small-css-tips-006/
cover_image: https://since1979.dev/wp-content/uploads/2021/02/css-tips-banner-006.jpg
tags: webdev, css, html, beginners
---

To continue on my [previous post](https://dev.to/vanaf1979/some-small-css-tips-005-2d4) here are some more tweets with little Css tips that might help you in your projects. 

### Css child selector
{% twitter 1349695898377465859 %}
{% codepen https://codepen.io/Since1979/pen/wvzQrPz %}

Css child selector docs: https://developer.mozilla.org/en-US/docs/Web/CSS/Child_combinator

--- 

### :focus with Adjacent Sibling Combinator
{% twitter 1351134940361011202 %}
{% codepen https://codepen.io/Since1979/pen/jOMXgvg %}
focus docs: https://developer.mozilla.org/en-US/docs/Web/CSS/:focus
Adjacent Sibling Combinator docs: https://developer.mozilla.org/en-US/docs/Web/CSS/Adjacent_sibling_combinator

--- 

### Swap out colors using custom properties
{% twitter 1359497193074417664 %}
{% youtube Yl2j_b82zwo %}
Blog post: https://dev.to/vanaf1979/swap-out-text-colors-with-css-custom-properties-4gg

--- 

### Centering using Grid
{% twitter 1351497227894722566 %}

---

### Skew cards
{% twitter 1351869085118832641 %}
{% codepen https://codepen.io/Since1979/pen/QWKoVpx %}
Css skewY() docs: https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function/skewY()

--- 

### Subscribe and Follow

**[Subscribe to my Youtube channel.](https://www.youtube.com/channel/UCeyqA3y26RlnfUSx3ufgFoA)**

**[Follow me on Twitter](https://twitter.com/Vanaf1979)**

**Thanks for reading/watching and stay safe**
What is a good way to create a database for multiple frontend users (one must cannot  touch other users' data)?
Tags: help, database, security, webdev
Published: 2021-02-15 10:27:45

I usually make 

- One `User` table for User metadata
- Some of other tables have `userID` (i.e. user specific)
- Some of others have `userID[]` or pivot table / m2m (i.e. shared between only some users)
- Others doesn't have `userID` at all (shared between all users)

But is this a good or even a **secured** way in the first place?

How does **User management** system work in this case; when there are thousands of **similar** users with very low privileges?
Prevent Whenever scheduled cron jobs to run simultaneously in Rails.
Tags: rails, whenever, cronjob, flock
Published: 2021-02-15 10:23:42

In [Simply.TV](http://simply.tv) we have a number of cronjobs running to surveil some of our internal processes.

These jobs are scheduled to run every single minute using the [whenever gem](https://github.com/javan/whenever) and its `runner` job type.

We have a job scheduled to run every single minute:
```
every 1.minute do
  runner 'Parse.detect_crashed_jobs'
end
```

It's using the `rails runner` command to execute the method `Parse.detect_crashed_jobs` and is doing that every minute.

Unfortunately some times our load rises on the server for various reasons and there's a chance that one of these jobs ends up running for more than a minute. This can result in the same job being scheduled to run simultaneously as the crontab will just keep processing the job every minute.

**Enter `flock`**. `flock` is shipped with most Linux distributions, at least this is tested on Linux Ubuntu 16.4 and upwards.

I've introduced a new job type and template to the `whenever` `config/schedule.rb` file:

```
job_type :runner,  "cd :path && bin/rails runner -e :environment \":task\" :output"
set :job_template, "bash -l -c 'flock -n '\\''/tmp/:task-runner.lockfile'\\'' -c '\\'':job'\\'''"
```

The `job_template` is using the `bash` command exactly like `whenever` defaults, but I've wrapped the actual job execution in a `flock` command. `flock` writes a temp file (using the task as filename) and uses this temp file to track if the job is running already. If it's already running it's skipping execution and exits.
At the same time I'm also changing the `job_type` for runner slightly by wrapping the task in double quotes instead of single quotes which is `whenever`s default value. This is to allow the `job_template` to wrap the flock command in single quotes. It just makes everything easier.

Now whenever a job is scheduled using `whenever` via the `runner` method, the job will be executed through `flock` who'll ensure the same job isn't running twice.
5 Most Interesting JavaScript APIs
Tags: api, javascript, webdev, beginners
Published: 2021-02-15 10:09:57

In this post, I will tell you the 5 Most interesting APIs for your next big project.

## 1. Open Weather Map
![Open Weather Map Image](https://dev-to-uploads.s3.amazonaws.com/i/y3klvjjz9o7bxix8scgd.png)

[OpenWeatherMap](https://openweathermap.org/) is an API that provides weather data including forecasts and historical data. Their API provides access to weather maps and forecasts for multiple cities across the world. It includes almost everything related to Weather.

## 2. API-Football
![API-Football Image](https://dev-to-uploads.s3.amazonaws.com/i/lcms1ej2m4bo260qb2n6.png)

[API-Football](https://www.api-football.com/) API is the most popular RESTful API for football data. It covers over 300 major and minor football leagues. It also gets live scores, pre-match odds, events, line-ups, standings, stats, and all you want to know about Football.

## 3. musiXmatch
![musiXmatch Image](https://dev-to-uploads.s3.amazonaws.com/i/kr5tjswbzmv2w2lq4hl1.png)
[musiXmatch](https://www.musixmatch.com/) is the world’s largest lyrics database with over 50 million active users and over 14 million lyrics. The musiXmatch API grants developers access to this music, album, and lyrics data.

## 4. Rebrandly API (URL Shortener)
![Rebrandly API (URL Shortener) Image](https://dev-to-uploads.s3.amazonaws.com/i/xzonhpj9acydbvc1v54l.png)

The [Rebarndly URL Shortener API](https://developers.rebrandly.com/docs) is a simple API that converts URLs to short links. It’s completely free to use. Just paste a link to cut it!

## 5. Chuck Norris API
![Chuck Norris API Image](https://dev-to-uploads.s3.amazonaws.com/i/5znka3e3uv48h0nc85k8.png)
[Chuck Norris API](https://api.chucknorris.io/) is a hilarious API that provides random jokes and memes about the great American hero 😂 😂.

Thanks For Reading This Article.

Drop the links and about the API in the discussion box below if you have any suggestions.

Don't Forget To Follow Me On [Twitter](https://twitter.com/GarvitMotwani)
Using SQLite in test, and why you should be carefull.
Tags: mariadb, symfony, phpunit, sqlite
Published: 2021-02-15 10:07:22

I recently started using phpunit. Yeah, don't shout at me...! I am just a self taught programmer, and I have to do everything all by myself. Anyway, I become to like testing.

As I am using Symfony a lot, I always watch for tips and tricks. Then I came along this video series of Gary Clarke, which by the way, I respect highly as I am learning much of his videos.

In [this](https://www.youtube.com/watch?v=J46I-cctz7M&t=370s) video he shows a trick of using an in-memory SQLite database for very fast test-runs. After a little investigation, I started to use it as well.

All went fine, until I started to test my (date-driven) validations. In a specific case, I had to test if a new requested date was bigger than a value in the database. This is for preventing overlapping date ranges.

The used validation runs a DQL in the repository, and if records are returned, the dates overlap.

It worked perfectly in my dev environment (MariaDB), but when I started to write the tests, one assertings continually failed, which actually was valid in my manual dev test.

Here's the QueryBuilder logic involved in the validations:
```
 return $this->createQueryBuilder('e')
     ->andWhere('e.asset = :asset')
     ->andWhere('(:requestDateTo > e.fromDate AND :requestDateFrom < e.toDate)')
     ->setParameter('requestDateFrom', $booking->getFromDate())
     ->setParameter('requestDateTo', $booking->getToDate())
     ->setParameter('asset', $booking->getAsset())
     ->getQuery()
     ->execute();
```

Now this worked perfectly fine in my dev environment, but a certain assertion (which I knew had to be right) did fail in test every time.

Long story short, after a lot of debugging I discovered that SQLite (via DQL) is treating a  DateTime variable differently. This translates in SQL like:
```
select * where '2021-01-01 00:00:000000' > date_from;
```
When a database record exist in the database with type = datetype and value is '2021-01-01', this doesn't return a record in MariaDB, but it will in SQLite. It seems SQLite treats '2021-01-01 00:00:000000' > '2021-01-01' as true, while MariaDB treats this as false.

I eventually solved it by forcing the date parameters in the (SQLite) matching formats, which also works in MariaDB. Ended up with:
```
 return $this->createQueryBuilder('e')
     ->andWhere('e.asset = :asset')
     ->andWhere('(:requestDateTo > e.fromDate AND :requestDateFrom < e.toDate)')
     ->setParameter('requestDateFrom', $booking->getFromDate()->format('Y-m-d'))
     ->setParameter('requestDateTo', $booking->getToDate()->format('Y-m-d'))
     ->setParameter('asset', $booking->getAsset())
     ->getQuery()
     ->execute();
```
So, as using SQLite in-memory is a badass trick to quickly run databased involved tests, beware of the quirks that can come up when using a different database typology.
const vs. let
Tags: javascript, webdev
Published: 2021-02-15 10:07:04

In JavaScript, There are three ways of declaring a variable, why though? How are they different? `const` cannot be redeclared. therefore it will have one constant value, and can't be changed. For Example-
```javascript
const number = 1

number = 2
//Gives an error (const cannot be redefined.)
``` 
Whereas `let` can be changed anytime. For example-
```js
let num = 2

num = 5

//Value changes to 5 with no errors.
```
Thanks for reading. 
Hope I helped :D
Recoil parte 1
Tags: reactnative, react, redux, recoil
Published: 2021-02-15 09:55:31

Hoje vamos abordar o básico de **Recoil** (https://recoiljs.org/) . 

E segundo o time do Facebook(criadores): **Recoil** é um conjunto experimental de utilitários para gerenciamento de estado com **React**.

o Recoil é constituido de duas coisas: **Atoms** e **Selectors**

## Atoms
Os átomos são unidades de estado, eles são atualizáveis ​​e assináveis, o que significa que quando um átomo é atualizado, cada componente assinado é renderizado novamente com o novo valor.

```js
import {
    atom
} from 'recoil';

export const counterAtom = atom({
    key: 'counter',
    default: 0
});
```

## Selectors
Um seletor representa uma parte do estado derivado. Você pode pensar no estado derivado como a saída da passagem do estado para uma função pura que modifica o estado fornecido de alguma forma.

```js
import {
    selector
} from 'recoil';

const fahrenheit = atom({
  key: "fahrenheit",
  default: 32
});

const celcius = selector({
  key: "celcius",
  get: ({ get }) => ((get(fahrenheit) - 32) * 5) / 9,
  set: ({ set }, newValue) => set(fahrenheit, (newValue * 9) / 5 + 32)
});
```

a propriedade **_get_** pode acessar os **atoms** ou outros **selectors** e a função pode realizar ações **_async_** e retornar o resultado para os componentes que estão observando.  Se **set** também for fornecido, ele retornará um **RecoilStateobjeto** gravável.

o criador do **Recoil**, **Dave McCabe** disse em um comentário no Hacker News(https://news.ycombinator.com/item?id=23183177)

**"Bem, eu sei que em uma ferramenta vimos um aumento de 20x ou mais em comparação ao uso do Redux. Isso ocorre porque o Redux é O (n) no sentido de que ele tem que perguntar a cada componente conectado se precisa renderizar novamente, enquanto recoil é O (1). "**

É isso, gente. Em breve volto aqui com um tutorial prático usando Recoil :)
The free Gmail SMTP server
Tags: laravel, google, email
Published: 2021-02-15 09:47:30

In this tutorial, I'm going to show you how to configure the Gmail SMTP server with Laravel. Usually, when you want to send emails you have to pay for some service. But using the Gmail server you can do it for free!

## Configuring Laravel

In your Laravel `.env` file, add these values:

```
MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=john@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=john@example.org
MAIL_FROM_NAME="${APP_NAME}"
```

---

[Continue reading](https://www.jeroenvanrensen.nl/blog/gmail-smtp-server)
StoneDeFi Join Hands With StaFi
Published: 2021-02-15 09:27:33

What is Stone?

Stone is a yield aggregation protocol that powers innovative yield generation strategies through liquid PoS staking. Following thorough review and research into the DeFi space, Stone has identified and crafted new farming strategies that tap into PoS farming, starting with staked ETH.
This means that Stone users will soon get exposure to yield opportunities in assets that are multiples the size of the current value locked in DeFi.


BENEFIT OF THE PARTNERSHIP TO THE BOTH COMMUNITY 

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/e9uhw5owh853iswm220u.png)

StaFi and Stone both recognize the potential of interoperability and have been designing new products on substrate, anticipating new assets emerging on Polkadot Ecosystem. “So far over 50% of DOTs are staked and that is worth 10 billion USD with 28 days of unbounding. In addition, parachain auctions will make even more DOTs staked within the system for up to 2 years. There is a strong market need of making the staked DOT liquid.” Mentioned Alex Lam, “Stone aspires to build index products and other interest products on substrate to harness the abundance of cross-chain assets on Polkadot and provide easy access for average users to yield-bearing assets.”

Introduction of rETH onto Stone

rETH is a synthetic derivative asset issued to ETH stakers, that enables instant liquidity for the illiquid Ethereum 2.0 network. rETH can be redeemed from the StaFi platform for the stakers to keep in self-custody, trade on Uniswap or utilize in DeFi protocols to earn a yield.
Stone will support rETH in its farming strategy, providing rETH holders the best yields via liquidity provision and lending activities.
[StaFi is a generation platform of staking derivatives, rETH will solve the controversy between locking period and token dilution until phase1.5 of ETH2, integrated into STONE will bring a new use case for rETH holder, that’s yield farming, which make me excited] Said Liam Young, Founder of StaFi.

Accepting a staked asset in the DeFi space requires close scrutiny over the security of users’ funds and its credibility.
“StaFi is one of the early pioneers to develop the concept of liquid staking. At Stone, we are always actively looking for strong partners to complete the whole ecosystem of DeFi 2.0 — new assets, new strategies and new products. StaFi definitely brings new assets to allow Stone to develop new strategies and new products. We see the partnership going to be a super solid one to set the standards of how liquid staking yield farming shall be done in the future” commented Alex Lam, Project Lead at Stone.