teleren/devto huggingface dataset:
Bug of the day with module variable
Tags: javascript, webdev, showdev, coding
Published: 2020-04-01 13:32:19

---
title: Bug of the day with module variable
published: true
description: Set value for module variable bug of the day
tags: #javascript,#webdev,#showdev,#coding
---
Let´s see code bellow:

```javascript
// Item.js
let active = null;

const setActive = item => {
  active = item;
}

export const activateItem = item => {
  active = setActive(item);
}

```
Where´s the problem? After several hours of debugging of our js code for activating modules. I found out this bug in similar code as above.
Variable active is global for module. If you will call function activateItem from outside of module, the value of active is undefined. Why? Method setAcive returns nothing:

```javascript

NOTHING = undefined; // :D

```

Let's go to repair this situation:

```javascript
// Item.js
let active = null;

const setActive = item => {
  active = item;
}

export const activateItem = item => {
  setActive(item);
}

```
COVID-19: How to keep in touch with my colleagues
Tags: productivity, remote, beginners, discuss
Published: 2020-04-01 13:06:20

---
title: COVID-19: How to keep in touch with my colleagues
published: true
description:
tags: #productivity #remote #beginners #discuss
---

Like a lot of you, I have to stay at home due to **COVID-19**. It is strictly forbidden to go to the office for a few weeks in France :fr:. 

In this particular circumstance, my company had to adapt. Few devs work often remotely but not all the company at the same time. As we are all far away from each other, we're trying to keep close virtually despite the distance.

We've taken actions to be still productive and keep the good atmosphere and preserve our team culture in the company.

24H live conversation :timer_clock:
-----------
The first thing we've put in place is a 24H live conversation on Hangouts. It is like the coffee machine at the office:  you go in, talk about everything with anyone available and then back to work. 
I like to go on the call in the morning with my coffee cup. We can talk about the weekend or the last Netflix series. 

It may seem useless but this little move allows anyone to keep in touch with its peers and avoid isolation. Foreign workmates are often on it and I think it's a big help for them to know they **are not alone**!

Daily standup :memo:
-----------
For each team, we're doing a daily meeting to know what my colleagues worked on yesterday and will work today and I can be informed if there is any blocker. That helps to keep the productivity high in the team so we know that **everybody is pushing hard** to keep a strong velocity.

E-Beers :beers:
-----------
Every Thursday, we drink a beer / cocktail / tea cup all together on Zoom and update each other situations. Sometimes we can see some of our co-worker's baby faces :baby: appear in the background. It's a good time to talk with my workmate about everything except work. It is a good time to **relax** and **be proud of the work we have accomplished** this week. 

Calls :phone:
-----------
When I need an urgent information or just want to talk about a specific topic, I simply take my phone and call my colleague, instead of writing conversation. This gives a **human interaction** that is missed on Slack. I feel less alone and I always keep in touch with my colleagues who are, more often than not, my friends too.

Conclusion
-----------

During this difficult period, **communication** is key. If you want to avoid isolation in your company, feel productive and keep human interactivity, you have to put in place some solution for your team. **Be there for each other** :handshake:

How do you handle this distance in your team and how do you stay productive remotely? Tell us in the comments.

