teleren/devto huggingface dataset:
Benefit of 'key' prop in React
Tags: react, javascript
Published: 2020-01-29 04:47:34

If you are a beginner in a react js you may have encountered the key warning in the console while listing elements on the page in a loop.

KEY  is a very important and useful concept in react js in improving user experience 

Now the question is how?? -- Refer the image below
 
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/jjk1740dybdj720z0jfz.JPEG)

In the image above on the left side, we have a list were 2 elements are rendered, then now
we add the third element at end of the list as shown at right, react will compare both and will get to know that it needs to update only the third element in the list.

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

But if we add the element at first position as shown in image above(Diana added th list) the react match will fail and it re-render all list again.
to avoid this re rendering, we can use the "key" prop in the list which will keep track and update only elements that are new. as shown in the below image. ..so simple :)

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/eydknsac9jfxr9bhcbi5.JPEG)
Random number generation in Python
Tags: python, beginners
Published: 2020-01-30 15:53:41

In <a href="https://python.org">Python</a> you can generate random numbers with the random module. To load this module use the line

```python
    import random
```

To generate 10 numbers between 1 and 10 you can use:

```python
import random

for x in range(10):
    print(random.randint(1,11))
```

*These are pseudo-random numbers, but for most purposes they are good.*

The lowest possible number here is 1 and the maximum number 10. The for loop is used to repeat this 10 times.

If instead of random integers you want random floats, you can use uniform() as shown in <a href="https://pythonbasics.org/random-numbers/">this example</a>

## Random examples

To get a larger number of random numbers, you can change the for loop. If 
you want 20 numbers use:

```python
import random

for x in range(20):
    print(random.randint(1,11))

```

For 50 numbers use:

```python
import random

for x in range(50):
    print(random.randint(1,11))
```

You get the idea. To get numbers between 1 and 100 you can use:

```python
print(random.randint(1,101))
```

or in a loop

```python
import random

for x in range(50):
    print(random.randint(1,101))
```


**Related links:**
* <a href="https://docs.python.org/3.8/library/random.html">Python documentation on random module</a>
* <a href="https://pythonspot.com/random-numbers/">More random data examples</a>
* <a href="https://pythonspot.com/">Learn Python</a>
Serverless and the Dreaded CORS
Tags: serverless, webdev, cors, design
Published: 2020-02-02 06:42:39

While venturing farther in the Serverless world, I started making a list of things I encountered on my journey that I would like to delve deeper into; plainly because, I figured learning just enough to make something work was never going to satisfy my voracious appetite. Towards cementing my understanding, I started making unorganized one-liner notes as reference material. This article (_and the ones that will follow, hopefully_) are logical extensions of those notepad entries.

My very first entry on the list, was CORS -  more commonly known as *Cross Origin Resource Sharing*. 

1. So what EXACTLY is CORS?
Cross Origin Resource Sharing (__CORS__) enables a web-app to access resources OUTSIDE of its domain in a controlled manner and offers flexibility + functionality over the default same-origin security policy.

2. What is Same-Origin Security Policy?
A policy, under which, a web browser permits web page #1 to access data in web page # 2, ONLY IF both web pages have the same origin i.e. belong to the same domain.

3. How is CORS relevant in Serverless?
Web API Backends being a popular use case in serverless, a web page might need to make calls to a backend API that lies on a different domain i.e. of different origin; therefore, requiring the call to be CORS-friendly.

4. What is a common error indicating that CORS is NOT enabled?
No 'Access-Control-Allow-Origin' header is present on the requested resource

4. How is CORS implemented?
Two main ways:
  - Headers
     - Access-Control-Allow-Origin header: Included in the response to specify the origin of where the request originated from as the value for allowing access to the resource's contents.
 - Pre-flight requests (*__GET, POST, HEAD methods excluded__*)
     - Browser will send a preflight request to the resource using the OPTIONS method; in response to which, the resource you're requesting will return with methods that are safe to send and may optionally return the headers that are valid to send across.

5. Ways that CORS can be exploited? (i.e. Poor design practices)
 - Allowing access to any domain in the origin field
 - Allowing access to all sub-domains (_including currently non-existent sub-domains, that could potentially be malicious_)
 - Origin header specification supporting the value **null**
 - Trusting origins with vulnerabilities to XSS i.e. Cross Site Scripting
 - Whitelisting trusted subdomain using HTTP
 - Lower security standards for authentication on intranets/internal websites

6. Ways to prevent CORS-based attacks?
 - Allowing trusted websites ONLY
 - Avoid whitelisting null
 - Avoid use of wildcards in intranets/internal websites
 - Judiciously configure cross-domain requests by correctly specifying origin against Access-Control-Allow-Origin header
 - Stringent configuration of server-side security policies.


*__Credits: Major shout-out to Alex DeBrie for his amazing article on Serverless and CORS that helped me a lot while writing this post.__*
While Loop – JavaScript Series – Part 13
Tags: javascript, codenewbie, tutorial, beginners
Published: 2020-02-02 17:29:57

Suppose we are going to print 1 to 10 on the console. But how we can do it ? We can do it easily 
```
console.log(1)
console.log(2)
...
console.log(9)
console.log(10)
```
But this is not a good way to do it. Currently we can do it because it's only ten times. But suppose we need to print 1 - 100. How to do it ?
This is where we use loops. We're going to use `while` loop today!
While is easy. Just remember what we learned in our last tutorial. While loop syntax is - 
```
while (condition) {
  // code block to be executed
}
```
Let's write some real codes now. If we wants to print 1 - 100 then we are going to store the values in variable and we are going to start from 1. So `var number = 1`
Now we are going to start our while. While and the condition will be. 
```
while (number < 101) {
  //code block that we wants to do
}
```
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/t7dh0znny6yr8sttydgw.png)

Now we are going to print the values from the first one. We need to increase the value of number to break the condition, if the condition doesn't break then it will stuck forever. So we always break the loop condition

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

See the result in browser

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

Do you understand the while loop ?

You can see the graphical version here
{% instagram B8En8fkgtQf %}

Source Codes - { Check commits }
{% github nerdjfpb/javaScript-Series %}

Originally it published on [nerdjfpbblog](https://blog.nerdjfpb.com/javascript-part-13/). You can connect with me in [twitter](https://twitter.com/nerdjfpb) or [linkedin](https://www.linkedin.com/in/nerdjfpb/)!
How would you want the rich text editor for your end users to be?
Tags: javascript, typescript, discuss
Published: 2020-02-02 11:08:32

Should it be WYSIWYG or some kind of markup language, like Markdown?

How do I make it powerful without compromising security?

I have just created [Showdown-Extra](https://github.com/patarapolw/showdown-extra) with [Showdown.js](https://github.com/showdownjs/showdown) and [DOMPurify](https://github.com/cure53/DOMPurify), but recently, I think it would be best if I just use a WYSIWYG editor, like [Quill.js](https://quilljs.com/).

{% github patarapolw/showdown-extra no-readme %}

I have also created a demo. <https://patarapolw.github.io/showdown-extra/>

BTW, my plan is not yet something big like [Discourse](https://www.discourse.org/), but a self-hosted commenting system. I should probably limit features.

{% github patarapolw/aloud no-readme %}

Some other options, I think, are basically markdown language with custom components, like MDX (React)...
Quick tip: NTLM / Windows pass-through authentication with Selenium and ChromeDriver
Tags: chromedriver, selenium, testing, registry
Published: 2020-02-02 15:42:27

---
title: Quick tip: NTLM / Windows pass-through authentication with Selenium and ChromeDriver
published: true
date: 2020-02-02 14:58:00 UTC
tags: chromedriver,selenium,testing,registry
canonical_url: https://seankilleen.com/2020/02/ntlm-pass-through-authentication-with-chromedriver/
---

## Challenge

I was on a project for a web application that used Windows Active Directory authentication for internal users.

We had some automated acceptance tests using Selenium and ChromeDriver. However, these tests would always fail on our build agents, and we couldn’t figure out why. There were errors around authentication.

## Solution

After a hunch and some intense googling, we found that there are registry settings where you can enable Chrome to allow ChromeDriver to accept NTLM authentication negotiation by default.

The key is to add the following to your registry, to ensure you’re enabling the desired auth schemes for the desired domains.

An example `.reg` file is below that you can modify to use. After running applying these settings to our build agents, the problems were resolved.

```
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\Software\Policies\Google\Chrome]
"AuthNegotiateDelegateWhitelist"="*.companydomain.org,*.companydomain.coop"
"AuthSchemes"="basic,digest,ntlm,negotiate"
"AuthServerWhitelist"="*.companydomain.org,*.companydomain.coop"

```

Happy testing!
crafting a workday
Tags: productivity
Published: 2020-02-02 15:43:36

Originally posted on [josephchekanoff.com](https://josephchekanoff.com/blog/crafting-a-workday/).

Running a development agency is really difficult. I (currently) don't have a workday "structure" that invokes creativity **and** growth. 

[@dhh](http://twitter.com/dhh) shared a great workday schedule on Twitter:

{% twitter 1202243381490937859 %}

To incentivize creating an environment that promotes productivity _and_ focus on the the things that matter, I'm putting it out here as a reminder to myself. Here's my version of "the perfect workday."


| Hour | Focus |
|:--|:--|
| 5am | Walk Dog + Run |
| 6am | Shower + Breakfast  |
| 7am | Reflection + Standup  |
| 8am-12pm | Build things |
| 12pm | Walk Dog + Lunch (Friday Yoga) |
| 1pm-3pm | Project Management  |
| 3pm-5pm | Prospecting + Business Development
| 5pm | Gym or Bike |
| 6pm | Dinner + Walk Dog |
| 7pm-8pm | Family time or Event  |
| 9pm | Walk Dog + Read / TV |
| 10pm | Bed |

Things to note:
- Lots of time outside (running, biking, dog).
- AM focus (when I'm most productive/creative) on building.
- Frequent Breaks
- At least 7 hours of sleep.
- This is a goal.

> "It is your commitment to the _process_ that will determine your _progress_."
> _I'm (still) a fan of [James Clear](http://jamesclear.com)._

If [Chek Creative](http://chekcreative.com) is going to grow at the aggressive pace we have outlined as a team, we'll all need systems for getting things done. For me, that is contributing to our product development, planning for our team's success, and prospecting new business on a daily basis.

How do you design your workday?
[solution] Des champs personnalisés en plein coeur
Tags: webdev, tutorial, joomla
Published: 2020-02-05 17:11:18

---
title: [solution] Des champs personnalisés en plein coeur
published: true
date: 2019-11-26 09:41:31 UTC
tags: webdev,tutorial,joomla
canonical_url: 
---

Salut les joomlers de l'extrême!

Un ami joomler qui se reconnaitra m'a demandé comment faire pour intégrer $this->item->jcfields dans un module comme mod\_articles\_latest

J'ai accepté le défi et je partage le resultat avec vous. La communauté de Joomla!. La famille des joomlers.

Découvrez sans plus attendre l'exemple de code à utiliser, bien commenté pour réussir le challenge.

Bon courage et à bientôt pour de nouvelles astuces

 

[Voir comment faire](https://gist.github.com/alexandreelise/e04d417c9f911ce2ab2a3e931142e89b "Exemple de code pour le module articles latest")
Heap Sort
Tags: algorithms, programming, java
Published: 2020-02-03 14:57:58

The heap sort is useful to get min/max item as well as sorting. We can build a tree to a min heap or max heap. A max heap, for instance, keeps a parent being not smaller than children.
The following code is for a max heap. The __top__ indicates the next insertion position in the array which is identical to the array size.
```java
	class Heap {
		private int[] arr;
		private int top;
		public Heap(int sz) { arr=new int[sz]; top=0; }
		public void push(int num) {
			arr[++top]=num;
			climbUp(top);
		}
		public void pop() {
			int min=arr[1];
			arr[1]=arr[top--];
			climbDown(1);
			arr[top+1]=min;
		}
		public int size() { return top; }
		private void climbUp(int p) {
			if(p<=1||arr[p]<=arr[p/2]) return;
			swapAt(p,p/2);
			climbUp(p/2);
		}
		private void climbDown(int p) {
			int np=p*2;
			if(np>top) return;
			if(np<top&&arr[np+1]>arr[np]) np++;
			if(arr[p]>=arr[np]) return;
			swapAt(p,np);
			climbDown(np);
		}
		private void swapAt(int p,int q) {
			int t=arr[p];
			arr[p]=arr[q];
			arr[q]=t;
		}
	}
```
How to fetch subcollections from Cloud Firestore with React
Tags: google, firebase, firestore, react
Published: 2020-02-03 16:54:07

---
title: How to fetch subcollections from Cloud Firestore with React
published: true
description: 
tags: google, firebase, firestore, react
series: Getting started with Firebase Cloud Firestore
---
# More data!

First, I add more data to my database. Just to make things more realistic. For each cinema I add a subcollection `movies` in which I add some `movies`. Each movie has this info

```
name: string,
runtime: string,
genre: string,
release_date: timestamp
```

In Firestore, data can also have different structure (NoSQL's power!) but, for simplicity, I follow the canonical way.


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

I add one movie for the first cinema and two movies for the second one.

# Fetching the subcollection

I make the cinemas list clickable, so when I click an item I load movies scheduled for that specific cinema. To do this, I create a function `selectCinema` that will perform a new `query` to fetch a specific subcollection.

```typescript
...
const selectCinema = (cinema) => {
  database.collection('cinemas').doc(cinema.id).collection('movies').get()
    .then(response => {
      response.forEach(document => {
        // access the movie information
      });
    })
    .catch(error => {
      setError(error);
    });
}
..
{cinemas.map(cinema => (
  <li key={cinema.id} onClick={() => selectCinema(cinema)}>
    <b>{cinema.name}</b> in {cinema.city} has {cinema.total_seats} total seats
  </li>
))}
```

At this point is easy managing the show/hide logic with React using the `state`.

{%gist https://gist.github.com/rossanodan/e97e19d31000019a3b705412662eca46 %}

# A working demo

Gaunt but working.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dh613zks8s877vy0cxih.gif)
What are you going to do if/when your position gets automated?
Tags: discuss, devdiscuss, career
Published: 2020-02-04 14:53:20

---
title: What are you going to do if/when your position gets automated?
published: true
description: Thinking out loud.
tags: discuss, devdiscuss, career
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/in9z5qf1to2s4l3rv4c3.jpeg

---

Let's take it real far: what are you going to work because your job got automated? (Not a speculation on whether it can be automated, but it actually just *is*)

Would you continue to design and code?
Ripping Out Node.js - Building SaaS #30
Tags: python, django, saas, node
Published: 2020-03-05 18:05:24

{% youtube PyZDK-D0eWE %}

In this episode, we removed Node.js from deployment.  We had to finish off an issue with permissions first, but the deployment got simpler.  Then we continued on the steps to make deployment do even less.

Last episode, we got the static assets to the staging environment, but we ended the session with a permissions problem.  The files extracted from the tarball had the wrong user and group permissions.

I fixed the permissions by running an Ansible task that ran `chown` to use the `www-data` user and group.  To make sure that the directories had proper permissions, I used `755` to ensure they were executable.

Then we wrote another task to set the permission of non-directory files to `644`.  This change removes the executable bit from regular files and reduces their security risk.

We ran some tests to confirm the behavior of all the files, even running the test that destroyed all existing static files and starting from scratch.

With the permissions task complete, we could move onto the fun stuff of ripping out code.  Since all the static files are now created in Continuous Integration, there is no need for [Node.js](https://nodejs.org/en/) on the actual server.  We removed the [Ansible](https://www.ansible.com/) galaxy role and any task that used Node.js to run JavaScript.

Once Node was out of the way, I moved on to other issues.  I had to convert tasks that used `manage.py` from the Git clone to use the manage command that I bundled into the [Shiv](https://shiv.readthedocs.io/en/latest/) app.  That work turned out to be very minimal.

The next thing that can be removed is the Python virtual environment that was generated on the server.  The virtual environment isn't needed because all of the packages are baked into the Shiv app.  That means that we must remove anything that still depends on the virtual environment and move them into the Shiv app.

There are two main tools that still depend on the virtual environment:

1. [Celery](http://www.celeryproject.org/)
2. [wal-e](https://github.com/wal-e/wal-e) for [Postgres](https://www.postgresql.org/) backups

For the remainder of the stream, I worked on the `main.py` file, which is the entry point for Shiv, to make the file able to handle subcommands.  This will pave the way for next time when we call Celery from a Python script instead of its stand-alone executable.


Show notes for this stream are at [Episode 30 Show Notes](https://www.mattlayman.com/building-saas/ripping-out-nodejs/).

To learn more about the stream, please check out [Building SaaS with Python and Django](https://www.mattlayman.com/building-saas/).
KineMaster - The Top Video Editor For Android
Published: 2020-02-04 06:16:26

KineMaster is a video editing application that brings a full suite of editing tools to iPhone, iPad, iPod Touch, and Android devices. Designed for productivity on the go, KineMaster delivers the ability to create professional video content without requiring a laptop or desktop computer

(https://bigtechbyte.com/kinemaster-pro/)

BEST editing ever! I've used Kinemaster for the past year or so. I must say I'm not tech-savvy whatever and this app is extremely easy to use. I use it for my Youtuber channel (LifeWithLowee) Kinemaster is has a YouTuber channel (KineMaster) that shows you what new features and how to use their app.

Music and Sound Effect Clips

Music and Sound Effect Clips can be added to projects by tapping Audio on the Media Wheel to open the Audio Browser, and then selecting the desired music or sound effect track and tapping Add to place it on the Timeline starting at the time of the playhead’s current position.

Selecting a Music or Sound Effect Clip will bring up the Options Panel, which contains tools used to edit audio, which will be discussed in more detail below.

Please note that while on Android, KineMaster will display almost any available music or sound effect file on your device, on iOS devices, music must either be in iTunes on your device or in the KineMaster Internal folder. The KineMaster Internal folder is the same folder that is seen in folder sharing in iTunes on your computer

Files with DRM (Digital Rights Management), also known as copyright protection, cannot be imported into KineMaster, as it breaks the terms of service for most music services.
A use case for the Object.entries() method
Tags: javascript, beginners, webdev
Published: 2020-02-05 07:15:03

---
title: A use case for the Object.entries() method
published: true
description: Split up objects with Object.entries() and Array.filter
tags: #javascript #beginner #webdev
cover_image: https://user-images.githubusercontent.com/17259420/73816918-134db300-47ea-11ea-97eb-1109473ab723.jpg
---


*Perhaps you already know about Object.keys() and Object.values() to create an array of an objects keys and values respectively. However, there's another method `Object.entries()` that will return a nested array of the objects key and values. This can be very helpful if you'd like to return only one of these pairs based on the other's value.*

# A clean way to return keys in an Object

Often times in form with form data there will be a list of choices presented to users that are selectable with radio buttons. The object's data returned from this will look something like this...

```javascript

const myListValues = {
  'selectionTitle': true,
  'anotherSelectionTitle': false
}
```
We could store these objects with their keys and value in our database as they are, however just adding the `key` name for any truthy value would be sufficient. By passing our `myListValues` object into Object.entries() we can filter out any falsey values from our newly created array and then
return the keys as a string. 

###Execution 

We'll make use of not only Object.entries(), but also the very handy array methods `filter()` and `map()`. The output from `Object.entries(myListValues)` will be...

```javascript 

 const separatedList = [
   ['selectionTitle', true ], 
   ['anotherSelectionTitle', false ]
 ]; 
```

We now have an array that can be utilise `.filter()` and `.map()` to return our desired result. So let's clean up our `separatedList` array a bit. 

```javascript

 const separatedFilteredList = 
   Object.entries(myListValues).filter([key, value] => value);

 const selectedItems = separatedFilteredList.map(item => item[0]);
```

There we have it. Our selectedItems array is now just a list of the key names from our objects who's value was truthy. This is just one of many use cases for perhaps a lesser know object method. I'd love to see some more interesting use cases you may have come up with.