teleren/devto huggingface dataset:
Tricky async declarations
Tags: javascript, node, async, promise
Published: 2020-01-16 22:39:23

Imagine the following code, using Express and Sequelize:


```javascript
app.get('/', async (_, res) => {
  const result = await sequelizeModel.getStuff()[0]
  return res.status(200).send(result)
}
```

In simple words: given an endpoint, it will execute a query on the database and return the result.

But there's a small gotcha: that code works but doesn't return the results, because at the time of the promise creation, the `[0]` is not available/ready.

Only after the promise/async is fulfilled, the Sequelize object exists.


Working code:

```javascript
app.get('/', async (_, res) => {
  const result = await sequelizeModel.getStuff()
  return res.status(200).send(result[0])
}
```
Scaling WordPress: The Autoscaling Fallacy
Tags: aws, wordpress, devops, webperf
Published: 2020-01-16 22:36:19

Busy sites need autoscaling. That’s what everyone expects, technical and non-technical users alike. The rising popularity of cloud computing has taught us to expect unlimited capacity for all online services.

How does this apply to WordPress?

A quick search returns hundreds of results that equate AWS with automatic infinite capacity. While AWS is no silver bullet, some of these results do recommend a scalable architecture.

How does autoscaling actually work in the real world, though?

In theory, an adequately configured stack keeps track of various resources, such as CPU, Memory, PHP workers, etc. When the utilization for any of these resources exceeds a predefined limit for more than a few minutes, stack launches another VM. This new VM is then used to serve the additional traffic. Stack repeats this process as long as there is enough traffic to warrant additional resources.

Pretty cool, right?

While this process looks great on paper, it’s a little less magical in reality. When the stack launches a new VM to serve additional traffic, it can take 60 to 120 seconds for it to become ready and join the load-balancer. A good web ops team knows this and utilizes various caches and queues to make this latency invisible to the end-user. Without such caches and queues in place, visitors experience timeouts, slowdowns, or random errors while new VMs are being prepared.

Since autoscaling requires sustained heavy traffic to launch new VMs, it makes little sense to use it on smaller sites.

Time for a car analogy.

F1 cars are built for massive speed. But if you try diving an F1 car on slow speed, it doesn’t generate enough downforce to provide decent traction, the breaks aren’t warm enough to be useful, and the handling is tricky at best.

To get around some of these issues, the F1 crew pre-warms the tires, uses a starter motor to start the engine, and has the skills to handle any pit stops as quickly as possible.

When it comes to operating an autoscaling environment for WordPress, you do need similar systems in place. A process to warm up the load balancer, a way to spin up additional VMs, and a star crew that maintains the pit stops. There are just too many moving parts for autoscaling to “just work” automatically.

When you are shopping for an autoscaling solution, ask the providers on your shortlist these questions:

What’s your plan to minimize the latency while new VMs starting?
Will I be able to launch more VMs in advance if there is not enough traffic yet?
Will I be able to control the thresholds when autoscaling launches additional VMs?

And finally,

Will I be able to contact the crew that set this up directly when I’m expecting a traffic surge?

These questions will help you look past the marketing speak and save a lot of stress down the line.
🤔 Check if an object is empty in JS
Tags: javascript, beginners, webdev, tutorial
Published: 2020-01-16 22:23:36

Checking if an object is empty, is a quite common task. Let's figure out how to accomplish it.

Here we create an empty object using the object literal syntax.

```js
const someObject = {}
```

You might be tempted to compare this object, to an empty object like this:

```js
const someObject = {}
console.log(someObject === {}) // false
```

That's incorrect. Even if you compare two objects via the object literal, they're not equal:

```js
console.log({} === {}) // false
```

This is because you're comparing reference and not values. The reference to these objects isn't the same, even though the value is the same.

So how can we actually check if an object is empty? You could do so, by checking if it has any properties. We could use the [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) method, which returns an array of all the properties of the object.

```js
const someObject = {}
console.log(Object.entries(someObject).length === 0) // true
```

If you want to create a small function, it would make sense to first check if we're actually dealing with an object, to not throw any errors, if a wrong data type is checked:

```js
const isEmpty = obj => obj.constructor === Object && !Object.entries(obj).length

// let's see if it works:
const o = {}
console.log(isEmpty(o)) // true

o.name = "foo"
console.log(isEmpty(o)) // false
```

Also, lodash offers an [isEmpty](https://lodash.com/docs/4.17.15#isEmpty) utility function to check if an object is empty:

```js
const someObject = {}
console.log(_.isEmpty(someObject)) // true
```

---

Want to get better at Web Development?
[🚀🚀🚀subscribe to my Tutorial Tuesday ✉️newsletter](https://codesnacks.net/subscribe/)
Criar elementos dinamicamente em JS é uma boa ideia?
Tags: php, javascript, webdev
Published: 2020-01-16 22:10:27

Recentemente eu criei um video dinâmico para diminuir o tempo de playload. Imagine que a página vai carregar, mas o vídeo não. Mas ele está lá, pronto para ser criado. Quando o cliente clica na thumbnail (identica a do YT), o JS cria o elemento. Simples, fácil e bem útil, nesse caso.

https://webdesign.tutsplus.com/pt/tutorials/how-to-lazy-load-embedded-youtube-videos--cms-26743

Mas hoje me deparei com um problema um pouco mais complexo. Precisava carregar um elemento somente no mobile. O meu ambiente nesse caso é em PHP, ou seja, não tenho as facilidades de frameworks JS.

     window.addEventListener("load", sizeOfThings());
		function sizeOfThings() {
  			var windowWidth = window.innerWidth;
				var el = aElement;
				var node = document.querySelector('#sidebar-blog');
				
			windowWidth > 480 ? node.innerHTML = el
				: console.log("false");


Desinformado, eu tentei display: none. Descobri que a propriedade none esconde o elemento, mas o DOM o randeriza assim mesmo. Ou seja, nada últil para o meu propósito.

Procurei um bocado e decidi criar o elemento dinamicamente. Pensei: eu só preciso saber qual é a largura da página, se ela for > 480, eu crio o elemento. E aí eu descobri que o objeto Window tem a propriedade innerWidth. Amo JS.

Funcionou. Mas, por motivos especificos do PHP e tal, eu tive que utilizar esse script inline. Esse é um sistema de conteúdo, portanto a parte sintática é importante. Sem falar que adiciona complexidade ao código. Quando eu quiser fazer isso de novo, vou ter que criar uma nova funcão? Ou passar parâmetro no HTML?

> Trabalhe menos, de forma mais inteligente.

# A solução

Quando o cliente faz uma requisição, ele envia o user-agent no cabeçalho HTTP. Esse user-agent tem informações sobre o cliente, como o navegador, o sistema operacional e etc. Então eu vou interceptar a requisição, ler o user-agent e randerizar somente se não for mobile. Pera, claro que não! Imagine o tamanho do esforço. Eu amo escrever código do zero, mas esse não era o momento.
Então eu descobri que um abençoado já havia escrito exatamente o que eu precisava. Intercepta a requisição, verifica de onde está vindo e devolve somente o que eu quero. Tem todos os devices listados e etc. Eu amo o open source.

Então, somente o que eu tive que fazer foi instanciar e usar a função isMobile(). Imagine o poder que essa implementação vai me dar daqui para frente.

https://github.com/serbanghita/Mobile-Detect

E, como eu disse no inicio do artigo, o meu objetivo é a performance. E utilizar o PHP foi mais performático que utilizar o JS. Sem falar na parte sintática do código.

     require_once('mobile-detect.php');
     $detect = new Mobile_Detect;

     if ($detect->isMobile() == false ) {
     //your code
     }

Quer trocar uma ideia? https://github.com/portolucas
Event Coalescing to improve performance
Tags: zonejs, angular, eventlistener, performance
Published: 2020-01-16 01:18:04

---
title: Event Coalescing to improve performance
published: true
description: 
tags: Zone.js, Angular, EventListener, Performance
---

# Event Bubbling の性能の問題

下記のAngularアプリケーションでのHTMLテンプレートコードを見ましょう。

```html
<div (click)="doSomething()">
  <button (click)="doAnotherThing()">Button</button>
</div>
```

[Event Bubbling](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#Event_bubbling_and_capture) のため、DivのなかのButtonをクリックしたら、両方のEvent ListenerがTriggerされます。この２つのEvent Listenerが全部Change Detectionを実行します。実際はこのようなケースでChange Detectionを一回だけ実行したいです。特にこのようなケースがAngular MaterialとかUI ライブラリで結構普通のケースですので、性能改善したいです。

# 実行順番

まず上記のケースでEvent ListenerとChange Detectionの実行順番を見ましょう。

```typescript
export class AppComponent {
  doSomething() { // event listener for parent div
    console.log('event listener for parent div');
  }
  doAnotherThing() { // event listener for inner button
    console.log('event listener for inner button');
  }
}
```

そして、Zone.jsがEvent ListenerをMonkey patchされましたので、下記のような感じのコードになりました。

```typescript
function eventHandler(...) {
  try {
    realHandler(...); // doSomething あるいはdoAnotherThingのDelegate
  } finally {
    applicationRef.tick();
  }
}
```

そしたら、Buttonをクリックするとき、実行の順番が下記のようになりました。

```
event listener for inner button
applicationRef.tick
event listener for parent div
applicationRef.tick
```

実際ほしいのは

```
event listener for inner button
event listener for parent div
applicationRef.tick
```

です。

## 解決方法

Change Detectionを同期ではなく、非同期で実行することです。

```typescript
isChangeDetectionScheduled = false;
function eventHandler(...) {
  try {
    realHandler(...); // doSomething あるいはdoAnotherThingのDelegate
  } finally {
    if (isChangeDetectionScheduled) {
      return;
    }
    isChangeDetectionScheduled = true;
    requestAnimationFrame(() => {
      isChangeDetectionScheduled = false;
      applicationRef.tick();
    }); 
  }
}
```

のような感じのコードでChange DetectionをrequestAnimationFrameのSchedulerで実行させ、そしてもしScheduleされたTaskがあったら、スキップして、なかったら、Scheduleするということです。

## 設定方法

bootstrapModuleのとき、かきのOptionを設定することができます。

```typescript
platformBrowserDynamic().bootstrapModule(AppModule, {ngZoneEventCoalescing: true})
```

## 副作用

このオプションをTrueにしたら、もともと同期のChange Detectionが非同期になりました、普通のアプリケーションには影響がないですが、Google 内部でのEdge Caseで同期のChange Detectionが求めるテストケースがあるらしくて、それ以外が特に既存のアプリケーションには影響ないはずです。
この機能がすでに最新バージョンで使えますので、なにか問題が発見されたら、ぜひAngular RepoにIssueを提出ください。

以上です。

どうもありがとうございました！
Customize View of Devise
Tags: rails
Published: 2020-01-16 21:54:46

# 👍There are only 3 steps.

## 1. Change the config file

open `config/initializers/devise.rb` and turn on the `config.scoped_views`.

```ruby
  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  config.scoped_views = true
```

## 2. Restart the rails server
```sh
rails restart
```

## 3. Generate your views by devise

Run `rails generate devise:views [model_name]`.

For example:
```
# rails generate devise:views users
Running via Spring preloader in process 569
      invoke  Devise::Generators::SharedViewsGenerator
      create    app/views/users/shared
      create    app/views/users/shared/_error_messages.html.erb
      create    app/views/users/shared/_links.html.erb
      invoke  form_for
      create    app/views/users/confirmations
      create    app/views/users/confirmations/new.html.erb
      create    app/views/users/passwords
      create    app/views/users/passwords/edit.html.erb
      create    app/views/users/passwords/new.html.erb
      create    app/views/users/registrations
      create    app/views/users/registrations/edit.html.erb
      create    app/views/users/registrations/new.html.erb
      create    app/views/users/sessions
      create    app/views/users/sessions/new.html.erb
      create    app/views/users/unlocks
      create    app/views/users/unlocks/new.html.erb
      invoke  erb
      create    app/views/users/mailer
      create    app/views/users/mailer/confirmation_instructions.html.erb
      create    app/views/users/mailer/email_changed.html.erb
      create    app/views/users/mailer/password_change.html.erb
      create    app/views/users/mailer/reset_password_instructions.html.erb
      create    app/views/users/mailer/unlock_instructions.html.erb
```
But why doesn't it work?!
Tags: replit, python
Published: 2020-01-16 21:43:19

(everything is in **French**)

***Please help me...***

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/2fidh0weti6hs9oxmvxl.PNG)

{% replit @Sowl/ProjectBaraBaraAreBringingItems %}
Can content marketers create personalized experiences on the JAMstack?
Tags: jamstack, jamuary
Published: 2020-01-16 21:21:49

Personalization is a powerful technique used by marketers to create unique digital experiences that engage with customers on an individual level. They play an integral role in driving revenue streams for businesses and are essential to remaining competitive in a crowded marketplace. Personalizing content requires analyzing traffic to identify high value customer segments and sending content targeted to user needs. Many CMS-es include this feature out of the box. This way, content marketers can create content, learn about their audiences and tailor make experiences within the same tool. In the context of the JAMstack where services are decoupled, it can be a challenge to convince marketers to use yet another service (YAS *see tweet*) to write and potentially duplicate content and processes to. 

Even so, the decoupled approach to the JAMstack lends itself well to a process where content marketers can have their cake and eat it too. The decoupling between the presentation layer and content management means content delivery can be treated as a yet another service to plug into. Since personalization is inherently dynamic, we can easily augment how content is served to users with standalone personalization services like Frosmo or Brandfetch that hook into applications via serverless functions and web hooks. These mechanisms allow content marketers to give their users immediate feedback and vary content based on individual customer characteristics. Serving content statically on a CDN has the added benefit of accessing cutting-edge CDN features like A/B testing at the edge so granular metrics can be measured without an added trip to the server. 

Split testing for content personalization and engagement is a breeze with modern CDNs like Netlify. To learn more and get started, check out [Netlify's handy dandy docs](https://docs.netlify.com/site-deploys/split-testing/). And to learn more about using personalization tools in the JAMstack, check out [this article on “Personalizing the web for the modern user with Contentful and Frosmo“](https://www.contentful.com/blog/2018/12/13/frosmo-contentful-website-personalization/?utm_medium=social-organic&utm_source=devto&utm_campaign=netlify-is-awesome&utm_content=blog).
Binary Search - which camp are you in?
Tags: python, codingstorytime, computerscience, technology
Published: 2020-01-16 21:20:21

Which camp are you in?
What is your go-to starting values for a binary search range

n=maximum elements to search

Camp A -------> low = 1, high = n, mid= floor(low+high/2)

Camp B -------> low = 0, high = n-1, mid= floor(low+high/2)

Camp C -------> low = 0, high = n-1 , mid= floor(low+(high - low)/2)




https://www.facebook.com/groups/alljavascript/


{% replit @Moyarich/squareroot-pick-a-camp %}
Favorite Refactoring Techniques: Extract Class
Tags: extractclass, refactoring
Published: 2020-01-16 20:58:12

---
title: Favorite Refactoring Techniques: Extract Class
published: true
description: 
tags: extract class, refactoring
series: Favorite Refactoring Techniques
---

The next refactoring technique we'll look at is extracting classes. Extracting classes has a similar thought process as extracting functions. In both cases, we are extracting behavior. For classes however, we are extracting _sets_ of behavior or data. 

Say we have the following code: 

{% gist https://gist.github.com/Naomi-Dennis/c1d5def6c9a3c8c1af053edc05ae806e %}

Multiple conditionals that test strings is a perfect code smell that indicates something can be refactored. In this situation, each string in the `if statement` denotes a name for an item in a shop. The body of each statement is the same; it performs a transaction with said item, the item's value and the money of the person shopping. After the transaction is complete, `#perform_transaction()` returns the amount of money the shopper has left. The only clause that is different is `else`, which outputs a message to the shopper that the requested item is not found. 

With this information we can split the behavior of the conditionals into two parts: performing a transaction when the item is in the shop and outputting a message when the item is not in the shop. Looking at the transaction portion, we can see that each item not only has its own name, but its own value. We can extract this into a `ShopItem` class. 

{% gist https://gist.github.com/Naomi-Dennis/b1d2d421d240c5928bbc216105c8daa7 %}

With this class, we can rewrite our if statement to more accurately portray the first portion, checking if the item is in the shop and outputting a message if it isn't. Before extracting the class, if the item wasn't apart of the conditional statement, it was seen as not being included in the shop. Now, we can create a list of items and if the item isn't in the list, we can output the message. 

{% gist https://gist.github.com/Naomi-Dennis/dc25bb4bb30f6928087414dd529c8c39 %} 

Now our code tells a concrete story. Search for an item. If the item is found, perform the transaction and return money to the shopper, if the item isn't found then tell the shopper the item isn't being sold. 

As it stands, our if statement looks pretty good. However, we can make some minor changes to make it a bit better. 

{% gist https://gist.github.com/Naomi-Dennis/8b5ff8650e4dbc91437950fe4e845fed %}

All in all, our code now looks this (Please note, `# -- snip -- ` is code that wasn't mentioned.) : 

{% gist https://gist.github.com/Naomi-Dennis/1b0a50374e957aa84e06c3ddcdb34c0d %}
A quick guide to Agile Software Development
Tags: agile
Published: 2020-01-16 20:54:24

<h1>What is Agile Software Development?</h1>
<p>I am sure that most seasoned developers will be very familiar with Agile software development, but for those of you just starting out, this may be an unfamiliar practice. Since it's inception in circa 2001, Agile has grown to be one of the most popular methodologies for developing software, so it is important for aspiring developers like myself to understand it.</p>

<p>So what is Agile Software Development? Agile Software Development is an umbrella term for a number of methodologies that encourage flexbility and rapid responses to evolving requirements. This is achieved through:</p>

<ul><li><b>Incremental, evolving software</b> - agile methods split development into short iterations, or "sprints", that typically last from 1-4 weeks. This reduces the need for up-front planning and design, and the aim is to have a new feature or working product ready at the end of each sprint. 
<li><b>Self-organising and cross-functional teams</b> - often one agile team will cover planning, analysis, design, coding, and testing. This ensures that the entire team is aware of the bigger picture and how everything fits together.
<li><b>Effective communication</b> - a common practice in agile software development is the daily "scrum" (or stand-up). This involves team members sharing what they have been working on, what they plan on working on, and any issues they may have encountered. The benefit of this is that solutions can be found quickly to any roadblocks that are encountered, and that everyone is kept up-to-date on the status of the sprint.
</ul>

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/wharery7z31exehlmvjg.png)

<h1>Agile vs Waterfall</h1>
<p>The other prominent software development methodology is the Waterfall method. This typically involves a linear set of phases that each progress one after another, and are reliant on the previous phase being completed. As you can imagine, this does not offer as much flexbility as Agile, as each phase involves the completion of big tasks such as implementation or testing, and often requirements do change frequently during the production process, resulting in a lot of re-work and wasted resources. </p>

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/x97e417b06zrs5s139qs.png)



<h1>Summary</h1>
<p>In conclusion, Agile is a proven and effective software development methodology that favors small, efficient and flexible teams, working on products with ever-changing and evolving requirements. </p>

<p>However, some larger scale organizations have found that Agile Software Development simply is not effective for their own dev teams for a number of reasons, so adopt a kind of hybrid approach, that mixes elements of both Agile and rigid plan-driven practices like the Waterfall method. </p>

</p>Regardless, it is clear that Agile Software Development has an important place in the tech sphere, and will be around for many years to come.
Node.js and the require function
Tags: node, javascript, discuss
Published: 2020-01-16 20:33:00

##```const hello = require('./hello.js')```
I've always been curious about how things work behind the scenes, and today I'd like to share with you how the **_require_** function works in Node.js.

###But, what is a module in Node.js?
> a reusable block of code whose existence does not accidentally impact other code.

###require actually does three main things:
1. locates where the file is.
2. wraps the content of the file in a function and executes it.
3. return the module.exports

That's it :) 
let's see how every step works

### File Location
First, Node.js checks if that file is a built-in module by calling this function:```Module._resolveLookupPaths = function(request, parent)``` and if it's not the resolveLookupPaths return the path to the parent directory. If the string passed is a directory, Node looks for an index.js file. Then it creates a new object```const module = new Module(filename, parent);```, finally, the module gets cached, for more info [require.cache](https://nodejs.org/api/modules.html#modules_require_cache) .

###Wrapping the content
In the next 2 steps, the file's content is loaded and passed to a compile function to get executed.
```const content = fs.readFileSync(filename, 'utf8');```
```module._compile(stripBOM(content), filename);```
The code of _hello.js_ is wrapped inside this function
``````function(exports, require, module, __filename, __dirname) { 
  function Hello() {
    console.log("hello from emitter");
  }
  console.log("hello from hello.js");
  module.expors = Hello;
}``````
and this wrapper function is invoked by the call method.
```result = compiledWrapper.call(thisValue, exports, require, module,
                                  filename, dirname);```
the content gets executed ![hello.js](https://thepracticaldev.s3.amazonaws.com/i/6b0q0ik9z61beur1ark6.png)


###finally
this.exports is returned ```return this.exports;```, which in our case will be ```function Hello() {
  console.log("hello from emitter");
}```


Actually, there is much much more, but I tried to mention the most important aspects of it.
Thanks, your feedback is highly appreciated.