PS: I want to say thank you to [Hivebrite](https://hivebrite.com/) which is doing everything they can to keep a good atmosphere in the company.

_If you want to share some good practices, you can DM me on [Twitter](https://twitter.com/MPefi)_
Inefficient efficiency
Tags: todayilearned, api, programming, coding
Published: 2020-04-01 13:00:14

*TL;DR notes from articles I read today.*

### [Inefficient efficiency](https://bit.ly/3dKhtaS)

- Latency (measured in time units) is the time between a stimulus and a response, while throughput (measured in deliveries per time unit) is the rate at which the system meets its goals.
- Sometimes latency and throughput interfere with each other. Do you field a request and respond before taking the next request (low latency for the first customer but overall lower throughput), or do you accept the second request while processing the first for higher throughput?
- You make latency/throughput tradeoffs every day and most of us are biased towards throughput. For example - you carefully plan all foreseeable architectural improvements instead of initiating the first profitable change you come across.
- Instead, you should optimize for latency. For example - if preferences are likely to change between requests (high rate of change), so you can adapt, which is less wasteful.
- To decide between throughput and latency, consider the cost of delay, whether you might learn something that changes your approach subsequently, and whether external factors might force a new approach. 

*[Full post here](https://bit.ly/3dKhtaS), 4 mins read*

---

### [Tips on API monitoring](https://bit.ly/2UQe0Pf)

- Track your functional uptime with comprehensive, end-to-end testing for both functionality and performance. Simple ping tests are usually not enough to meet your service level agreements (SLAs).
- Since 95% of API vulnerabilities are due to human error, add monitoring at 5-minute intervals for breaches and downtime. Integrate automated testing into every step of your CI/CD pipeline to filter out human errors and make sure you have load-testing capabilities too. 
- But you should beware of 
    - tools that perform ‘synthetic testing’ and cannot reproduce actual consumer flows.
    - tools that use third-party clouds, adding another layer of insecurity to your API (have internal APIs use on-premise tools instead).
    - having separate testing and monitoring solutions. 
    - tests that are not detailed enough for intelligent results.

*[Full post here](https://bit.ly/2UQe0Pf), 4 mins read*

---

*[Get these notes directly in your inbox every weekday by signing up for my newsletter, in.snippets().](https://mailchi.mp/appsmith/insnippets?utm_source=devto&utm_medium=post08&utm_campaign=is)*
Learning HTML, CSS, and JS through Frontend Mentor - Challenge 1
Tags: beginners, webdev, css, html
Published: 2020-04-01 12:48:14

I've been working on developerHabits - a Youtube channel for developers interested in growth mindset and tech tutorials - for about a month now.

Now I decided it's time to start doing some coding videos. The initial plan is to do Frontend Mentor(https://www.frontendmentor.io/) challenges. You get to see how I complete the whole challenge in one video.

{%youtube kfcyiY_4LNo %}

This clip is about solving the Four Card feature section challenge.
🔴 Final solution: https://www.frontendmentor.io/solutions/four-card-feature-section-MSw7ST-Fm

Also, follow me in
👉 Dev.to: https://dev.to/kethmars
👉 IG: https://www.instagram.com/developerhabits
How to automate website creation with minimal coding?
Tags: beginners, discuss, webdev
Published: 2020-04-01 12:02:48

Hi everyone,

I am trying to figure out how to automate website creation with little or no-code. I have some experience with WordPress, and recently I came across JAMstack and static site generators used with *modern* CMS. My coding experience is limited so I would prefer something that I could get up and running with minimal coding. 

If I understood correctly, I have to use a CMS to handle data, a SSG to create the HTML, and of course hosting to serve the page on web. But things still don't click in my head. How to pick the tech (HUGO, Strapi, Gatsby, Publii etc), how to automate the process, how to feed the system with themes, what else is needed if any...

Can you please explain/show broadly or in detail how such system look like? Diagrams, text, a url to where this is already explained... Everything is welcomed and appreciated. 

Thank you.
NPM CLI (Covid-19 Special)
Tags: npm, covid19, javascript
Published: 2020-04-01 12:42:22

> Npm cli built using javascript.You can also build your own now.
<hr>
### Fork or Clone the repository

    git clone https://github.com/UmarGit/Covid-19-CLI.git
<hr>
### Install the project globally

    npm install -g .
<hr>
### Now Run the Project from Command Prompt

    covid-19
<hr>
### Check Cases of a Country(like for Pakistan its country code is 'PK')

    covid-19 -n PK
<hr>
### Check Cases of other Countries

    covid-19 -n PK #Pakistan
    covid-19 -n US #United States
    covid-19 -n IF #Italy
    covid-19 -n AF #Afghanistan
    covid-19 -n CN #China

## Conclusion

> You can edit the index.js file and package.json as per your needs and make your own cli.How easy it was !.Please leave a star if you like this !
The RxJS concatenation strategies, pt 4/4
Tags: javascript, rxjs
Published: 2020-04-01 12:41:43

Welcome to the last part of this small journey regarding the RxJS concatenation strategies.

Before getting further into reading, ensure to have read the previous articles, to have a better understanding of the context.

[Part 1 concatMap strategy](https://dev.to/e4r/the-rxjs-concatenation-strategies-pt-1-4-394g)

[Part 2 mergeMap strategy](https://dev.to/e4r/the-rxjs-concatenation-strategies-pt-2-4-37de)

[Part 3 switchMap strategy](https://dev.to/e4r/the-rxjs-concatenation-strategies-pt-3-4-25b0)

Today we’ll cover the last one, the **exhaustMap** strategy. Have a glance to its marble table:

![exhaustMap marble table](https://miro.medium.com/max/1400/1*HMR6XMGlq8gWj8qlaCvfsg.png)

Here we have our “usual” streams of events, we assume that the first one above is a stream of events emitted by an imaginary user, which types in a as much imaginary text input the values “1” , “3”, and “5”, each value separated by a certain amount of time, let’s say that the value “3” is typed one second and a half later than “1”, and the value “5” is typed just one second later than “3”.

Then, at each value typed, our RxJS operator exhaustMap creates, concatenates and schedules 3 different events one each half a second, which value is the value typed in multiplied by 10, and is finally emitted as a GET request.

So, if a user types “1”, there will be three HTTP GET request one each half a second:

[GET] /endpoint/10 at 0s

[GET] /endpoint/10 at 0.5s

[GET] /endpoint/10 at 1.0s

Now, let’s say that the user, after 1.5 seconds, types “3” in our text box: our RxJS operator exhaustMap concatenates the three HTTP calls and schedules them as previously said, but after about a second, the user types “5”.

Differently from other operators, in this case we’ll have the expected three HTTP calls [GET] /endpoint/50 ignored, since the previous event hasn’t finished yet.

This could be particularly useful for example in payments forms: we absolutely don’t want that the user clicks multiple times on our payment button and pays again and again (do we? 😛).

Once the user clicks on the button, the exhaustMap simply ignores all the other events emitted if the ongoing event hasn’t finished yet.

I hope that this operator is a bit more clearer now :)

Thanks for reading!
Why do websites take so long to load?
Tags: webperf, webdev, loadingtime, websitespeed
Published: 2020-04-01 12:33:57

Firstly you should check your **website performance**. You can use [Google Page Insights](https://developers.google.com/speed/pagespeed/insights/). ![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kzgyhmwo28qxlzfe9md1.PNG)It presents a report related to your website. You can examine this error attentively. Then you start to solve this problem. Generally, image size or format causes this slow loading time. You should optimize your image, maybe use [CDN](https://image4.io/en/blog/what-is-multi-cdn/?utm_source=Devto&utm_medium=post&utm_campaign=growth&utm_term=m5&utm_content=w14_2020). [image4io](https://image4.io/en/?utm_source=Devto&utm_medium=post&utm_campaign=growth&utm_term=m5&utm_content=w14_2020) can solve these problems. Because image4io is an image optimizer, using CDN, storage management. After you integrate to image4io, your website speed up seriously. [Try it!](https://console.image4.io/Auth/SignUp?_ga=2.101049409.1128465940.1585744239-1292144703.1585744239/?utm_source=Devto&utm_medium=post&utm_campaign=growth&utm_term=m5&utm_content=w14_2020)
Daily Developer Jokes - Wednesday, Apr 1, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-04-01 12:00:26

---
title: "Daily Developer Jokes - Wednesday, Apr 1, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Wednesday%2C%20Apr%201%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e125964dfaa7.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ What is React's favorite movie genre?

___A:___ Suspense
 -->
Discuss: React component libraries compatible with emotion and TypeScript?
Tags: discuss, react, webdev, typescript
Published: 2020-04-01 11:53:10

Hello,
I'm seeking a React component library that can be used with TypeScript, I can control the styles by `emotion`'s css prop (or something similar), and is supporting theming.

I found the followings:

* [Material UI](https://material-ui.com/)
* [Rebass](https://rebassjs.org/)
* [Chakra UI](https://chakra-ui.com/)
* [Theme UI](https://theme-ui.com/) (This seems not production-ready yet though)
* [Grommet](https://v2.grommet.io/) (emotion is not supported yet though)

Do you have any other alternatives, or any suggestions?
Can you tell me what library you like, and what case you prefer it for?

I've been using [Sancho UI](https://sancho-ui.com/), but it recently seems inactive and I'm looking for an alternative...
SameSite cookies with Apache
Tags: web
Published: 2020-04-01 15:58:31

---
title: SameSite cookies with Apache
published: true
date: 2020-04-01 11:47:00 UTC
tags: Web
canonical_url: https://www.petefreitag.com/item/894.cfm
---

Almost two years ago I wrote about how you can enable [SameSite cookies with IIS](https://www.petefreitag.com/item/850.cfm) on cookies that do not have the ability to be written as SameSite. Today I was helping a client on Apache do the same thing, here's how we can add `SameSite=lax` to a `JSESSIONID` cookie for example:

```
Header edit Set-Cookie ^(JSESSIONID.\*)$ $1;SameSite=lax
```

But suppose you just wanted to make all cookies set by your web app SameSite, you can just do this:

```
Header edit Set-Cookie ^(.\*)$ $1;SameSite=lax
```

This works by appending `;SameSite=lax` to the end of all `Set-Cookie` http response headers.
Web scraping and an easy way to avoid getting blocked. (What should I do if I were that webmaster?)
Tags: webdev, discuss, node, javascript
Published: 2020-04-01 11:46:38

I found [this guide](https://www.scrapehero.com/how-to-prevent-getting-blacklisted-while-scraping/) a while later after I have found the solution.

TL;DR

- Use website's public API, if exists.
- Read `https://website.com/robots.txt`
- Rate limiting. Do not try to DoS (Denial of Service) the website.
- Use a fake [User Agent](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent) by setting request header, or use a headless browser, like Puppeteer, or Selenium.

```js
await Promise.all(vocabs.map(async (v, i) => {
  await new Promise(resolve => setTimeout(resolve, i * 1000))  // Sleep for i seconds.
  await axios.get('https://website.com/search.php', {
    params: {
      q: v
    },
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0'
    }
  }).then(r => {
    const $ = cheerio.load(r.data)
    // ...
  })
}))
```

Interestingly, CORS cannot prevent website scraping from other places than `<script>` tags. Why do we have CORS by default, again?
EXPLORING REDIS AND IT’S DATATYPES
Published: 2020-04-01 11:30:39

Link: https://blog.joshsoftware.com/2018/03/28/exploring-redis-and-its-datatypes/

Today Performance is what that comes first, when we developers try to develop web services. One of the issue is that, when a web service tries to interact with database, in order to get the result it may take time depending on the number of records.
A better way to turn strings into arrays!
Tags: javascript, array, algorithms, react
Published: 2020-04-01 10:39:33

---
title: A better way to turn strings into arrays!
published: true
description: 
tags: JavaScript, array, algorithms, React
---

Converting a string to an array is quite a common occurrence for most developers. But I recently found a way to do this that is more concise and readable.

# How most Javascript developers turn their strings into an array:

```
const name = "Brandon"
name.split("")
// Result: ["B", "r", "a", "n", "d", "o", "n"]
```

This works perfectly fine, and is actually the way I see 90%+ of developers covert their strings into an array.  
The downside for me is, it's not extremely readable for people who don't know the ins and outs of the Array.split method.

# The better way to turn your strings into arrays.
```
const name = "Brandon"
Array.from(name)
// Result: ["B", "r", "a", "n", "d", "o", "n"]
```


This produces the exact same result as Array.split(""), but here your code reads like a book. Array.from(your_string) is exactly what you want to do.

# Performance
I did do some research on performance differences between these two ways of converting strings to an array. 
I only found one non official blog saying that Array.split is considerably faster than Array.from, however I would be interested to read more tests on this before I'm convinced. If you can provide more info on this topic please leave a comment below. 

## Fun Fact
Another nice thing you can do is turn a Node List into an array, using Array.from.
```
const pTags = Array.from(document.querySelectorAll('p'));
```

With this, you can create a regular array instead of a Node List when using querySelectorAll.
Where do you store your IMPORTANT passwords?
Tags: productivity, discuss, security
Published: 2020-04-01 10:18:55

Remembering your passwords can be a tricky thing to do these days. 

So, we should have a password manager that can keep our passwords safe.

For this solution, we have compiled the list of the best Password Managers:

https://hostingpill.com/best-password-managers/

Those are 100%, secure password managers. 

Please let me know which password manager are you using?
1.0.0 でも master でも動く mrbgem の書き方
Tags: mruby
Published: 2020-04-01 10:12:28

---
title: 1.0.0 でも master でも動く mrbgem の書き方
published: true
description: 
tags: mruby
---

**注: この記事は 2014/03 に書いたものです。**

mruby の[安定版1.0.0](http://forum.mruby.org/download/index.html)と[最新版](https://github.com/mruby/mruby)のどちらでも動作する mrbgem の書き方を紹介します。以下では、安定版のことを 1.0.0、最新版のことを master と呼びます。

# C 言語 API の変更

## mrb_str_cat_lit の追加
`mrb_str_cat_lit` の動作は `mrb_str_cat_cstr` と同じです。strlen(3) 一回分速いだけの違いしかありませんから、`mrb_str_cat_cstr` を使っておけば間違いありません。

## mrb_const_defined_at の引数の型の変更

返り値と第二引数の型が異なります。第二引数の型は `mrb_value` と `struct RClass *` でまったく異なるため注意が必要です。

```c
/* master */ mrb_bool mrb_const_defined_at(mrb_state *mrb, mrb_value mod, mrb_sym id);
/* 1.0.0  */ int mrb_const_defined_at(mrb_state *mrb, struct RClass *klass, mrb_sym id);
```

## mrb_class_get の仕様変更

`mrb_module_get` は 1.0.0 と master の違いの中でもっともひっかかりやすいものです。1.0.0 では `mrb_class_get` の引数としてクラスもモジュールもどちらも指定できましたが、master ではクラスしか指定できなくなりました。モジュールを得るためには替わりに `mrb_module_get` を使う必要があります。重要な非互換ですが、対応は容易です。1.0.0 では `mrb_module_get` は以下のように定義できます。

```c
#if MRUBY_RELEASE_NO < 10000
static struct RClass *
mrb_module_get(mrb_state *mrb, const char *name)
{
  return mrb_class_get(mrb, name);
}
#endif
```
例: https://github.com/iij/mruby-io/blob/master/src/io.c#L23

## mrb_yield_internal の名称変更
`mrb_yield_internal` は 1.0.0 では非公開な API という位置付けでしたが、便利なためいくつかの mrbgem から利用されていました。master では `mrb_yield_with_class` と名前を変え、mruby.h で公開されるようになりました。

# Ruby 言語処理系としての動作の変更

## const_defined? の変更
トップレベルで定義されているモジュール/クラスの名前を Module#const_defined? に与えると、master では true が返ってきます。これは CRuby と同じ挙動です。1.0.0 では false を返してきました。

```rb
class A
end
class B
end
p B.const_defined? :A
p B.const_get :A
```

```shell-session
% mruby a.rb
true
A

% mruby-1.0.0 a.rb
false
A
```

## Float#nan? の追加
Float#nan? は master にはありますが 1.0.0 にはありません。以下のように実装できます。

```rb
unless Float.method_defined? :nan?
  class Float
    def nan?
      not (self == self)
    end
  end
end
```
例: https://github.com/iij/mruby-iijson/blob/master/mrblib/json.rb#L104

## Integer#div の追加
Integer#div は master にはありますが 1.0.0 にはありません。以下のように実装できます。あるいは、1.0.0 にもある `Integer#divmod` を使って回避することも可能です。

```rb
unless Integer.method_defined? :div
  class Integer
    def div(other)
      self.divmod(other)[0]
    end
  end
end
```

または `123.div(45)` => `123.divmod(45)[0]`
How to add Basic Auth in Next.js apps with Firebase Hosting and SSR
Tags: react, nextjs, firebase, javascript
Published: 2020-04-01 09:51:04

# Overview

`Next.js` has no method for Basic Auth. So we gonna use `Express.js`.
Also I'll use template: [with-firebase-hosting-and-typescript](https://github.com/zeit/next.js/tree/canary/examples/with-firebase-hosting-and-typescript).

Require:
  - Node.js v10.x.x
  - firebase-tools@latest


# Steps

## Set up Next.js app

We check this [README](https://github.com/zeit/next.js/blob/canary/examples/with-firebase-hosting-and-typescript/README.md).


```
# bash

yarn create next-app --example with-firebase-hosting-and-typescript with-firebase-hosting-and-typescript-app
```

## Install modules

- express
- @types/express
- next-routes
- basic-auth-connect

```
# bash

yarn add express next-routes basic-auth-connect
```

bash
```
# bash

yarn add -D @types/express
```

## Error handling

(If you get this error)

```Error: > Couldn't find a `pages` directory. Please create one under the project root```

We gonna fix `functions`, because this template can't deploy firebase functions. (Apr 1st.2020)

```
// src/functions/index.ts

const app = next({ dev, conf: { distDir: 'next' } })
```

↓

```
// src/functions/index.ts

const app = next({ dev: false, conf: { distDir: 'next' } })
```

## Develop

```
// src/functions/index.ts

import * as functions from 'firebase-functions';
import next from 'next';
import express from 'express';

/* eslint-disable @typescript-eslint/no-var-requires */
const routes = require('next-routes');
const basicAuth = require('basic-auth-connect');

const USERNAME = 'user';
const PASSWORD = 'password';

const server = express();

const app = next({ dev: false, conf: { distDir: 'next' } });
const handler = routes().getRequestHandler(app);
server.use(basicAuth(USERNAME, PASSWORD));
server.get('*', (req, res) => handler(req, res));

export const nextApp = functions.https.onRequest(server);
```

## Set up Firebase Project

We gonna change this: `<project-name-here>` to our firebase project name.

```
# .firebaserc

{
  "projects": {
    "default": "<project-name-here>"
  }
}
```

# Run

## At local

We gonna use `firebase-emulators` for testing on local.
 
### Build

```yarn preserve```


### Run

```firebase emulators:start```

## Deploy

```firebase deploy```

Have fun ☺️
Thanks.