teleren/devto huggingface dataset:
★ Avoid nesting using the crossJoin and eachSpread collection functions
Tags: laravel, php
Published: 2020-01-02 23:05:50

---
title: ★ Avoid nesting using the crossJoin and eachSpread collection functions
published: true
date: 2018-10-24 20:36:40 UTC
tags: laravel, php
canonical_url: https://freek.dev/1187-avoid-nesting-using-the-crossjoin-and-eachspread-collection-functions
---

While working on a package I found myself trying to combine some data. This is what my code looked like. Assume that `$locales` and `$fields` are arrays that are already populated.

```
collect($locales)->each(function (string $locale) {
    collect($fields)->each(function (Field $field) use ($locale) 
       $this->doSomeWork($locale, $field); 
    });
});
```

Sure, it's pretty already pretty clear, but there are also two cool collection methods that allow us to do the same thing. [`crossJoin`](https://laravel.com/docs/5.7/collections#method-crossjoin) creates a new collection with all possible combinations of the input given. [`eachSpread`](https://laravel.com/docs/5.7/collections#method-eachspread) is a method that will pass each nested item as an argument to the callback.

Using those functions the code above can be rewritten as this:

```
collect($this->locales)
    ->crossJoin($this->originalFields)
    ->eachSpread(function (string $locale, Field $field) {
        $this->doSomeWork($locale, $field);
    });
```

Even though the first version of the code was pretty clear, I like this one better. There's no nesting involved here and we avoided the need for that damn `use` to import a variable.

Thanks [Seb](https://twitter.com/sebdedeyne) for this refactor!
Notable dev.to Issues Up for Grabs
Tags: meta, hacktoberfest
Published: 2018-10-24 18:37:54

---
title: Notable dev.to Issues Up for Grabs
published: true
description: "Hacktoberfest is ending soon - get them while they're hot!"
tags: meta, hacktoberfest
---

Hello again! 👋 We're back with some more issues that we're looking for some help with. You can find the [first post by clicking here](https://dev.to/devteam/notable-issues-of-the-week-up-for-grabs-19f7). This week, we're highlighting these three issues:

{% github https://github.com/thepracticaldev/dev.to/issues/923 %}

Any Docker help would be greatly appreciated. We've had some comments saying that the speed doesn't seem to be an issue on Linux, so it might only be an issue with macOS. Maybe it's a problem you've run into? Feel free to leave a comment on the issue. Even a comment about how our Docker setup runs on your machine would help a bunch!

{% github https://github.com/thepracticaldev/dev.to/issues/134 %}

Night mode!!! Halloween is definitely coming up, and a dark theme for dev.to would be awesome. Regardless, I know my night time eyes would appreciate it. Check out the issue and the comments for more info on getting started.

{% github https://github.com/thepracticaldev/dev.to/issues/969 %}

This is an awesome issue that came in this week. The issue well written, and the author also suggests a great solution. It's a great low-hanging fruit for accessibility and Hacktoberfest.

### That's all for now; we'll have more next week!
How do you deal with One-upmanship ?
Tags: discuss
Published: 2018-10-24 17:58:56

---
title: How do you deal with One-upmanship ?
published: true
description: 
tags: discuss
---
![](https://thepracticaldev.s3.amazonaws.com/i/e8v425nhjeqpixscftce.jpg)
Let me start with this.

_"Computers are easy its people that are hard"_

We've all been there.. Your on slack or hangouts or reddit..Your trying to discuss or highlight something that someone might find useful. Some project you are working on or a tool you built to shave some time off a repetitive task or a third party app ..something you believe gives value. 

Then you get hit with the _**"expert"**_ opinion that provides no feedback or improvement. Just a pendantic statement highlighting a irrelevant observation.

This is usually a one-upmanship moment. These put downs are what drive imposter syndrome among a dev community. 

How do you steer theses discussions back into a constructive conversation and not play into a egotistical game?

I don't mean to come across as bitter here but there are issues in dev culture like this that disable a learning mindset.

And I am in no means dissing being a expert in a subject. But with that expertise it's better to use your knowledge for the greater of the community.
A tour through the OWASP Top 10
Tags: cybersecurity, owasp, websecurity, infosec
Published: 2018-10-24 17:07:20

---
title: A tour through the OWASP Top 10
published: true
description: It's Cyber Security Awareness Month; let's take a run through the OWASP Top 10.
tags: #cybersecurity #owasp #websecurity #infosec
canonical_url: https://auth0.com/blog/a-run-through-the-owasp-top-10/
---

October is National Cyber Security Awareness Month! To celebrate, we’re going to run through the OWASP TOP 10 to remind ourselves of how we can better protect our applications, our businesses, and our customers from unlawful and damaging cyber attacks which could be prevented by implementing the correct procedures in the right places.

[Read on 🐝](https://auth0.com/blog/a-run-through-the-owasp-top-10/?utm_source=dev&utm_medium=sc&utm_campaign=owasp_t10)

![A tour through the OWASP Top 10](https://thepracticaldev.s3.amazonaws.com/i/nycclfsizojf7iiv21et.png)
New Beginnings, Starting my Own Business
Tags: business, webdev, blog
Published: 2018-10-24 15:28:42

---
title: New Beginnings, Starting my Own Business
published: true
description: 
tags: business, webdev, blog
---

Recently I left my job at a world-class design agency in Portland, Oregon. Well, I didn't *leave* it - I got laid off for financial reasons. But I had been thinking about leaving for a few months prior, and everything kind of lined up perfectly.

I've never been one to take take the typical, expected path. I dropped out of high school, never had plans of going to college. While my friends were studying for their finals, I was teaching myself how to code. I've always wanted to start my own business but never knew what I wanted it to be.

So, when I got the news that I was being laid off, I decided this would be the moment. Now is the time to walk the talk, and take the risky leap into the depths of entrepreneurship. I started my own web-development/marketing agency with my life-long friend - He handles everything that isn't technical (sales, bookkeeping, time-management, etc) while I do all of the dirty work. 

So far we haven't gotten any actual profit, but things are actually going better than expected. We decided to really lay in on the "local" aspect of our service - Going door-to-door and pitching local businesses, letting them know we're real, here, and responsive. That angle has been working out extremely well, I live in a somewhat rural, isolated town and all of the businesses here get their websites made by some developer they found on the internet who takes a week to reply to their emails. So when we walk into their store, and have a face-to-face conversation with them, it seems to really strike a chord.

I'm writing this on a Wednesday morning, tweaking out on a massive cup of coffee. It's the 24th, rent is due in a week and I don't have nearly enough money to pay it. I'm putting off time with my friends and family, not getting nearly enough sleep, treating my body like an old run-down car, deflecting waves of hate from my peers, and loving every second of it. 

I've never seen the point in living a life doing what others expect of you. I don't know if I'll be able to pay my landlord, or buy groceries next week, but I know that whatever happens is up to me.
CodeTip - Javascript: Compare class instances
Tags: javascript, compare
Published: 2018-10-24 16:48:16

---
title: CodeTip - Javascript: Compare class instances
published: true
description: compare class instances in javascript
tags: js, javascript, compare
---

Many times we are in situations we want to compare instances of a class, aka objects, for example in case you develop a game and you want to compare instances of a gameobject, e.g. `Car`:

```js
class Car {
  constructor(speed){
    this.speed = speed
  }
}
```

Let's say we want to compare instances of a car (or sort/filter an array of them). Obviously we can do:

```js
const car1 = new Car(100)
const car2 = new Car(120)
const car3 = new Car(90)
 
console.log(car2.speed > car1.speed) // true
 
const sorted = [car1, car2, car3].sort((a,b) => {
  return a.speed - b.speed;
});
```

This works perfectly fine but we can do better, so we don’t have to type `.speed` every time we want to compare two cars, or sort/filter an array of them. We can define a valueOf method in the Car class, the method returns the “value” of the instance.

```js
class Car {
  constructor(speed){
    this.speed = speed
  }
 
  valueOf(){
    return this.speed;
  }
}
 
 
const car1 = new Car(100)
const car2 = new Car(120)
const car3 = new Car(90)
 
console.log(car2 > car1) // true
```
Extend is sometimes faster than Append
Tags: python, cpython, discuss
Published: 2018-10-24 15:41:29

---
title: Extend is sometimes faster than Append
published: true
description: A simple optimization for Python.
tags: python, cpython, discuss
---

I just was comparing the *performance* difference between `[].append(x)` and `[] + [x]`. I just realized `[].append(x)` was faster. But when i tried it with `[].extend([x])` is faster. You just can use it while optimizing your code. Do not use it while you're coding, but when you're going to optimize it use `[].extend([x])`. Simple benchmarks
```python
>>> import timeit
>>> start = timeit.timeit()
>>> [1, 2, 3, 4] + [5]
[1, 2, 3, 4, 5]
>>> end = timeit.timeit()
>>> end - start
0.006420466001145542
>>> start = timeit.timeit()
>>> [1, 2, 3, 4].append(5)
>>> end = timeit.timeit()
>>> end - start
0.004373588995804312
>>> start = timeit.timeit()
>>> [1, 2, 3, 4].extend([5])
>>> end = timeit.timeit()
>>> end - start
0.0022365170007105917
```

Results for the first benchmark
```python
Fastest: [1, 2, 3, 4].extend([5])
0.0022365170007105917 seconds

Medium: [1, 2, 3, 4].append(5)
0.004373588995804312 seconds

Slowest: [1, 2, 3, 4] + [5]
0.006420466001145542 seconds
```

Second benchmarks from CLI
```python
lambdef ~ λ python -mtimeit -s'[1, 2, 3, 4] + [5]'
100000000 loops, best of 3: 0.00939 usec per loop
lambdef ~ λ python -mtimeit -s'[1, 2, 3, 4].append(5)'
100000000 loops, best of 3: 0.00938 usec per loop
lambdef ~ λ python -mtimeit -s'[1, 2, 3, 4].extend([5])'
100000000 loops, best of 3: 0.00993 usec per loop
```

Results for the second benchmark
```python
Fastest: [1, 2, 3, 4].append(5)
100000000 loops, best of 3: 0.00938 usec per loop

Medium: [1, 2, 3, 4] + [5]
100000000 loops, best of 3: 0.00939 usec per loop

Slowest: [1, 2, 3, 4].extend([5])
100000000 loops, best of 3: 0.00993 usec per loop
```

So when you add items continuously, you should prefer `.append()`, otherwise you should use `.extend()`.
Would a Nonprofit Twitter Clone Work?
Tags: twitter, nonprofit, foss, opensource
Published: 2018-10-24 15:34:14

---
title: "Would a Nonprofit Twitter Clone Work?"
published: true
description: "What is the next Twitter clone was open-source and ran by a nonprofit?"
tags: twitter,nonprofit,foss,open source
canonical_url: "https://www.feliciano.tech/blog/would-a-nonprofit-twitter-clone-work/"
cover_image: "https://www.Feliciano.Tech/assets/img/feature/default.png"
---

Many people have said that Facebook has gotten so big it should be considered a public utility.
I think this applies much more so to Twitter given the penetration and speed a single tweet can achieve for both local and global news.
Forget major cities and tech hubs, even the most remote parts of the world get their news via tweets.

This utility-like nature has been threatened and damaged many times before by decisions Twitter has made.
Some of these decisions due to what's in their best interest as a for-profit business.
They have an obligation to make money, I understand.

But what if they didn't?

<!--more-->

Many, many, many (did I say many?) people have attempted to make Twitter clones.
In the scope of this blog post, I see two large problems with these clones.

1. They are for-profit startups.
Or worse, not businesses at all.
Too many VCs have invested money in Twitter to want to let it fail now by investing in a competing project.
Also, being for-profit brings the same troubles Twitter has now.
Balancing privacy concerns and user freedom with the need to make a buck.
1. Many "clones" aren't really clones anyway.
These projects tend to create their own take on Twitter.
That's fair, that's their right as makers and entrepreneurs.
Personally, I mostly like the way Twitter works and would like an exact clone.
It's gotten as big as it has for a reason, right?

## So can we do it?

How possible would it be to create an identical Twitter clone, where the backing company is a nonprofit or foundation?
Where making money isn't one of the underlying goals but instead a sustainable communications and news platform for the world is?

If I remember correctly, one of Twitter's largest problems in the past as been scaling their infrastructure.
That remains an issue and for a nonprofit, paying for that infrastructure will be as well.

Still, I'm excited about the thought of cloning Twitter into an actual, public, technology infrastructure.
Even if it's just a pipe dream.
opunit! sanity checks for vms, containers, and servers.
Tags: devops, infrastructure, vms, docker
Published: 2018-10-24 15:30:12

---
title: opunit! sanity checks for vms, containers, and servers.
published: true
description: Sanity checks and tests for vms, containers, and remote servers.
tags: devops, infrastructure, vms, docker
---

When building/maintaining vm images, containers, and servers as part of your infrastructure or CI/CD pipeline how do you verify that you built the right thing?

`opunit verify` is a simple [open-source tool](https://github.com/ottomatica/opunit/) that will run sanity checks against an environment. Things like, is a service running on a port, can my instance resolve dns, did the right version of a package/tool get installed?

Running opunit, will then give a test report, much like a `mocha` or other testing frameworks.

![opunit](https://user-images.githubusercontent.com/9158546/47369653-29e20080-d6b2-11e8-8098-b64c59d282c6.png)

To setup the checks, you just need to provide a simple configuration file:

```yaml
- group:
    description: "Basic checks for startup"
    checks:
      - availability:
          port: 8080
          status: 200
      - version:          
         cmd: node --version
         range: ^10.x.x
```

You can also connect to running containers or remote servers:

```bash

# Just give address and ssh key:
$ opunit verify root@example.com:2222 -c {opunit.yml path} -i ~/.ssh/server_rsa

# Or name/sha of container
$ opunit verify -c {opunit.yml path} -t {docker container name or id}


```

Try it out! Request any new features you think would be cool!

```
npm install -g opunit
```
ReactJs component to plot in realtime
Tags: reatjs, plot, canvas
Published: 2018-10-24 15:21:59

---
title: ReactJs component to plot in realtime
published: true
description: 
tags: #reatjs #plot #canvas
---

http://github.com/mojtabamarashee/graph.js

![image](https://thepracticaldev.s3.amazonaws.com/i/5vpi58102ks1rv8ra3b7.png)
Top React Links of the Week 💜
Tags: react
Published: 2018-10-24 14:44:43

---
title: Top React Links of the Week 💜
published: true
description: The latest React Status Digest 
tags: react 
---

***The hottest links from [this week's issue](https://react.statuscode.com/issues/111?utm_source=devto&utm_campaign=react_roundup) of ReactStatus 💜***  


###  1: [Glean: A Refactoring Tool for React Code](https://www.wix.engineering/blog/finally-a-react-refactoring-tool-introducing-glean)

Glean simplifies and automates some of the most common React-related refactoring operations (e.g. exporting a JSX excerpt into a component) and integrates with VS Code.

### 2: [React v16.6.0 Released](https://reactjs.org/blog/2018/10/23/react-v-16-6.html)

A minor release with ‘a few new convenient features’ including React.memo which provides a way for function components to only be rerendered if their props change, a way to do code splitting using Suspense, and an easier way to consume Context from class components.

### 3: [Getting to Know React DOM’s Event Handling System Inside Out](https://medium.com/the-guild/getting-to-know-react-doms-event-handling-system-inside-out-378c44d2a5d0)

If you wanna step up your React game this article is for you. It will shed some light regards React’s internals and how it handles events.


### 4: [TypeScript Support Now in Create React App](https://github.com/facebook/create-react-app/pull/4837)

It’s not in a final release yet, but it won’t be far away.



###5: [React Suspense with Netlify Functions](https://www.netlify.com/blog/2018/10/18/react-suspense-with-netlify-functions/)

Netlify Functions (usually a serverless functions service you can use from Netlify’s static site hosting platform) provides a local way to fake a backend API to try out building a Suspense app.

### 6: [Understanding React 16.4's New Component Lifecycle Methods](https://blog.bitsrc.io/understanding-react-v16-4-new-component-lifecycle-methods-fa7b224efd7d)

 A hands-on guide to React’s new component lifecycle methods.



**📬 Want more?**

Join nearly 24,000 others, and get the latest React news and tutorials directly in your inbox: [Subscribe now](https://react.statuscode.com/?utm_source=devto&utm_campaign=react_roundup)
What tools do you use for server side PDF generation?
Tags: help, php
Published: 2018-10-24 14:33:14

---
title: What tools do you use for server side PDF generation?
published: true
tags: #help #php
---

Hey there, I'll keep it short. At our company we tried different approaches for PDF generation (server side, specifically in PHP) over the years but none made us happy. HTML to PDF using print stylesheets in the front (nowadays seems like a low tech puppetteer), domPDF for HTML to PDF in the back, or FPDF/TCPDF to manually place the elements on every page on the back.

For simple invoice-like PDFs we can use anything but currently I'm facing the task of generating a document with a complex design and dynamically generated data. For this I'm using FPDI + TCPDF loading a pregenerated PDF and then filling the gaps using coordinates mostly which is really boring and cumbersome.

Any thoughts?

Thanks!
React.lazy, What and how to use in your app
Tags: javascript, react
Published: 2018-10-24 14:09:42

---
title: React.lazy, What and how to use in your app
published: true
description: React.lazy - Code-Splitting with Suspense
tags: javascript,react
---

React 16.6 is out and with it comes the new [Lazy API](https://reactjs.org/docs/code-splitting.html#reactlazy). The Rreact.lazy function lets you render a dynamic import as a regular component. 

React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.


#### Usage: 

```js
const LazyComponent = React.lazy(() => import('./Component'));
```

#### Show a fallback with Suspense

Wrap the component where it's used with Suspense and pass a fallback. The fallback prop accepts any React elements that you want to render while waiting for the component to load.

```js
<Suspense fallback={<div>Loading Component...</div>}>
  <LazyComponent />
</Suspense>

```

<br/>  
<br/>  
<br/>  
#### I made a simple example to show 
  
  
The app shows a **Press Me!!** button which when pressed fetches a random user data from [randomuser](https://randomuser.me) then loads and renders the User component.

```js
const User = React.lazy(() => import('./User'));

....

<React.Suspense fallback={<div>Loading Component...</div>}>
  {user && <User user={user}/>}
  {loading ? (
    <div>Loading User...</div>
  ) : (
    !user && <button onClick={this.loadUser}>Press Me!!</button>
  )}
</React.Suspense>

```


**Live**: [react-lazy-example](http://vigneshm.com/react-lazy-example/)
**Code**: [github](https://github.com/vigzmv/react-lazy-example)


Run the app, open your Network tab in Dev console, Press the button and see the lazily loaded javascript chunk. 🎉🎉
PostgreSQL: Vacuum / Autovacuum
Tags: postgres, tutorial, autovacuum
Published: 2018-10-24 13:56:36

---
title: PostgreSQL: Vacuum / Autovacuum
published: true
description: Eliminate the bloat in your database with vacuum and autovacuum.
tags: postgresql, tutorial, autovacuum
---

Hey guys, in this article we'll be focusing on understanding a narrow but very critical aspect of performance tuning with PostgreSQL. Specifically, we're going to be discussing Vacuum and Autovacuum.

[PostgreSQL: Vacuum / Autovacuum](https://www.smoothterminal.com/articles/vacuum-autovacuum)


![PostgreSQL](https://blog.hostonnet.com/wp-content/uploads/2013/06/postgresql.png)
How to add a custom prompt to windows console
Tags: windows, cmder, clink, terraform
Published: 2018-10-24 13:49:25

---
title: How to add a custom prompt to windows console
published: true
description: How to add a terraform workspace prompt to cmder with clink (lua)
cover_image: https://thepracticaldev.s3.amazonaws.com/i/vtygux95d03t3k2v7gf5.jpg
tags: #windows, #cmder, #clink, #terraform
---
[Cmder][1] is an awsome package of software which replaces the default console `cmd.exe` or `powershell` on windows.

If you are in a git repo, you see the current branch in the prompt, colored in white if its clean or red if dirty. There are similar features for yarn, npm, ...

![Cmder Screenshot](https://thepracticaldev.s3.amazonaws.com/i/gq1toqolv48jbcjea13q.png)


Sometimes you want to add the output of **<YOUR TOOL>** to the prompt too. This can be done like this:

In my case i wanted to see on which [terraform workspace][2] i am. with terraform you can do this by running `terraform workspace show` in your terraform directory. this would output something like 

```shell
λ terraform workspace show
default
```

To do this you have to create a **[clink extension][3]**. Assuming that you installed cmder in `C:\Program Files\Cmder` you create a file called `terraform.lua` in `C:\Program Files\Cmder\vendor\clink-completions`

`terraform.lua`

```lua
local color = require("color")

local function is_terraform()
    for dir in io.popen([[dir ".\" /b /ad]]):lines() do 
        if dir == ".terraform" then
            return true
        end 
    end
    
    return false
end

local function terraform_prompt_filter()
    if is_terraform() then
        f = assert (io.popen ("terraform workspace show"))
        for line in f:lines() do
            terraform_context = '(workspace: ' .. line .. ')'
            if line == "production" then
                prompt_color = color.RED
            elseif line == "development" then
                prompt_color = color.GREEN
            else
                prompt_color = color.YELLOW
            end
            break
        end -- for loop
        f:close()
        terraform_context = color.color_text(terraform_context, prompt_color)
        clink.prompt.value = clink.prompt.value:gsub("\n", terraform_context .. "\n")
        return false
    end 
end

clink.prompt.register_filter(terraform_prompt_filter, 1)
```

this code checks if it is currently in a terraform directory by looking if the directory `.terraform` exists. it colors the workspace output in green if you are on `development` workspace, red if you are on `production` and yellow on all others. adapt the code for your needs.

i am sure that the lua code can be optimized, i am open for comments and enhancements.


links:
- cover image by Willi Heidelbach https://pixabay.com/en/puzzle-match-missing-hole-blank-693870/



[1]: http://cmder.net/
[2]: https://www.terraform.io/docs/state/workspaces.html
[3]: https://github.com/vladimir-kotikov/clink-completions