teleren/devto huggingface dataset:
VIM auto-completion with coc.nvim
Tags: vim, languageserver, texteditor
Published: 2020-05-09 18:25:10

VIM is a modal text editor which gives bare minimal setup for text editing. However it's highly flexible and configurable with plugins. With few configurations, we can make VIM similar to VSCode. First you need to install a plugin managers. There are a bunch of plugin managers,

- [Vundle](https://github.com/VundleVim/Vundle.vim)
- [Vim Plug](https://github.com/junegunn/vim-plug)
- [Pathogen](https://github.com/tpope/vim-pathogen)

Installing any of the above managers is a straight forward task. After installing a plugin manager we are good to go :clap:

Next up installing [coc.nvim](https://github.com/neoclide/coc.nvim). Coc is an intellisense engine for VIM. (same as in VSCode) This uses [language server protocol](https://microsoft.github.io/language-server-protocol/). 

![Intellisense](https://user-images.githubusercontent.com/251450/55285193-400a9000-53b9-11e9-8cff-ffe4983c5947.gif "Intellisense")

A prerequisite for Coc is Node.js as it's written in TypeScript. Navigate to [vimawesome](https://vimawesome.com/plugin/coc-nvim) and copy `install from` script for the plugin manager you already installed earlier. Open your `.vimrc` and paste the copied plugin reference and run `:source %` and `:PluginInstall` to install the plugin.

From this point onwards we can use Coc intellisense, but there are a couple of commands that can be mapped from `.vimrc` to make it really convenient to be used quickly. [Coc README](https://github.com/neoclide/coc.nvim#example-vim-configuration) offers a starting point for this configuration. This configuration can be copied and pasted to `.vimrc`. This will add few key mappings like gr, gi, gd for moving to method references, implementations, and definitions. 

For every programming language Coc expects extensions to be installed. For an example for web development following command can be used.

`:CocInstall coc-tsserver coc-html coc-css`

This adds intellisense support TypeScript, HTML, and CSS.

Once that's done, that's all what we need for intellisense :tada:

![Documentation](https://dev-to-uploads.s3.amazonaws.com/i/x2z8phnjjzcio1lyihqv.png)
Documentation with `K` mapping

:page_facing_up: Check out my not so minimal and messy [`.vimrc`](https://github.com/rajikaimal/dotfiles/tree/master/vim)
Build your own Linked List in JS
Tags: javascript, webdev, algorithms, beginners
Published: 2020-05-16 08:40:40

I am trying to improve my hold on data structures and algorithms so, I implemented my own linked list class JavaScript. I've shared the API here and tell me if any other methods should be implemented.

Try implementing it on your own as I also was afraid of linked lists using the .next, .next each time. Implementing it really increased my confidence to use linked lists as a data structure.

API's implemented: 

size() - returns number of data elements in list
 empty() - bool returns true if empty
 value_at(index) - returns the value of the nth item (starting at 0 for first)
 push_front(value) - adds an item to the front of the list
 pop_front() - remove front item and return its value
 push_back(value) - adds an item at the end
 pop_back() - removes end item and returns its value
 front() - get value of front item
 back() - get value of end item
 insert(index, value) - insert value at index, so current item at that index is pointed to by new item at index
 erase(index) - removes node at given index
 value_n_from_end(n) - returns the value of the node at nth position from the end of the list
 reverse() - reverses the list
 remove_value(value) - removes the first item in the list with this value

> Link to the [class](https://github.com/ajitsinghkaler/javascript/blob/master/interview/linkedList.js)


> I am trying to improve my hold on data structures and algorithms please tell me if you have any good resources available in the comments below. 

If you find any error in my code please raise a pull request in my [repo](https://github.com/ajitsinghkaler/javascript/blob/master/interview/linkedList.js)
Material Table II in 20 Minutes (Styling)
Tags: angular, typescript, material
Published: 2020-05-09 21:56:31

In our previous article, we demonstrated how to wire up a Material Table to a JSON file (containing articles), and a paginator; which, looks like this:

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

**Changing the Style of the Rows**

We didn't like the lines on each row and found the root cause to be the default style from MatTable.

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

Let's get rid of the lines by adding this to our page's css.

```css
th.mat-header-cell,
td.mat-cell,
td.mat-footer-cell {
  border-bottom-width: 0px;  
}
```
Ok now let's change the default a:hover behavior and get rid of the typical underscore.

```css
a {
  cursor: pointer;
  border-radius: 5px;
  position: relative;
  padding-left: 0.5em;
  padding-right: 1em;
  padding-bottom: 0.1em;
  text-decoration: none;
}

a:hover {
  box-shadow: inset 0px -7px 15px #1976d255;
}
```
**Results**

No more lines, and a soft inset box shadow following our theme color! This is what it looks like in action.

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

**Search**

The matTable datasource has these properties:

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

In our next article we will show how to tie into these properties to provide automatic (and mostly instant) searches. We'll also explore the sortData function.

JWP2020
Solution to Leetcode’s Valid Perfect Square
Tags: tutorial, codenewbie, leetcode, algorithms
Published: 2020-05-09 23:34:28

This is an easy [Leetcode problem 367](https://leetcode.com/problems/valid-perfect-square/). The question gives a number and you are to write a function to determine if it is a perfect square. See the image below for description.

![problem description]
(https://miro.medium.com/max/1400/1*P5i0IPr8UqObEFFcpMIZlQ.png)

According to [wikipedia](https://en.wikipedia.org/wiki/Square_number), a perfect square is the product of a number with itself. in this context, a perfect square is a number when multiplied by itself will give you the number in question.
There are many ways in solving this problem but I will talk about three in this article.

**NOTE: Do not use any library functions like Math.sqrt().**

<h3><b>THE NAIVE APPROACH</b></h3>
Of course the naive or brute force approach would be to loop through from 1 to the number, multiplying a number by itself and checking if the product equals the number you are looking for. if it does, then return true, else return false.

```
public static boolean isPerfectSquareWithBruteForce(int num) {
    if (num == 1) return true;
    for (int i = 1; i < num; i++) {
        if (i*i == num) return true;
    }
    return false;
}
```

The code above works but can be very slow. its runtime is O(n).
To make this better, we may decide to loop from 1 to half of the number because there is no way you can get the number in question by multiplying number greater than half (i.e num/2) by itself. e.g to determine if 9 is a perfect square, there is no way a number between 4 to 9 would give you 9. So in other words, to know if a number is a perfect square, the number that will multiply itself will have to be in the first half (between 1–3).
```
 public static boolean isPerfectSquareWithHalfNumber(int num) {
        if (num ==  1 || num ==  0) return true;
        for (int i = num/2; i >= 0; i-- ) {
            if (i*i == num) return true;
        }

        return false;
    }
```

Technically speaking, it may seem that the above code would make it faster but the truth is , the runtime of this is O(n/2) which still translates to O(n) because in computer science, we don’t consider constants when dealing with runtime.

<h3><b>A FASTER SOLUTION</b></h3>
A better way to solve this problem would be to use Binary Search. This solves the problem by using the divide and conquer methodology. It keeps splitting the number into half and checking if number is found.

```
public static boolean isPerfectSquareWithBinarySearch(int num) {

    double start = 1;
    double end = num/2;

    if (num == 1) return true;

    while (start <= end) {
        double mid = Math.floor((end - start)/2) + start;

        if (mid * mid ==  num) {
            return true;
        }else if (mid * mid < num) {
            start = mid + 1;
        }else {
            end = mid - 1;
        }
    }
    return false;
}
```

The runtime of the above is O(log n) which is faster than O(n) linear time.

Thank you for reading and please leave a comment or suggestion.
Building Calndr, a free AddEvent alternative
Tags: showdev, laravel, php, javascript
Published: 2020-05-10 02:37:29

Coronavirus has impacted pretty much every business large and small, and has resulted in a massive surge in online events. Companies that previous provided solely physical services are switching to webinars and online courses, so the demand for tech in this area has spiked.

In the last few months, I've had multiple different clients come to me with requests to help them schedule events online. There's some existing services that allow you to create add to calendar links out there, such as AddEvent, but they are expensive for what they do - essentially just generating a few links in a certain format (for different calendar software).

After integrating a simple version into one of my client's applications, I decided to create [Calndr.link](https://calndr.link/). It's a super simple service that allows you to generate calendar links for all the major providers in a couple of clicks. Enter the event details (title, location/meeting link, date, etc) and hit generate and you'll be provided with some HTML to copy/paste directly into your newsletter, website, email signature, etc. You can also copy/paste the direct links as well, if you prefer.

![Options](https://i.imgur.com/DUNVN7z.png)
![Add to Calendar](https://i.imgur.com/hoZ1T2P.png)

## The Tech

I decided to have some fun when building this, using Interia.js (totally overkill for moment, but fun!). On the back end, it's running Laravel 7.

It's deployed on Google Cloud using Cloud Run, so it's running completely serverless. I love the flexibility and ease of use, just whip up a simple docker container, push it to the image registry and hit deploy!

Since you're only charged for requests that actually hit the server, it's extremely cheap. It's basically Lambda, but you can run anything (since it runs custom docker containers).

I'm planning on writing a guide on how to deploy Laravel on GCR serverless, so keep an eye out for that!

Feel free to leave a comment if you've got any questions or suggestions for [Calndr.link](https://calndr.link/)!
Vanilla JavaScript string includes
Tags: javascript
Published: 2020-05-10 07:26:41

While we recently checked if a [string `startsWith`](https://daily-dev-tips.com/posts/vanilla-javascript-string-startswith/) or a [string `endsWith`](https://daily-dev-tips.com/posts/vanilla-javascript-string-endswith/) a specific substring. We are now going to find out if a string contains another substring.

To do so, we are using the `JavaScript` function `includes()`.

## Using includes() function in JavaScript

We can use this function by calling it on a string and passing a substring to it.

```js
var string =
  'The greatest glory in living lies not in never falling, but in rising every time we fall.';

// Check if it includes with `living`
console.log(string.includes('living'));
// true
```

For the `includes()` function it is important to know it's a case sensitive function, so the following will fail:

```js
var string =
  'The greatest glory in living lies not in never falling, but in rising every time we fall.';

// Check if it includes with `Living`
console.log(string.includes('Living'));
// false
```

## Using an offset starting position with includes()

As the brothers startsWith() and endsWith() this one has another position parameter. This position is from where it will start to look.

```js
var string =
  'The greatest glory in living lies not in never falling, but in rising every time we fall.';

// Check if it includes with `living`
console.log(string.includes('living', 30));
// false
```

Feel free to play with this Codepen:

<p class="codepen" data-height="265" data-theme-id="dark" data-default-tab="js,result" data-user="rebelchris" data-slug-hash="eYprJZd" style="height: 265px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;" data-pen-title="Vanilla JavaScript string includes">
  <span>See the Pen <a href="https://codepen.io/rebelchris/pen/eYprJZd">
  Vanilla JavaScript string includes</a> by Chris Bongers (<a href="https://codepen.io/rebelchris">@rebelchris</a>)
  on <a href="https://codepen.io">CodePen</a>.</span>
</p>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

## Browser Support

This function works well in all modern browsers, including edge!

### 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)
Folding in JS
Tags: javascript
Published: 2020-05-10 09:28:18

Mutatis mutandis between Haskell and JS, the two approaches to fold a list/array are `foldl`, which does it from the "left", and `foldr`, which does it from the "right"[^1].

```js
const foldl = f => z => ([x, ...xs]) =>
    x === undefined ? z
    : foldl (f) (f(z)(x)) (xs)

const foldr = f => z => ([x, ...xs]) =>
    x === undefined ? z
    : f (x) (foldr(f)(z)(xs))
```

With these two functions defined, recursion over an array is abstracted, so there's no need to manually traverse it - all other operations can now be defined in terms of `foldr` or `foldl` (at least as an exercise in futility)[^2].

## In terms of fold

```js
// helper function
const cons    = x => ([...xs]) => [x,...xs]
const append  = ([...xs]) => ([...ys]) => [...xs, ...ys]
const apply   = f => x => f(x)
const flip    = f => a => b => f(b)(a)
const add = a => b => a + b
const mul = a => b => a * b
const and = a => b => a && b
const or  = a => b => a || b
const K   = a => _ => a;
const B   = g => f => x => g(f(x))


// In Terms Of Fold

// foldr_id - leaves a list intact, showing that folding a list means replacing all cons with `f` and the empty list ctor `[]` with an initial value, `z`
const foldr_id = foldr (cons)        ([])

const reverse  = foldl (flip (cons)) ([])
const flatten  = foldr (append)      ([])

const compose  = foldr (apply)
const pipe     = foldl (flip(apply))

const head     = foldr (K)       (undefined)
const last     = foldl (flip(K)) (undefined)

const sum      = foldr (add)  (0)
const product  = foldr (mul)  (1)

const all      = foldr (and)  (true)
const some     = foldr (or)   (false)

const map    = f => foldr (B(cons)(f)) ([])
const filter = p => foldr (x => xs => p(x) ? cons(x)(xs) : xs) ([])



// Check

let m = [1,2,3]
let n = [5,6,7]
let t = [[1,2,3], [5,6,7]]
let p = [true, true, false]

console.log(
    '\n',
    'foldr_id:'         , foldr_id  (m) , '\n' ,
   
    'reverse :'         , reverse   (m) , '\n' ,
    'flatten :'         , flatten   (t) , '\n' ,

    'sum     :'         , sum       (m) , '\n' ,
    'product :'         , product   (m) , '\n' ,

    'all     :'         , all       (p) , '\n' ,
    'some    :'         , some      (p) , '\n' ,

    'head    :'         , head      (m) , '\n' ,
    'last    :'         , last      (m) , '\n' ,

    'map     :'         , map    (add(10)) (m) , '\n' ,
    'filter  :'         , filter (a=>a>1)  (m) , '\n' ,

    'compose :'         , compose (5) ([x=>x*3, x=>x+5]) , '\n' ,
    'pipe    :'         , pipe    (5) ([x=>x*3, x=>x+5]) , '\n' ,
)
```

[^1]: The elements are accessed from the left in both cases.

[^2]: Haskell's lists are singly-linked lists, so prepending is the most efficient operation to add an element; but to append an element, the entire list needs to be traversed. Although JS arrays  have many incarnations (depending whether they hold homogeneous or heterogeneous elements, whether they are sparse, etc.), appending should be the most efficient operation.
Multiple PHP Pools
Tags: ubuntu, development, php
Published: 2020-05-10 09:59:29

---
title: Multiple PHP Pools
published: true
date: 2020-05-10 00:00:00 UTC
tags: ubuntu, development, php
canonical_url: http://jamessessford.com/blog/multiple-php-pools
---

PHP has gotten phenomenal to work with over the last few years.There have been so many improvements - both to the language itself and, in my humble opinion, the developer experience in using the language every day.

I'm a terrible hypeman for anything but if you're interested in the current state of PHP, I'd highly recommend reading [PHP in 2020](https://dev.to/brendt/php-in-2020-1nag-temp-slug-1485828) by Brent Roose.

One of the new features of PHP that I wanted to experiment with was preloading but I had several sites on my Rasperry Pi and they didn't all depend on the same code, so I needed to seperate my instances.

## Enter pools

PHP pools are seperate processes that can each be used to serve a subset of requests. You'll probably already be using the default pool at the moment:

```
server {
    ###

    server_name www.test;

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }

    ###
}
```

On Ubuntu, PHP pool configuration is located at `/etc/php/7.4/fpm/pool.d/`. I'd start by copying the template that's there for my new pool.

```
cd /etc/php/7.4/fpm/pool.d
sudo cp www.conf www2eb.conf
```

You'll then want to edit this file and update, at minimum, a setting or two.

```
sudo nano www2eb.conf
```

Update the name of the pool:

```
; Start a new pool named 'www'.
; the variable $pool can be used in any directive and will be replaced by the
; pool name ('www' here)
[www2eb]
```

If you want to change the user that owns the pool, update the following:

```
; Unix user/group of processes
; Note: The user is mandatory. If the group is not set, the default user's group
; will be used.
user = poolowner
```

Lastly, we need to give it a different socket so we can send requests to it via NGINX

```
; Note: This value is mandatory.
listen = /run/php/php7.4-fpm.poolowner.sock
```

Now that we've updated the PHP pools, we need to update our NGINX server block to point to the correct socket:

```
server {
    ###

    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php7.4-fpm.poolowner.sock;
    }

    ###
}
```

We've now made all of the updates that we need, it's time to restart our services:

```
sudo service nginx restart && sudo service php-7.4-fpm restart
```

You can now check that your new PHP pool is working by visiting your site in a browser.
Merge Sort Algorithm - Algorithm Design and Analysis
Tags: javascript, webdev, algorithms, computerscience
Published: 2020-05-13 15:32:55

In this episode of Algorithm Design and Analysis we'll break down the merge sort sorting algorithm, and implement it in JavaScript. This requires us to dive into recursion and take a divide-and-conquer approach to sorting an array.

I upload videos like this one as well as live stream coding session on my [YouTube channel](https://www.youtube.com/channel/UCZxtkm5msn0r1etbzvGZx5A).

---

To keep up with everything I’m doing, follow me on [Twitter](https://twitter.com/MichaelSolati) and [dev.to](https://dev.to/michaelsolati). If you’re thinking, _“Show me the code!”_ you can find me on [GitHub](https://github.com/MichaelSolati).
Friday Night Deploys #22 - A Brief Discussion On The State Of The Modern Web
Tags: webdev, podcast, jokes
Published: 2020-05-15 20:12:53

## Intro
Hey, How's it going everyone?
This week's topic is about a recent article that had some hubbub recently called "Second Guessing the Modern Web" by Tom Macwright on their personal blog. If you would like to take a read through it before listening you can find it in the following link.

https://macwright.org/2020/05/10/spa-fatigue.html

We make some pretty far fetched analogies with modern web development and the Tony Hawk's Pro Skater video game series; Y'know most things link back to Tony Hawk's Pro Skater. (Not sponsored by Tony Hawk (I Wish)).

## Episode Summary
This week the DevPlebs talk about: Getting requests for content! How expensive it is to podcast! Our eventual sponsored content! Apple saying we're too sad for analytics! Bad documentation! Our stupid, simple brains! Getting thrown into the deep end of the pool! Meeting two Vice Admirals of the Royal Canadian Navy! Being careful about who you choose to challenge to a pushup contest! The Presidential Fitness Test! Doing 53 pushups! That time Keith lost 120 lbs! How Trump looks perpetually sore! How to redeem 2020 through a world leader fitness challenge! How we're a 25% fitness podcast! Keith's unreliable memories! The entire history of Spike TV! Takeshi's Castle! Phil's big, dirty bundle! The Tony Hawk Pro Skater 1 + 2 Remaster! How pure the web used to be! Cellphones getting bigger in order to watch pornography on them! Comparing the virtual dom to PUBG! Getting back into running! Having snowstorms in mid-May! Being called "stud"! Having so many episodes that we have pagination on our page! Reminiscing on 6 AM! Getting 9 hours of sleep! Our expert opinion on the state of the modern web!

## Listen to The Full Episode!
{% spotify spotify:episode:2iEycDPQSrSz6Z9sL3JnAj%}

_or [listen directly on spotify](https://open.spotify.com/episode/2iEycDPQSrSz6Z9sL3JnAj)_

**We're also on...**
**Apple Podcasts:** https://podcasts.apple.com/ca/podcast/friday-night-deploys/id1485252900

**Google Music Podcasts:** https://play.google.com/music/m/D2fy7ibvzudgnxr6xjua4m5x6eu?t=22_A_Brief_Discussion_On_The_State_Of_The_Modern_Web-Friday_Night_Deploys

**Our Website:** https://www.devplebs.tech/friday-night-deploys/22-a-brief-discussion-on-the-state-of-the-modern-web/

## Get In Touch With Us!
What's your hot take on second-guessing the modern web? If you would like to share for us to read out in the next episode you can reach us at the following...

**Twitter:** [@DevPlebs](https://twitter.com/DevPlebs).
**Email:** deadbeats@devplebs.tech

## Follow Our Twitters... If You Want!
[DevPlebs](https://twitter.com/DevPlebs).
[Keith Brewster](https://twitter.com/brewsterbhg).
[Phil Tietjen](https://twitter.com/phizzard).

You can also ask questions or give us some feedback about the show!
Understanding Call Stacks In Java Script
Tags: javascript, callstack, memory, v8
Published: 2020-05-16 11:14:58

##What is a call stack?
A call stack is a region in memory that keeps track of the running/active subroutine/function in a program. it follows a first in last out approach(FILO). When a function is called it is pushed on top of the call stack and when it returns it is popped out of the call stack.


##Global execution context?
A global execution context is always the first function on the stack. it is an anonymous function the creates the environment in which the javascript code runs. For an environment like the browser the global execution context creates a global object called windows and assigns it to "this".



##Stack limits and overflow
As interesting as stacks sounds they also have a memory limit just like any storage. the limit of the stack determines the total number of functions that can be on the stack at once. Stack limits differ in various browsers. when a stack limit is exceeded it causes an error known as stack overflow.

The quickest way to cause a stack overflow is by recursion.
```javascript
function sayHello() {
	sayHello()
}

sayHello();
```

The above code will cause a stack overflow because it keeps adding to the stack and exceed the given stack memory allocation.


## Javascript has only one call stack
Javascript is a single-threaded language and what this means for the call stack is javascript can only have one call stack.