teleren/devto huggingface dataset:
How to compress images on client-side
Tags: javascript, typescript, nextjs, image
Published: 2022-04-12 20:11:43


Optimizing images on the web is a common thing. For [hellocurator](https://www.hellocurator.xyz/), we want to optimize images before the upload, we can do it without servers, on the client-side.

The [Canvas element](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API) let manipulate images with Javascript quite easily.
We can found a lot of [code examples](https://gist.github.com/1isten/0ec8c0bc78171c38a3d8b3cf48430a41) about how to compress image with the Canvas API.

I will use [compressorjs](https://github.com/fengyuanchen/compressorjs), a tiny librarie ([3.8 kB minzipped](https://bundlephobia.com/package/compressorjs@1.1.1)).
Compressor.js uses the Browser's native `HTMLCanvasElement.toBlob()` API to do the compression work, which means it is lossy compression.

There's a [live Demo](https://fengyuanchen.github.io/compressorjs/) to play with it.

## The code

In some case, I like to wrap dependencies in my projects.
So the code looks like:

```JSX
import Compressor from "compressorjs";

export const compress = async (
  file: File,
  quality: number,
  maxHeight: number,
  maxWidth: number,
  convertSize?: number
): Promise<File | Blob> => {
  return await new Promise((resolve, reject) => {
    new Compressor(file, {
      quality,
      maxHeight,
      maxWidth,
      convertSize,
      success: resolve,
      error: reject,
    });
  });
};
```

You can use more options, as provided in the [GitHub repo](https://github.com/fengyuanchen/compressorjs#options).

And, to use it

```JSX
const upload async = (data) => {
  const file = data.image[0];
  const compressedFile = await compress(file, 0.6, 2000, 2000, 1000);
  const imageUploaded = await upload(compressedFile);
  ...
}
```

[GitHub Gist](https://gist.github.com/ibelick/aeb88474d3c74277bd4ccc3dc03271ec)

[Post on my website](https://www.julienthibeaut.xyz/blog/client-side-images-compression)
🐋 DOMAINE.nc : the fun (docker) way... and screenshots contest 🎨
Tags: docker, angular, api, devops
Published: 2022-04-12 20:09:49

## ❔ Intro

A few months ago, during COVID lockdown in New-Caledonia, we decided to build cohesion around a simple yet very efficient innovation project across two teams, challenging us about what we could achieve together within less than 3 days.

> _Our main concern was to show what can be achieved when we have public APIs... and what we could do with [Open Innovation](https://en.wikipedia.org/wiki/Open_innovation)._

## 🐋 Do it the Docker way

The we built and released this project relying on dedicated and public

- Back image : [optnc/domaine-nc-api](https://hub.docker.com/r/optnc/domaine-nc-api)
- Front-end image : [optnc/domaine-nc-front](https://hub.docker.com/r/optnc/domaine-nc-front)

## 💡 Our goals

- 🧪 Create a whole new `UX` on an existing web app
- 🧑‍🤝‍🧑 Collaborate accross two teams and experiment [Github issues](https://github.com/features/issues)
- 😛 Have fun
- 🧑‍🎓 Get knowledge on Github Actions and pure front image building
- 😎 Make something cool together we can enjoy and play with

Then we did this👇

## 🕹️ Run the demo

```shell
cat << EOF > docker-compose.yml
version: "3.7"
services:
  api:
    image: docker.io/optnc/domaine-nc-api:latest
    ports:
      - "8080:8080"
  front:
    links:
      - api
    image: docker.io/optnc/domaine-nc-front:stable
    environment:
      - DNS_BACKEND=api:8080
    ports:
      - "80:80"
EOF

# Run docker-compose
docker-compose up -d
```

Now you're ready to give it a try :

```
# Give it a try 🤩
firefox http://localhost/opt.nc
firefox http://localhost
```

## 🙏🏻 Acknowledgements

This post is dedicated to [Laurent Schaeffer](https://www.linkedin.com/in/laurent-schaeffer-b1174a173/) (aka. [lschaeffer313](https://github.com/lschaeffer313)) and [Michèle Barré](https://www.linkedin.com/in/michelebarre/) (aka. [@mbarre](https://github.com/mbarre)) who where the core developers.

Also I want to thank [Sabrina](https://www.linkedin.com/in/sabrinaverolle/) who did trust us and accepted to invest 3 days of dev of Laurent.

We really enjoyed a lot developing together and role playing.

Now, I'm happy to welcome [Daniel Santos](https://www.linkedin.com/in/daniel-santos-dev-fullstack/) (aka. [@Dougniel](https://github.com/Dougniel)) on the team as front-end and DEVOPS, and of course Michèle as back-end active maintainer.

## 📷 Drop your screenshots 🎁

If you enjoyed this approach, drop a screenshot of your favorite  `.nc` domain in New-Caledonia in the discussion 👇
Tiny react hook to upload files into IPFS
Tags: ipfs, web3, react, javascript
Published: 2022-04-12 20:02:41

For [hellocurator](https://www.hellocurator.xyz/) we want to let users upload an image through our application. The solution of choice for decentralized storing is IPFS.

**IPFS is a distributed system for storing and accessing files, websites, applications, and data.**
I recommend reading the [doc](https://docs.ipfs.io/concepts/what-is-ipfs/) if you want to know more about the concepts.

Since our app is written in Next.js, we will use React with a custom hook. But you can take the functionality with any other JavaScript framework.

## The code

We will use the [ipfs-http-client](https://github.com/ipfs/js-ipfs/tree/master/packages/ipfs-http-client) library.

```terminal
npm i ipfs-http-client
```

```JSX
import { create } from "ipfs-http-client";
import { ImportCandidate } from "ipfs-core-types/src/utils";

const client = create({ url: "https://ipfs.infura.io:5001/api/v0" });

const useIpfs = () => {
  const upload = async (file: ImportCandidate) => {
    try {
      const added = await client.add(file);
      const url = `https://ipfs.infura.io/ipfs/${added.path}`;

      return url;
    } catch (error) {
      console.error("Error uploading file: ", error);
    }
  };

  return {
    upload,
  };
};

export default useIpfs;
```

The basic functionality takes 3 lines of code:

- create a client with a gateway. There are different types of [gateway](https://docs.ipfs.io/concepts/ipfs-gateway/#overview) for IFPS. For our example, we use a free one by infura.io, but you can use other services or create your own.
- Import a file or data into IPFS
- Get the path of the stored file

You can use this hook for storing anything you want on IPFS.

```JSX
const onSubmit: SubmitHandler<FormValues> = async (data) => {
  const image = data.image[0];

  /* upload an image */
  const imageUrl = await upload(image);

  /* upload a file */
  const fileUrl = await upload(data.file);

  /* upload a text */
  const textUrl = await upload("hello!");

  /* upload a JSON */
  const jsonUrl = await upload(
      JSON.stringify({
      title: "hellocurator",
      description: "We’re happy to introduce hellocurator",
    })
  );

  /* etc. */
};
```

[GitHub Gist](https://gist.github.com/ibelick/b0d06dd5b3ef32f431e930f1bf4b3e78)

[Post on my website](https://www.julienthibeaut.xyz/blog/react-hook-upload-files-IPFS)
Calling all indie game developers, come show off your games! 👾
Tags: gamedev, discuss, showdev
Published: 2022-04-12 19:59:49

Have you developed an indie game or are possibly developing an indie game? I'd love to hear about it! 

Drop a comment below linking to one of your games — or even better, drop a link to a post that you wrote about developing the game!

Not an indie game developer, but still wanna play? No sweat, drop a link to your favorite indie game or indie game related post. 👾
Two css technique to make image responsive.
Published: 2022-04-12 19:59:04

Image is a basic content of a website. Unlike text, browser don't wrap image inside it's container or element. If an image size is wider than it's parent container, it will overflow from it's container and can cause issue like vertical scrollbar. I remember back then when I was learning css I hated it so much when I saw vertical scrollbar appeared on my screen.

So today I will show you two bulletproof technique to make image responsive and prevent overflow from it's container.

### 1. Using css property "max-inline-size"
"max-inline-size" render itself inside it's container and prevent overflow.

Example:

```html
 <div class="img-container">
	 <img src="#" />
 </div>
```

```css
.img-container {
	width: 200px;
	height: 200px;
	border: 1px solid black;
}

img {
	max-inline-size: 100%;
	block-size: auto;
}
```

Here property "block-size: auto" used to maintaining the image aspect ratio. If you want to change the aspect ratio of an image you can use css property "aspect-ratio". If the image rendered stretched you can use object-fit.

```css
img {
	max-inline-size: 100%;
	block-size: auto;
	aspect-ratio: "2/1";
	object-fit: cover;
}
```

### 2. The Netflix way!
You can use padding technique to maintain image aspect ratio. Netflix use this technique. It's work on every old browser including IE :3 .

Example:

```html
<div class="img-container">
	<div class="wrapper">
		<img src="http://placehold.jp/1920x1080.png" />
	</div>
</div>
```

```css
.img-container {
	width: 200px;
	height: 0;
}

.wrapper {
	position: relative;
	padding-top: 56.25%;
}

img {
	position: absolute;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
}
```

#### Core Concept
Do you know what's the logic behind this?
Let's see we defined our parent element width 200px and height 0. Look at the image source. The original width and height of this image is 1920x1080. The aspect ratio of this image is 16:9. So we want to fit this image to our parent div with img-container class and as well as we want to maintain the aspect ratio of this image. How we will do that?
The aspect ratio is 16:9 (width:height). If we divide height from width 9/16 we will get 0.5625 = 56.25%. Now if we put that value in padding top it will work as image height! Do you get the idea?

Still not?
Let's try another example with 1:1 aspect ratio. If we have an image about 500x500 size which aspect ratio is 1:1. So if we define width: 500px in parent element. The padding-top will be 1/1 = 1 = 100%. 100% padding-top of parent element width will be 500px! Which is height of our image. So 500x500 a perfect square and we can maintain this image aspect ratio.

**Remember padding-top calculated from parent width.**

That's it. This is my first ever blog post. So please forgive, if I make any mistake. If you don't understand something let me know in the comment section.

💻👻 Thanks For Reading.
An easy way to automate running Rails test (or any command) on file changes
Tags: ruby, rails, testing
Published: 2022-04-12 19:52:15

To my dismay, I realised today while going through unit testing in _Agile Web Development with Rails 6 by Ruby, Copeland & Thomas_ that the Rails CLI does not ship with a `--watch` option.

It seems like a pretty jarring piece of missing functionality and I still don't know why it's not built into the CLI, so I [posted a question in the Rails forum](https://discuss.rubyonrails.org/t/why-does-rails-cli-not-come-with-watch-option/80435) to ask for context, for a start. Let's see how that goes.

## Jest CLI has it out of the box

Having used Jest CLI for running tests before, I was used to being able to do this:

```
$ jest --watchAll
```

... and have the CLI handle watching files for changes and re-running relevant tests.

But as I've had to use Rails more recently, and I dug into why this was missing from the Rails CLI, I realised that "running relevant tests based on file changes" is actually quite complex. For example, if I changed a method, how should the watcher communicate to the test runner about which tests to re-run (rather than, say, re-running _all_ tests)?

But that's a bit outside of the scope of this post. I brought it up just as a way of doing a head-nod to the complexity behind something like this.

## Enter `entr`

Anyway, as I sat at my desk thinking about how to make my TDD-ish (test driven development) workflow easier, I realised that **perhaps 50 percent of the usefulness of an automated test runner comes from re-running all tests in a particular test file if it has just been saved**.

For that, I learned today that there's a nice command line package called `entr` that you can install with `homebrew` (macOS).

Here's how I used it to re-run rails tests based on changes to any file in the /test directory:

```
$ cd rails-app
$ find ./test -name '*.rb' | entr -s 'rails test'
```

This will re-run all tests whenever any test file has been re-saved (regardless of whether an actual modification was made). A great first step!

## There are gems for that

Just a quick note here that what I mentioned is just one of many ways to achieve the same thing. In fact, what I wrote is less convenient if you need to have this available to everyone in a team rather than just for yourself.

There's a [video](http://railscasts.com/episodes/264-guard) dated back to 2011 posted in RailsCast about how to use the `guard` gem to watch files and run tests. This is probably a better approach if you want to implement test runner automation for a team. There is a boatload of other gems that have slightly different implementations but provide similar functionality - you can see them [here](https://www.ruby-toolbox.com/categories/continuous_testing) on ruby-toolbox.
Get Started with JavaScript Promises (in Under 2 Minutes)
Tags: javascript, webdev, beginners, programming
Published: 2022-04-12 19:48:48


## Intro
Welcome to an extremely brief introduction to JavaScript Promises. After getting to grips with Promises myself I thought I would share the essentials that I needed to put them into practice.

---

## Basics of JS Promises
Promises can be defined with the following recipe:

```
function function1 () {
  return new Promise ((resolve, reject) => {
    try {
      doSomeStuff()
      resolve()
    } catch (err) {
      reject(err) 
    }
  })
}
```

`resolve()` should be called if the operation associated with the Promise has been successful. `reject()` should be called if the Promise could not be **resolved**, maybe there was some sort of problem when trying to perform the associated operation.

The caller function then has the option to asynchronously wait for the Promise to resolve using `await` or the `then()` method of Promises. To use `await`, declare the entire function as asynchronous using the `async` keyword. Here are examples of both:

```
async function callerFunc1() {
  // Use 'await'
  await function1()
}
  
function callerFunc2() {
  // Use '.then()'
  function1().then(() => {
    doSomethingAfterwards() 
  })
}
```

Two extra things about `Promise.then()`. Firstly, we can chain `.then()` statements together to make something that operates like so:

```
function callerFunc3() {
  function1.then(() => {
    console.log('First thing finished')
  }).then(() => {
    console.log('Second thing finished')
  })
}
```

Secondly, `then()` can actually take two arguments: one in case the Promise **resolves** and another to handle the case when the Promise **rejects**.

```
function callerFunc4() {
  function1.then(() => {
    console.log('Everything went to plan!')
  }, () => {
    console.log('The Promise rejected :(')
  })
}
```

If you want to see these examples in action, check out [this StackBlitz](https://stackblitz.com/edit/js-mkctvv?devToolsHeight=33&file=index.js) 

---

## Conclusion
Hopefully you found this helpful, to get updates as soon as I release helpful guides such as this follow me on [Twitter](https://twitter.com/_adamjhawley) or [Dev](https://dev.to/adamjhawley)!
Living with WFH.. 2 years later (a review)🏠
Tags: discuss
Published: 2022-04-12 19:41:30

This is probably an unpopular opinion but, working from home, all the time it's the best thing that ever happened to me.

# Why you no like me? 🙄
It's not you it's me:

## Meetings 🕳️
It's not that I don't like people it's just that being able to jump in out of meetings on a call is so so so much faster.
I usually have 10 mins of opinion in any given meeting, maybe 10 mins of listening and 10 mins of not listening. Or even better solving the problems as they are being discussed and looking like some sort of time management traveling super duper.. person

## I lost my train of thought 🚆
But don't worry, now your at home you can drop your laptop on the floor and go play trains then come back a little later! Genius 👍

## Do you actually do any work?
Absolutely, now there is no work life, home life balance I can just pretend there is and cry myself to sleep at night worrying about taking out the bins and also do I have a race condition to fix?

## don't your kids distract you
No, work distracts me from them! Save me

All in all I love it it's a winner, what about you, let me know in the comments below BFFL?! (I'm so lonely)
One of these two apple.com domains is fake
Tags: security, domainnames
Published: 2022-04-12 19:36:15

Five years ago, a [security researcher](https://www.xudongz.com/blog/2017/idn-phishing/) registered a fake domain that is indistinguishable from apple.com. Chrome released a patch so people would be able to tell the difference. After an intense discussion and careful consideration, Firefox decided not to fix it. That's why the current version of Firefox still displays both domain as identical. What happened?

{% youtube 0UseDf9rMH0 %}

If you are reading this - and I have a hunch that you are - you know the basic Latin alphabet. What you might not think about every day is that lots of different alphabets are used across the world. Even within the Latin script, there are different alphabet flavors containing characters like ü, à, î, ł or ñ. Similarly, there is the Cyrillic script. It also has a lot of regional variations.

Latin and Cyrillic have some overlap. In some fonts, the lowercase Latin A happens to look exactly like the lowercase Cyrillic A. Same with the lowercase Latin P and the lowercase Cyrillic R. That's how I can write apple.com and аррӏе.com with different characters, and have them look identical in some fonts.

![Analysis of the characters in the Cyrillic apple.com domain name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqhb8r7s71tcfqebafvy.png)

To help people recognize the difference, Chrome wrote a patch. Since then, domain names under Latin-character TLDs that consist only of Cyrillic lookalike characters now look different than the Latin domain. It now renders the fake apple.com domain name as `xn--80ak6aa92e.com`.

Firefox took a stance against the fix. Their reasoning is explained in the video, and they do have a point. The gist of it is that they want to treat Latin and Cyrillic as equals, and automatically treating either the Latin or Cyrillic variant as suspicious would go against that. They also argue that it's the .com registry's job to prevent the registration of lookalike domain names, which the registry isn't doing. Plus, Firefox still has Phishing Protection as a final line of defense.

So that's why five years later, you can still access the fake domain name in Firefox. Meanwhile, the fake domain hasn't been claimed by Apple, nor has it been taken offline by its domain registrar. Presumably, it's because it isn't actively trying to scam anyone. But it serves as a reminder that we have a lot of alphabets on this planet and that sometimes, this causes sticky situations.
Configuration ESLint and Prettier in a project React.
Tags: javascript, react, prettier, eslint
Published: 2022-04-12 19:18:12

**ESLINT**
1.- Install ESLint

```
npm install eslint --save-dev
```
2.- Initialize ESLint

```
npx eslint --init 
```
3.- answer questions as seen in the following image for configuration
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/juftmnu5oqbmb2sn4ma9.png)
4.- To fix a project you use

```
npx eslint . --fix
```
**PRETTIER**
1.- Install configuration prettier and eslint

```
npm i eslint-config-prettier -D
```
2.- Install prettier

```
npm i prettier -D  
```
3.- Create file .prettierrc.json and inside this file write your configuration..
4.- In configuration .JSON write

```
"editor.formatOnPaste": true,
"editor.formatOnSave": true,
"editor.formatOnType": true,
"prettier.eslintIntegration": true
```
Paracetamol.js💊| #99: Explica este código JavaScript
Tags: javascript, spanish, webdev, beginners
Published: 2022-04-12 19:16:02

## **<center>Explica este código JavaScript</center>**

```js
console.log(([] || {}) && (undefined ?? "") || null);
console.log(0 || false || Symbol("hola") || 2n);
console.log(typeof (undefined || null || 0 || ("0" ?? 0)));
console.log((() => "hola")() || (false && true));
```

A. `{}`, `2n`, `number`, `false`
B. `undefined`, `Symbol("hola")`, `string`, `"hola"`
C. `null`, `Symbol("hola")`, `string`, `"hola"`
D. `null`, `0`, `number`, `true`

Respuesta en el primer comentario

---

Respuesta: 
C. `null`, `Symbol("hola")`, `string`, `"hola"`

El operador `||` solo se ejecuta si el primer operando es un valor `falsy`.
El operador `&&` solo se ejecuta si el primer operando es un valor `truthy`.
El oeprador `??` solo se ejecuta si el primer operando es `null` o `undefined`

Dicho todo esto y conociendo los [valores truthy](https://developer.mozilla.org/es/docs/Glossary/Truthy) y los [valores falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) no debería costarte llegar a que la respuesta correcta es C.
Hello fellow writers!
Tags: firstpost, beginners
Published: 2022-04-12 19:12:20

After a huge debate with myself on where to start the blog, either self-hosted on a CMS or without a CMS, WYSIWYG or a Markdown based, WordPress or Ghost.... Finally decided to just go on dev.to, enough for my needs, and lets explore the field first rather than going into the specifics.

So hello Dev community! I'll be writing posts on my interests, my learnings and my failures (the better learnings), so stay tuned for the joy ride!

PS: Oh I realized I had a Hacktoberfest 2021 badge associated with this account (:
Webinar on April 27th
Tags: programming, devops, testing, productivity
Published: 2022-04-12 19:00:28

**Topic:** "Ephemeral Environments: E2E Testing Before Merge" 

Follow this registration link if you'd like to attend: https://us06web.zoom.us/webinar/register/2216497880926/WN_CLMIJsawQDKLSupJGciJpw

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

**Discover...**
- An effective way to shorten feedback loops between developers & testers
- How to eliminate surprise blockers when attempting to deploy.
- How ephemeral environments can help accelerate your existing E2E tests by running them on every pull request.

We’ll be joined by special guest [Amrisha Sinha](https://www.linkedin.com/in/amrishasinha/) of [MaestroQA](https://www.maestroqa.com/), to hear how her team has successfully implemented E2E testing with [CircleCI](https://circleci.com/) + [Shipyard](https://shipyard.build/).

If you’re interested in this topic, but can't make the session - no need to worry! 

Just [register](https://us06web.zoom.us/webinar/register/2216497880926/WN_CLMIJsawQDKLSupJGciJpw) and we’ll email you a link to the recording after the live session has ended