teleren/devto huggingface dataset:
What’s your alternative solution? Challenge #55
Tags: challenge, javascript, codenewbie, learntocode
Published: 2020-05-31 14:10:02

# About this series

This is series of daily JavaScript coding challenges... for both beginners and advanced users.

Each day I’m gone present you a very simple coding challenge, together with the solution. The solution is intentionally written in a didactic way using classic JavaScript syntax in order to be accessible to coders of all levels.

Solutions are designed with increase level of complexity.

## Today’s coding challenge

```
Shuffle an array of strings

```

(scroll down for solution)

## Code newbies

If you are a code newbie, try to work on the solution on your own. After you finish it, or if you need help, please consult the provided solution.

## Advanced developers

Please provide alternative solutions in the comments below. 

You can solve it using functional concepts or solve it using a different algorithm... or just solve it using the latest ES innovations.

By providing a new solution you can show code newbies different ways to solve the same problem.

## Solution

```javascript
// Solution for challenge49

var ar = ["Shuffle", "an", "array", "of", "strings"];

println(shuffleArray(ar));

// Shuffle array implemented using Fisher–Yates shuffle algorithm
function shuffleArray(ar)
{
    for(var i = ar.length - 1; i > 0; i--)
    {
        var j = randomInt(0, i - 1);
        
        var t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }
    
    return ar;
}

// Get a random int between min and max (both included)
function randomInt(min, max) 
{
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

```


