teleren/devto huggingface dataset:
while loops that have an index
Tags: perl, testing, loop, each
Published: 2019-06-27 10:28:45

Perl5 got this syntax that allow to use a while loop without having to explicitly incrementing an index by doing an `i++`. It is made possible by the [`each` function](https://perldoc.pl/functions/each).

Let's demonstrate this in a simple test that check that and array and an array ref contains the same things:

```perl
# t/01_foo_order.t    
use v5.18;
use Test::More tests => 3; 

my $events_arr_ref = get_events();
my @expected_events = ('foo', 'bar', 'baz');

while ( my ( $i, $event ) = each( @$events_arr_ref )) {
  is @$events_arr_ref[$i], 
    $expected_events[$i], 
    "Array element [ $i ] is $expected_events[$i]";
}

done_testing();

sub get_events {
  return [ 'foo', 'bar', 'baz' ];
}

```

Let's execute our test:

```bash
prove -v t/01_foo_order.t
1..3
ok 1 - Array element [ 0 ] value is foo
ok 2 - Array element [ 1 ] value is bar
ok 3 - Array element [ 2 ] value is baz
ok
All tests successful.
Files=1, Tests=3,  0 wallclock secs ( 0.03 usr  0.00 sys +  0.07 cusr  0.00 csys =  0.10 CPU)
Result: PASS
```

`while ( my ( $i, $event ) = each( @$events_arr_ref )) {}` makes possible to iterate on the `$events_arr_ref` array reference and for each element found, initializing `$i` and `$event` with the right value. 

This is quite the same than a `for` loop except that you don't have to increment the index and that it must be used in case you want to iterate on the whole array.

I use it quite often, can be handsome if you want to avoid `$_`. Just yet another [TIMTOWTDI](https://en.wikipedia.org/wiki/There%27s_more_than_one_way_to_do_it)...

**Sources**:

- [*automatically get loop index in foreach loop in perl*](https://stackoverflow.com/questions/974656/automatically-get-loop-index-in-foreach-loop-in-perl) on StackOverflow
- The [Perl5 documentation for the *`each` function*](https://perldoc.pl/functions/each)
Poll: why does clicking a DEV comment link display the comment in isolation?
Tags: discuss, meta
Published: 2019-06-27 14:34:36

---
title: Poll: why does clicking a DEV comment link display the comment in isolation?
published: true
description: Do you like DEV's ux for linking to comments?
tags: discuss, meta
---

For those who aren't familiar, when you click on a comment link in DEV.to, you are taken to a page which displays only that comment in isolation ([example here](https://dev.to/ben/comment/329n)). If you want more context, you can (must) click `VIEW POST` or `VIEW FULL DISCUSSION` links. Medium works similarly.

## Question: Do you like this UX?

To me, a comment is inherently contextual.

- Is there ever a time when viewing a comment without context is desireable? When / why?
- Is there a technical reason for the current UX?
  - Github comment links are powered by anchor tags, so the browser simply displays the full page and scrolls to the relevant section (very intuitive).
Crypto Exchange clone Scripts to start your exchange like Binance
Tags: bitdealclonescript
Published: 2019-06-28 12:05:33

---
title: Crypto Exchange clone Scripts to start your exchange like Binance
published: true
description: Get a cryptocurrency clone script to start your exchange as like binance,coinbase,etc
tags: bitdeal clonescript
---

Bitdeal - Leading Clone Script Provider, furnishes the best clone scripts of top crypto exchanges to build your own cryptocurrency exchange as like Okex,coinbase,upbit,binance and lot more. We develop and deploy the best clone scripts with many new features and plug-ins to make your exchange stand unique in the crowd.

15 clone script to start your crypto exchange like binance, bitstamp and more 

Binance Clone Script 
Bitstamp Clone Script 
Bithump Clone Script
Coinbase Clone Script
Bitfinex Clone Script
Poloniex Clone Script
Okex Clone Script 
Paxful Clone Script 
Kraken Clone Script 
Upbit Clone Script 
Korbit Clone Script 
Bitflyer Clone Script 
Coincheck Clone Script 
Gemini Clone Script 
Bitmax Clone Script

Bitdeal - Leading Clone Script Provider, provides the best exchange clone scripts across the world to start your own exchange as like Binance, Coinbase, Okex, Poloniex, Bithump, etc.,

We provide features like an automated trading bot, Unhackable Admin panel, User-friendly trader panel, etc with secured API's. You can start your own online crypto exchange as like popular exchanges to acquire the larger portion of the crypto market.

[Book a live demo for any exchange clone script st Bitdeal !!](https://www.bitdeal.net/cryptocurrency-exchange-clone-scripts)
Around the Web – 20190628
Tags: blog
Published: 2019-07-22 13:55:41

---
title: Around the Web – 20190628
published: true
tags: Blog
canonical_url: https://wipdeveloper.com/around-the-web-20190628/
cover_image: https://wipdeveloper.com/wp-content/uploads/2017/07/WIPDeveloper.com-logo-black-with-white-background.png
series: Around the Web
---

And now for somethings to read (or watch) over the weekend, if you have some spare time that is.

## [Puns and Jokes](https://www.gooddaysirpodcast.com/221)

**Good Day, Sir! Show**  – Jeremy Ross – In this episode, we discuss what was learned from scanning 10.2 billion lines of Apex code, Tableau, the top 10 highest-paid CEO’s, Hacker News asks what Salesforce is, and Salesforce Certifications and Trailhead fraud.

## [The cost of JavaScript in 2019 · V8](https://v8.dev/blog/cost-of-javascript-2019)

**v8.dev**  – Jun 25 – Note: If you prefer watching a presentation over reading articles, then enjoy the video below! If not, skip the video and read on. One large change to the cost of JavaScript over the last few years has been an improvement in how fast browsers can…

## [Google’s new reCAPTCHA has a dark side](https://www.fastcompany.com/90369697/googles-new-recaptcha-has-a-dark-side)

**Fast Company**  – Jun 27, 8:00 AM – We’ve all tried to log into a website or submit a form only to be stuck clicking boxes of traffic lights or storefronts or bridges in a desperate attempt to finally convince the computer that we’re not actually a bot. For many years, this has been…

## [Raspberry Pi 4 on sale now from $35](https://www.raspberrypi.org/blog/raspberry-pi-4-on-sale-now-from-35/)

**Raspberry Pi**  – Eben Upton – Jun 23, 11:00 PM – We have a surprise for you today: Raspberry Pi 4 is now on sale, starting at $35. This is a comprehensive upgrade, touching almost every element of the platform. For the first time we provide a PC-like level of performance for most users, while…

## Till Next Week

Want to share something? Let me know by leaving a comment below or emailing [brett@wipdeveloper.com](mailto:brett@wipdeveloper.com)  or following and tell me on [Twitter/BrettMN](https://twitter.com/BrettMN).

Don’t forget to sign up for **[The Weekly Stand-Up!](https://wipdeveloper.com/newsletter/)** to receive free the [WIPDeveloper.com](https://wipdeveloper.com/) weekly newsletter every Sunday

The post [Around the Web – 20190628](https://wipdeveloper.com/around-the-web-20190628/) appeared first on [WIPDeveloper.com](https://wipdeveloper.com).
How to Start Your Day Calmly 
Tags: calm, focus, software, development
Published: 2019-06-29 08:32:25

---
title: How to Start Your Day Calmly 
published: true
description: As a software developer, it is imperative to have a calm start to the day and remain focused all day. So here is how I found that calm when I followed the 9 steps.. 
tags: #calm #focus #software #development
---

1) Wake up early

2) Don't touch the mobile, don't receive any calls either. Make sure you had turned off the WiFi/Data before falling to sleep last night.

3) Get Fresh

4) Go for a walk

4.1) Give a few rounds

4.2) Freehand Exercise

4.3) Meditate/Pray whatever works

(Order may vary from 4.1 to 4.3)

5) Spend some time with elderly persons, preferably wise

(in my case an aged road-side tea-stall owner)

6) Don't touch the mobile yet

7) Do some reading (Newspaper maybe)

8) Get Ready

8.1) Shower

8.2) Breakfast

(Order may vary from 7 to 8.2)

9) Head out

* Now you are ready to turn on WiFi/Data and take calls

For someone who is not consistent, this is hard to follow in a daily basis, so I hardly have a calm start to the day :|
graphql reddit
Tags: graphql, materia
Published: 2019-06-29 14:01:28

Postman now supports GraphQL! - https://blog.graphqleditor.com/graphql-postman/
Generate code from your GraphQL schema with a single function call - https://graphql-code-generator.com/

Introduction to Materia — An API Builder made for Frontend developers https://medium.com/materia-in-depth/introduction-to-materia-an-api-builder-made-for-frontend-developers-ded3830ab60f

Materia

https://getmateria.com/
https://github.com/materiahq/materia-server
Card Hover Effect | CSS | Cubic Bezier Updated
Tags: codepen, sass, html, code
Published: 2019-06-30 00:21:01

{% codepen https://codepen.io/KaioRocha/pen/orpKxq %}

Hey there! Here's my new pen, check it out also on my youtube video to see the whole process https://youtu.be/Izm8SutcQv4
Fixing the World With Software
Tags: career, motivation, technology, life
Published: 2019-06-30 15:29:35

---
title: Fixing the World With Software
published: true
description: There are so many big problems the world faces today. We hear about them in the news every day. You want to do something good in the world. You want to make a change. But you like building software. What can a software developer do to make the world a better place?
tags: career, motivation, technology, life
canonical_url: https://jorin.me/fixing-the-world-with-software/ 
cover_image: https://thepracticaldev.s3.amazonaws.com/i/5mmrcbpd5d7qowx3eqof.jpg
---
 
There are so many big problems the world faces today. We hear about them in the news every day.
You want to do something good in the world. You want to make a change. But you like building software.
What can a software developer do to _make the world a better place_?

Probably most of humanity had big problems in their time. In some way or another we might always fight for survival, for our existence. Uniquely nowadays is the global scale of our problems. The challenges we are facing have never been more complex and as part of our information-driven society the media constantly keeps reminding us of the threads we are facing. At the same time our abilities and the reach of our actions has never been greater.

I mostly see three obvious challenges nowadays:

1. **Keeping the global human society in order to prevent fatal conflicts between different groups of humans.** Even with free and diverse societies we need to find ways to solve conflicts peacefully. Modern warfare has advanced to a point where any wrong action could make the whole planet uninhabitable.
2. **Finding ways to control human health and prevent epidemics.** We still understand surprisingly little about the biology we are made of. A single virus could wipe out all of humanity.
3. **Managing to live in harmony with our environment.** The impact humans have on the planet has become so big that we have to find ways to keep our planet's ecosystem in balance. We need to find sustainable ways to deal with [carbon emissions](http://worrydream.com/ClimateChange/), air pollution, energy consumption, waste, water pollution, food production and many other issues.


The most frightening thing with these issues is that they seem too big for anyone to solve and it is difficult to even know where to start.

[John Kay](https://www.johnkay.com/) has some great advice for achieving complex goals:

{% youtube _BoAtYL3OWU %}

But how can software help approaching these problems?

These issues seem to be only solvable by politicians and policy makers, scientists and engineers, company managers and journalists.

_And this, I think, is the key:_

**I don't believe software can change the world.  Humans can.** I think our role as software developers is to support the ones that can make a change. We build tools and platforms to enable others.

**If you are building software and want to tackle critical issues, ask yourself who you are building software for. Think about how you can enable others.**

_[(cover photo by NASA)](https://unsplash.com/photos/Q1p7bh3SHj8)_
Decoupling code and secrets
Tags: codebases, secretsmanagement, decoupling, software
Published: 2019-07-05 18:16:35

---
title: Decoupling code and secrets
published: true
description: A personal insight on better practices for dealing with secrets management in codebases
tags: codebases, secrets management, decoupling, software
cover_image: https://www.howtogeek.com/wp-content/uploads/2015/11/encryption.png.pagespeed.ce.r1UYcb9ZXB.png
---

I was talking with a colleague on switching from [Vault](https://www.vaultproject.io/) to [Kubernetes secrets](https://kubernetes.io/docs/concepts/configuration/secret/) the other day. To my surprise a lot of **our application code was dependent on our Vault implementation**. Our migration would need opening a PR for every service we maintain. While trying hard not to grimace I started wondering on ways how to avoid this from the start. Two alternatives came to my mind which I'll describe here.


# Solution A
An alternative is to wrap the logic of dealing with Vault's specifics and bundle that into a library. As result, once migrating to K8s secrets we could change the library's code once and it will impact the services using it. But it wouldn't be a cross-language solution i.e. you would have to maintain one library for Go and another library for Node.js.

# Solution B
Another solution is to inject the secrets into the application process as environment variables. This approach decouples your applications from your secret management approach: the changes happen once for all your applications. Since it allows for more flexibility and portability than the solution A, this solution would be a better choice for a long-term scenario. This solution also follows the [12 Factor App](https://12factor.net/config) approach for configuring applications.

# In conclusion
Handling secrets for applications is a complex subject. Even if you use a solution that facilitates the concerns I covered here - being language-agnostic and having it configured as part of the provisioning of your images/instances - you're not exempt of application logic logging secrets in the wild.
You will spend more time thinking, designing and implementing decoupled components.  It will also make your architecture easier to maintain and easier to apply changes.


### Further reading
If you want to read on secrets management in detail I've selected a few resources as follow up:
- [Secrets management guide](https://blog.cryptomove.com/secrets-management-guide-approaches-open-source-tools-commercial-products-challenges-db560fd0584d)
- [Managing Passwords and Application Secrets: Common Anti-Patterns](https://blog.envkey.com/managing-passwords-and-secrets-common-anti-patterns-2d5d2ab8e8ca)
- [Secret Management Architectures: Finding the balance between security and complexity
](https://medium.com/slalom-technology/secret-management-architectures-finding-the-balance-between-security-and-complexity-9e56f2078e54)



Many thanks to [Ruben Bridgewater](http://twitter.com/BridgeAR), [Ben](http://twitter.com/BenedekGagyi), and [Ujjwal Sharma](http://twitter.com/ryzokuken) for reviewing a first draft of this blog post.
Was not able to comment out jsx in react, so I made my own snippets
Tags: vscode, productivity, react, tutorial
Published: 2019-07-04 14:47:12

While I was on a react project, I was not able to comment out jsx which was really frustrating. 

The way we comment out jsx is
` {/* comment */}`

But the default comment function on vscode doesnot comment out jsx. So, I made my own snippets to comment out jsx. 

First, open command palette

![](https://thepracticaldev.s3.amazonaws.com/i/twr7gox7txgou6dg393c.png)

Search for configure user snippets. But before choosing, look for the language type on your work file.

![](https://thepracticaldev.s3.amazonaws.com/i/rkg2czlkqde414wb5hnx.png)

Then choose javascript or javascriptreact.

![](https://thepracticaldev.s3.amazonaws.com/i/bwgcm1sqlz0gjod4hh4c.png)

After that you will see some examples of how you can make a snippets. Copy below code and paste it.

`"Comment out jsx": {
 "prefix": "jsx",
 "body": [
           "{/*",
	   "${TM_SELECTED_TEXT}",
	   "*/}"
	  ],
 "description": "Comment out jsx"
}`

Save the file and you are good to go. 

Select the code you want to comment and insert snippets.
Why we wrote (yet) another state management tool
Tags: javascript, react, frontend, redux
Published: 2019-07-05 15:13:56

## Redux vs. MobX?  
Most current state management solutions don't let you manage state using hooks, which causes you to manage local and global state differently and have a costly transition between the two.

Which brought us to look for solutions that use React hooks. The problem is that hooks only run inside React components.

## What about Context?!
Using plain React Context is not the best solution for state management:  
- When managing global state using Context in a large app, you will probably have many small, single-purpose providers. Soon enough you'll find a Provider wrapper hell.
- When you order the providers vertically, you can’t dynamically choose to depend on each other without changing the order, which might break things.
- Context doesn't support selectors, render bailout, or debouncing

## Our guidelines
To have global state management, we need a top-level provider. We wanted the developer to manage immutable state using hooks. We also wanted to allow for selectors and render-bailout for performance reasons. And lastly, we wanted to make sure there is no initialization code so that packages that use state management are easily pluggable into your app.

Iterating over and over the API got us to a solution that we feel is easy and powerful. We called the library Reusable. Here is the API:

### Provider:
```jsx
const App = () => (
  <ReusableProvider>
    ...
  </ReusableProvider>
)

```

### Define a store:
```javascript
const useCounter = createStore(() => {
  const [counter, setCounter] = useState(0);
  
  return {
    counter,
    increment: () => setCounter(prev => prev + 1)
  }
});
```

### Subscribe to the store:
```javascript
const Comp1 = () => {
  const something = useCounter();
}

const Comp2 = () => {
  const something = useCounter(); // same something
}
```

### Use a selector:
```javascript
const Comp1 = () => {
  const isPositive = useCounter(state => state.counter > 0);
   // Will only re-render if switching between positive and negative
}
```


## Find out more
To find out more and start experimenting with Reusable, visit the repo:  
[https://github.com/reusablejs/reusable](https://github.com/reusablejs/reusable)

You can also check out the video from ReactNext, where Maayan Glikser and myself present the library:
{% youtube oy-6urveWzo %}
Video: Disagreements are learning opportunities 📹
Tags: learning, debate, arguments, disagreements
Published: 2019-07-06 15:09:22

---
title: Video: Disagreements are learning opportunities 📹
published: true
description: When people passionately debate something, I'm immediately curious and interested. Some of my best learning moments have come out of observing an intense debate.
tags: learning, debate, arguments, disagreements
cover_image: https://thepracticaldev.s3.amazonaws.com/i/v5ga9d5cugyk1gvix0fz.png
---

When people passionately debate something, I'm immediately curious and interested. Some of my best learning moments have come out of observing an intense debate.
Container with the Most Water - Code Challenge
Tags: ruby, javascript, beginners, challenge
Published: 2019-07-06 21:33:30



[Leetcode Problem 11](https://leetcode.com/problems/container-with-most-water/)



This problem is pretty straight forward.

Given an array of heights, find the two indices that could contain the most water between them.


Generally there are two ways of solving this, the brute force method, and the two pointer method.


### Brute Force

This method will calculate every possible combination possible to determine the answer. This requires a nested loop resulting in a complexity of O(n^2).


Javascript
```
var maxArea = function(height) {
    let mostWater = 0
    
    for (let l = 0; l < height.length - 1; l++) {
        for (let r = height.length - 1; r > l; r--) {
            mostWater = Math.max(mostWater, (Math.min(height[l], height[r])*(r-l)))
        }        
    }
    return mostWater
}
```

A better way of doing this is to utilize two pointers.


### Two Pointer Method

For this method we utilize two pointers that are placed on opposite ends of the array to iterate through once resulting in a time complexity of O(n). The area between the current left (l) and right (r) indexes and if the area is larger than the current max, it is set as max.

The indices are moved based on which one is smaller or if equal the left one in this situation. It is arbitrary which is checked in the if statement.

Javascript
```
var maxArea = function(height) {
    let max = 0
    
    let l = 0
    let r = height.length - 1
    
    while (l < r) {
        if (height[l] > height[r]) {
            max = Math.max(height[r] * (r-l), max)
            r--
        } else {
            max = Math.max(height[l] * (r-l), max)
            l++ 
        }       
    }
    
    return max
};
```

In Ruby...
```
def max_area(height)
    max_area = 0
    
    l_idx = 0
    r_idx = height.length - 1
    
    while (r_idx > l_idx)  
        if height[r_idx] >= height[l_idx]
            max_area = [(height[l_idx] * (r_idx - l_idx)), max_area].max
            l_idx += 1
        else 
            max_area = [(height[r_idx] * (r_idx - l_idx)), max_area].max
            r_idx -= 1
        end        
    end
    
    return max_area
end
```

For more readability you can always separate out the max_area (ruby) or max (javascript) into multiple lines.  

Javascript
```
if (height[l] > height[r]) {
    maybeMax = height[r] * (r-l)
    r--
} else {
    maybeMax = height[l] * (r-l)
    l++ 
}        
    
max = Math.max(maybeMax, max)

```

Ruby
```
if height[r_idx] >= height[l_idx]
    maybe_max = height[l_idx] * (r_idx - l_idx)
    l_idx += 1
else 
    maybe_max = height[r_idx] * (r_idx - l_idx)
    r_idx -= 1
end

max_area = maybe_max if maybe_max > max_area
```

Decided to mix up the syntax on the last line for variety since the Ruby and JS solutions look so similar.
Never use array_merge in a loop in PHP
Tags: performance, php, loop
Published: 2019-07-08 19:13:09

---
title: Never use array_merge in a loop in PHP
published: true
description: array_merge in loop is a performance killer.
tags: performance, php, loop
---


I often see people using `array_merge` function in a `for`/`foreach`/`while` loop 😱 like this :


```php
$arraysToMerge = [ [1, 2], [2, 3], [5, 8] ];

$arraysMerged = [];
foreach($arraysToMerge as $array) {
    $arraysMerged = array_merge($arraysMerged, $array);
}
```

It's a very bad practice because it's a performance killer (especially in memory).

Since PHP 5.6, there is a new operator : the spread operator

```php
$arraysToMerge = [ [1, 2], [2, 3], [5,8] ];

$arraysMerged = array_merge([], ...$arraysToMerge);
```

* No more performance problem
* BONUS : no more `for`/`foreach`/`while` loop
* BONUS : process in *one line*


Look now at your code base to find code that you can improve 👩‍💻👨‍💻!

---

## Thank you for reading, and let's stay in touch !
If you liked this article, please share. You can also find me on [Twitter/X](https://twitter.com/enjimmyklein) for more PHP tips.