To quickly verify this solution, copy the code above in this coding [editor](https://codeguppy.com/code.html) and press "Run".

> Note: The solution was originally designed for [codeguppy.com](https://codeguppy.com) environment, and therefore is making use of `println`. This is the almost equivalent of `console.log` in other environments. Please feel free to use your preferred coding playground / environment when implementing your solution.
Revshare.js - a Revshare Web Component
Published: 2020-05-31 14:06:58

## What I built
I went through a bunch of ideas - a Vue component library, implementing this in another site, or adding it to my existing sites.  
Eventually, I settled on this idea, and for the entire month of May (minus an OS reinstall and plus tonnes of Google searching), I spent some time exploring Web Components and Javascript!  

I've built [Revshare.js](https://github.com/kewbish/revshare), a small Javascript library to make revsharing with Web Monetization easier. It provides an interface for a `<rev-share>` element with a pointers attribute to make probabilistic revsharing easier.  

### Submission Category: 
Foundational Technology (or perhaps Creative Catalyst, I'm not sure where it fits...)

## Demo
Add a `<script src="http://unpkg.com/@kewbish/revshare"/>` tag to your head, and that's all you need to get started.  

```html
...
<rev-share pointers='["$jackie.wallet": 60, "$charlie.wallet": 40]'>
    <p>This is your revshared content!</p>
</rev-share>
...
``` 

If you'd also like to make your `<rev-share>` element exclusive, just add the `exclusive` attribute as well. (This will hide the element when Web Monetization is not enabled.)  

```html
...
<rev-share pointers='["$jackie.wallet": 60, "$charlie.wallet": 40]' exclusive>
    <p>This is your revshared, exclusive content!</p>
</rev-share>
...
```
It works using probabilistic revsharing, and the [docs I used as a guideline are available here](https://webmonetization.org/docs/probabilistic-rev-sharing).

## Link to Code
The project is available on GitHub:
[Note]: # (Our markdown editor supports pretty embeds. If you're sharing a GitHub repo, try this syntax: `{% github link_to_your_repo %}`)
{% github kewbish/revshare %}

...[on NPM](https://www.npmjs.com/package/@kewbish/revshare), and [on UnPkg](http://unpkg.com/@kewbish/revshare).

## How I built it 

This is built with the basic Web Components API. This was also my first proper Javascript project, and a great learning experience.  
I was a bit confused with all the callbacks available, and when exactly they fired. The Mozilla Docs were super useful in this case.  

If you'd like to see what else I've posted regarding the GFTW hackathon:
{% link https://dev.to/kewbish/halfway-through-gftw-200i %}  

## Additional Resources/Info 
There are a couple other Web Component submissions that also add Web Monetization functionality - go check those out!

If you have any feedback, let me know! (I'm a complete newbie with Javascript - be gentle `:)`.)
issue with npm Image slider package
Published: 2020-05-31 14:04:25

Hello,
I am using this npm package : https://www.npmjs.com/package/react-simple-image-slider

This package has the property : slideDuration and i am using this property in my code. however, it is not working. Rest of the properties are working.  
I am not sure where is the issue. 
can someone please suggest where i can get the support. ? Thanks 

Regards,
MacOS vs Windows
Published: 2020-05-31 14:02:23

I have a Catalina on my SSD, that was 2 months ago when I setup Hackintosh, though I found it very hard to adapt to it because I mainly use JetBrain IDEs and the keybinds seemed very different.

I wanna learn Swift, so ofcourse moving to MacOS is a necessity. What are the pros and cons of moving to MacOS vs Windows?
Hit 1000 followers in Dev.to 🎉 🎉 🎉
Tags: showdev, writing
Published: 2020-05-31 13:37:16

---
title: Hit 1000 followers in Dev.to 🎉 🎉 🎉
published: true
description: 
tags: showdev, discuss, writing, 
cover_image: https://media.giphy.com/media/lMameLIF8voLu8HxWV/giphy.gif
---
Hello everyone

I have hit 1000 followers in dev.to today 🎉. Thank you for supporting me in this journey. 

I will try to write more articles, tutorials in dev.to and add value to the community.

Thank you all 😊 😊
Convert an Array to an Object in JavaScript
Tags: javascript, discuss, typescript, react
Published: 2020-05-31 13:35:19

**Scenario-1**: If you want to convert an array [1,2,3] to an object with keys being the index of the array, then you can use __Object.assign__ and __spread operator__.

example:
```javascript
let myArr = [1,2,3];

// use destructuring
{...myArr} // {0: 1, 1: 2, 2: 3}
```
-------------------------------------------------------

**Scenario-2**: Suppose you receive a list of data in response from API and you want to cluster them with respect to date.

We can use the Array reduce method to convert that array to an object. 

```javascript
let myArray = [
  {data: [1,2,3], date: '1/3/2012'},
  {data: [1,2,3,10,11], date: '3/6/2012'},
  {data: [1,2,3,4,5], date: '2/5/2012'}
]

myArray.reduce((lastUpdatedValue, currentValue) => {
  lastUpdatedValue[currentValue.date] = currentValue.data;
  return lastUpdatedValue;
}, {});

output: 
{
  1/3/2012: [1, 2, 3]
  2/5/2012: [1, 2, 3, 4, 5]
  3/6/2012: [1, 2, 3, 10, 11]
}
```

Reduce method takes initial value which will be _lastUpdatedValue_ on first iteration and on each iteration we can just add key & value pair to that object.

On each iteration starting from empty object, date as key and data as value will be added to the object.


Thank you for reading!
What's the worst piece of advice you've ever received?
Tags: discuss, career
Published: 2020-05-31 12:58:21

---
title: What's the worst piece of advice you've ever received?
published: true
description: 
tags: Discuss, career
//cover_image: https://direct_url_to_image.jpg
---

I've had a few throughout my career:

**You should really focus on C, don't bother learning Python.**

Focus on whatever makes you happy. You'll be way more likely to succeed. 

**Slow down**

There are definitely times where it makes sense to slow down, especially if you're burning out. But momentum can be extremely useful throughout your career. 

**You shouldn't try to go to university, you don't have the attention span for it**

This was my grade 11 music teacher. If I had listened I wouldn't have gone into Computer Science. Don't listen to people who try to limit what you can accomplish.
Log Log Log .. how to deforest with Java CDI 
Tags: java, beginners, tutorial, codequality
Published: 2020-05-31 12:52:26

<h1>Hello World!</h1>

..sorry had to do it. Welcome to my first dev.to post, hopefully the first of many! 

I wanted to start off with a really simple utility that Java developers can *easily integrate* in their code and improve the codebase. 

Something I see very often, usually in legacy projects, is a logger being declared for every class. 

```java
1   public class MyClass {
2 
3       private static Logger logger = LoggerFactory.getLogger(MyClass.class);
4
5   ...
6   }
```
Realistically this won't be very resource intensive but we can definitely make improvements to simplify. 

![matrix](https://dev-to-uploads.s3.amazonaws.com/i/vyckl5ids9d0gcpvyrq0.jpg)


<figcaption>You don't know what it is, but it's there, like a splinter in your mind, driving you mad</figcaption>


Introducing.. logging with CDI! 

With CDI, we can inject a SL4J (or your favourite implementation) logger.

First thing we need to do is implement a logging producer using the [Injection Point API](https://docs.oracle.com/javaee/7/api/javax/enterprise/inject/spi/InjectionPoint.html).

```java
1   @ApplicationScoped
2   public class LoggerProducer {
3
4	   @Produces
5	   public Logger getLogger(final InjectionPoint ip) {
6		   return LoggerFactory.getLogger(ip.getMember().getDeclaringClass());
6	   }
7   }
```

We specify the scope of the class as *@ApplicationScoped*. The injection point API allows us to know the declaring class of the injected logger. 

Imports : 

```java
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
```

**Note : Ensure that the correct *@Produces* annotation is imported, not the JAX-RS producer**

Next step is to simply *@Inject* our logger into our class and begin to log.

```java
1   @ApplicationScoped
2   public class MyClass {
3 
4       @Inject
5       private Logger logger;
6       
7       public void myMethod(){
8          logger.info("My log!");
9       }
10   }
```
There we have it, an easy CDI logger. 

There are other implementations such as a [Lombok logger](https://projectlombok.org/api/lombok/extern/slf4j/Slf4j.html). However, there are some steps to make Lombok compatible with your IDE and I believe a CDI logger is easier to integrate with an existing codebase.
Improve your commits using vscode
Tags: git, vscode, tutorial, codenewbie
Published: 2020-05-31 12:43:09

Photo by [yancymin](https://unsplash.com/@yancymin) at [Unplash](https://unsplash.com/)

If you are like me and enjoy Visual Studio Code(vscode) as a tool keep reading. Today I want show a simple trick using this editor to commit our code in a more organized way(in my opinion). I have been using this editor for almost 3 years, but it wasn't till some months ago that I figure it that I can commit my files partially, that means I can create a commit that doesn't include every changes that I made to a single files.

I had to learn this because I was working in a project where the people in charge to review my code were very strict about the commits, things like the changes included were very important for them, in order to understand the work done by some developer. One of the main requirements was doesn't merge changes related to new features with changes regarding to refactorization, so in this way we separate concerns in our commits. At the beginning I struggled achieving this, but after learnt how files can be partially committed everything was easier.
## Partially commits in vscode

Suppose that we have the following changes:

![gif diff](https://dev-to-uploads.s3.amazonaws.com/i/z80h5jk9w9axcstnw34n.png)

As we can see here we have implemented a new feature function and also refactored our `getSessionKey` function, we want include this two changes in two different commits . 

In vscode with for do that we select the changes that we want include in the next commit doing right click on the diff view and `Stage Selected Ranges` 

![Select ranges](https://dev-to-uploads.s3.amazonaws.com/i/8342pcvugl3n33faq666.png)

> _The editor allow us during the diff view, add changes on different selections, so we can select for example lines 5-10 and stage them, after that select lines 30-40 and stage them, repeating this until we have staged all the changes that we want commit._ 

After this we can see that our file is in the staging area ready for be included in our next commit, but note that we have staged only our change related to new feature. 

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

At this point we can proceed to commit and do the process again for the remaining changes. 

As you can see this is very easy and allow us to separate concern in our commits. I think that this is very helpful in many occasions when  we work and make many changes not being related or unable to live in the same commit, also with this approach we end with a detailed history of our work which for communicate our intentions and facilitates the code review process.

If you know another useful trick that we can use in vscode share it in the comments, thanks for your read.

_PS: I love the new UI for writing post thanks to [@devteam](https://dev.to/devteam)_
Concerns regarding using payment with graphql and js in general
Tags: help, security, webdev, graphql
Published: 2020-05-31 12:42:18

Hi everyone,

I am having concerns processing payments with graphql or js in general, what are your expriences on this subject?

Would you process payments using react vue or SSR solutions without worries of attacks?

Also I am looking for an advice here from people that work in web security and ethical hacking.

Update:For anyone looking for the suggestion from @dakotalewallen  you can find it here [Stripe Checkout](https://stripe.com/docs/payments/checkout/accept-a-payment)

Thank you in adavnce

Credits:

Credit card image [link](https://pixabay.com/vectors/credit-card-withdrawals-calculation-1369111/)

@dakotalewallen - thanks for suggesting stripe checkout
Template Blogger Scratch
Tags: Blogger
Published: 2020-05-31 12:13:38

&lt;?xml version ="1.0" encoding="UTF-8" ?&gt;<br />
&lt;!DOCTYPE html&gt;<br />
&lt;html xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/expr'&gt;<br />
&lt;head&gt;<br />
&lt;meta content='width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0' name='viewport'/&gt;<br />
<br />
&lt;b:skin&gt;&lt;![CDATA[<br />
]]&gt;&lt;/b:skin&gt;<br />
&lt;/head&gt;<br />
&lt;body&gt;<br />
&lt;b:section id='main'&gt;<br />
&lt;b:widget id='Blog1' locked='false' title='Blog Posts' type='Blog' visible='true'/&gt;<br />
&lt;/b:section&gt;<br />
&lt;/body&gt;<br />
&lt;/html&gt;<br />
<div>
<br /></div>
Record and Tuples - New Datatypes in JavaScript
Tags: javascript, node, webdev, ecma
Published: 2020-05-31 11:54:11

---
title: Record and Tuples - New Datatypes in JavaScript
published: true
description: Now deep immutablity is possible in JavaScript
tags: javascript, node, webdev, ecma
---
Record (Analogous to objects) and Tuple (Analogous to arrays) are the new types that are coming soon in JavaScript. At the time of writing, they are in Stage 1.

**Syntax** 
Notice the # before curly braces or square bracket. This is the Syntactical difference between objects/arrays and records/tuples.

```javascript 
const record = #{
    foo: "FOO",
    bar: "BAR"
};
const tuple = #["FOO", "BAR"]
```

**Deep Immautablity**
Record and Tuple are deeply immutable, unlike `Object.freeze`. The value of a record/tuple or the values inside nested record/tuples cannot be changed once it is defined. 

```javascript
const record = #{
    foo: "FOO",
    bar: "BAR",
    foobar: #["FOO", "BAR"]
};
const tuple = #["FOO", "BAR", #{foo: "FOO", bar: "BAR"}]

record.foo = "BAR" // Error
record.foobar[0] = "BAR" // Error
tuple[0] = "BAR" // Error
tuple[2].foo = "BAR" // Error
```
**Deep Equality**
IMO this is the best feature of record/tuple. In objects and arrays, you can only compare by their reference but in a record or a tuple, you can compare by its values. It is also possible to compare values of nested record/tuple

```javascript
const record2 = #{foo: "FOO", bar: "BAR", foobar: #["FOO", "BAR"]}
const tuple2 = #["FOO", "BAR", #{foo: "FOO", bar: "BAR"}]

record.foobar === #["FOO", "BAR"] // true
tuple[2] ===  #{foo: "FOO", bar: "BAR"} // true

record === record2 // true
tuple === tuple2 // true
```

**Features same as Object/Array**
You can use them just like you use objects and arrays.
Computed property names, shorthand notation, spread operator, Destructuring, rest operator.
```javascript
const f = "foo"
const bar = "BAR"
const values = #{a: 1, b: 2}

const record = #{
    [f]: "FOO",     // Computed property names
    bar,            // Short hand notation
    ...values       // Spread operator
};

console.log(record.foo == "FOO") // true
console.log(record.bar == "BAR") // true
console.log(record.a == 1) // true
console.log(record.b == 2) // true

const { foo: destructedFOO, ...rest } = record //  Destructuring and rest operator

console.log(destructedFOO == "FOO") // true
console.log(rest.a == 1) // true
console.log(rest.b == 2) // true
console.log(rest.bar == "BAR") // true
```

**Limitations**
Cannot use Record and Tuples on `lhs` while destructuring, symbol key not supported in the record, the nested Object/Array/Class can not be converted to record.
```javascript
// Using a record or tuple literal on the lhs is a SyntaxError
const #{ a, b } = #{ a: 1, b: 2 } // SyntaxError
const #[a, b] = #[1, 2] // SyntaxError

// Record and Tuples only support primitive data types 
const record = #{ instance: new SomeClass()} //Error
const record = #{ object: { a: 1}} //Error
const tuples = #[new SomeClass()] // Error
const tuples = #[1, [2]] // Error

// Records can only have String keys, not Symbol keys
const record = #{ [Symbol()]: #{} }; //Error
```
Windows10新規設定 2020/06
Tags: docker, windows, wsl2
Published: 2020-05-31 12:03:58

2004 May Updateが来たのでサブノートのOSを初期状態に戻して環境構築してみたメモ。

- Windows10を初期状態に戻す→ユーザーデータ削除。を選択(初期化に2時間くらいかかった)
- マカフィーをアンインストールしてWindows標準のアンチウイルスを有効化。某システムを停止してFB等にアクセスできるようにする。
- EdgeとChromeの最新版を導入。色々不便なので1PasswordをセットアップしてWindowsのログインアカウントをローカルからマイクロソフトアカウントを使うように変更
- 2004 May Updateを導入(30分くらいかかった)
- Dropbox(クライアントは入ってた)でログインし、スマートシンク有効状態で良く使うフォルダを選択同期(スマートシンク有効なら全同期でも良いのかもしれない)
- CorvusSKKを入れた(SKK辞書はDropboxで同期してあるのを取り込む)
- キーをリマップ。今回はPowerToysを入れてKeyboard Managerで入れ替えた。CapsLockをControlにして、右のAltとControlをVK243(全角/半角)に。CorvusSKKは全角半角で日本語モードと英数モードがトグルする。これでまともに入力できるようになったけど、CapsLockはControlになったものの、それがLockされてるような動きをしてる感じ？([issueが上がってた](https://github.com/microsoft/PowerToys/issues/3326))
- この後の作業に備えてWindows TerminalとGit for Windowsを導入。どっちも(と、前述のPowerToys)折角なのでwingetを使って入れてみた。(Gitのほうは`winget install -e Git`じゃないと入らないので注意
- [Git Bash for Windowsでlnが使えるように](https://qiita.com/ucho/items/c5ea0beb8acf2f1e4772#comment-250af72ab706bd611549)して、Dropboxで共有している設定ファイル類へリンクを張る
- WSL2を導入する。今回はUbuntu 20.04を入れてみた(WSL2への変換、思ったより時間かかった(10分くらい))
  - https://qiita.com/tomtwinkle/items/92c8c399f9aad62c45b6
  - https://www.kkaneko.jp/tools/wsl/wsl2.html
- WSL2とUbuntuを入れたらWindows Terminalの起動シェルの一覧に自動的に追加された。お手軽
- Docker for Windowsをインストール。WSL2を使うよう設定する
  - https://hub.docker.com/editions/community/docker-ce-desktop-windows/
  - インストール時にEnable WSL2(略 をONに
  - WSL2をbackendにする設定は最初から有効だったので、リソースとしてUbuntu 20.04を使う設定をONにしてDocker Engineをリスタート
Daily Developer Jokes - Sunday, May 31, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-05-31 12:00:28

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

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

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

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

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

<!-- 
Joke text:
___Q:___ Why do Java developers wear glasses?

___A:___ Because they don't C#!
 -->
How do I Build app without :app:bundleReleaseJsAndAssets error?
Tags: reactnative, react, node, typescript
Published: 2020-05-31 11:45:49

Good Day !
I need help , I need fix this error when building apk using gradlew assembleRelease , configuration is succesful , but when executing at 40% there throws an error :

```> Task :app:bundleReleaseJsAndAssets_SentryUpload FAILED
error: An organization slug is required (provide with --org)

Add --log-level=[info|debug] or export SENTRY_LOG_LEVEL=[info|debug] to see more output.
Please attach the full debug log to all bug reports.

FAILURE: Build completed with 2 failures.

Task failed with an exception.
-----------
What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
> Process 'command 'cmd'' finished with non-zero exit value 1

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

Task failed with an exception.
-----------
What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets_SentryUpload'.
> Process 'command 'cmd'' finished with non-zero exit value 1

Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights```