teleren/devto huggingface dataset:
react-native detect when user takes a screenshot
Tags: reactnative, screenshot
Published: 2021-09-03 21:43:54

---
title: react-native detect when user takes a screenshot 
published: true
description: how to detect when the user takes a screenshot; Listen for screenshot action react-native
tags: reactnative, screenshot
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/65fe9ag2mn0hv13eubsa.png
---

 This is really important when you communicate with family, colleagues, or close friends on the internet, you have to be sure that sensitive information won't be copied and re-shared with someone else. Popular applications like *Instagram*, *Snapchat* long ago implemented this simple feature: **screenshot detection**. 
 

![demo taking a screenshot on Android](https://media.giphy.com/media/TpDMJfK7nmyQThsJtI/giphy.gif?cid=790b761164e5ba08a35b4e56cd6dcada922260deedde5f8b&rid=giphy.gif&ct=g)

---

How things are in the react-native ecosystem? For current moment I found three modules that compatible with latest version of [react-native@0.65.x](https://reactnative.dev/blog/2021/08/06/version-065) (see below)



| Module name | iOS | Android | Stats |
|---|---|---|---|---|
| [react-native-detector](https://github.com/AzizAK/react-native-detector) | ✅ | ✅ | Quality: 75%; Popularity: 14%; Maintenance: 98% | 
| [expo-screen-capture](https://docs.expo.dev/versions/latest/sdk/screen-capture/#addscreenshotlistenerlistener) | ✅ | ✅ | Quality: 95%; Popularity: 38%; Maintenance: 98% | 
| [react-native-screenshot-notifier](https://github.com/rhdeck/react-native-screenshot-notifier) |❌ | ✅ | Quality: 51%; Popularity: 6%; Maintenance: 48% |
| [react-native-screenshot-detect](https://github.com/iamacup/react-native-screenshot-detect) | ✅ |❌ | Quality: 20%; Popularity: 3%; Maintenance: 33% |
 

---

> ⚠️ Note: Both modules has one limitation  on **Android**, that required a `READ_EXTERNAL_STORAGE` permission

For Android to understand that screenshot was taken modules use [`ContentObserver`](https://developer.android.com/reference/android/database/ContentObserver), to listen that a picture file was created and filename includes `"screenshot"`


---

if you have any question I am glad to discuss them in the comments!

(c) MurAmur ❤️
idle thought on my declining participation in dev communities
Tags: discuss, worklifebalance, softskills, mentalhealth
Published: 2021-09-03 21:40:56

---
title: idle thought on my declining participation in dev communities
published: true
description: 
tags: discussion, worklifebalance, softskills, mentalhealth
//cover_image: https://direct_url_to_image.jpg
---

It’s been a good long time since I’ve posted here, attended a meet up (digital or otherwise), or engaged on dev Twitter. I was wondering why that is, and I realized that this is the happiest I’ve ever been in my job, and when that happens, my urge to do side projects and write about software dries up a bit. Not sure I have a grand thesis here. It’s great to have a job that’s fulfilling and allows work life balance in a way that I’m unused to. However, my lack of drive makes me a little sad because in the past I’ve gotten a lot of value out of my interactions with the community.

Has anyone else experienced something similar? How does having a comfortable job versus an overly stressful job impact your community involvement, home life, or other behaviors? If you’re now primarily work from home and weren’t before, how does that impact where you spend your time? I’m eager to hear other perspectives.
Day 445 : Cherry Picking
Tags: hiphop, code, coding, lifelongdev
Published: 2021-09-03 21:04:34

_liner notes_:
- Professional : Pretty chill day. Had a couple meetings. Reviewed some pull requests and merged them. Reviewed the Web Components I created with my manager to make sure everything looks good. Day went by super quick.

- Personal : Last night I went through some tracks for the radio show. Watched an episode of Boruto. Did some research for my side project. Went to bed early since I since I had an early meeting.

![A shallow lake in Krka Nat'l Park, Croatia surrounded with a forest and waterfalls](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qljy55p9usva9vqlsafo.jpg)

Going to finish putting together the radio show tomorrow. It's Bandcamp Friday, so I'll be cherry picking some new joints. I want to get some work done on my side project. Keeping it short, want to get the weekend started! It's a long weekend, so see you on Tuesday.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 194sL-X2omY %}
Easy Random Color
Tags: javascript, css, tricks
Published: 2021-09-03 21:00:05

One way to generate a random color is to randomize the hue argument of the css hsl. This value is in degrees 0-360 (think colorwheel):

{% codepen https://codepen.io/ZevanRosser/pen/bGRwGvR default-tab=js,result %}

The other arguments can be randomized as well if you need random saturation and lightness… like this:

{% codepen https://codepen.io/ZevanRosser/pen/JjJRjLQ default-tab=js,result %}

_See more stuff like this over @ [Snippet Zone](https://snippet.zone/)_
Rails 7 - Sneak Peek [part1]
Tags: rails, programming, opensource, news
Published: 2021-09-03 20:58:06

### New method
```ruby
# replaces the common pattern of finding sibling objects without one self:
relation.excluding(post, another_post) 
```

### Lets see how we can use it
A simple example for this shows can you simply filter other posts in your usually built onboarding project and it seems quite cool
```ruby
class Post
  def simliar_posts
    user.posts.excluding(self)
  end
end
```

### Lets actually think if it useful in a common place
But wait a second... we have a really messy implementation of `BROADCAST` in ActionCable where we need to filter our own sent messages everytime, and this new friend may look promising to use.
What if we implement a `MULTICAST`, or even add a parameter to our usual `broadcast_to` method in ActionCable making it look like this [source](https://github.com/rails/rails/blob/a44fbb5dcacd3281116f7d9881a25e8f08f729a4/actioncable/lib/action_cable/server/broadcasting.rb#L42):
```ruby
def broadcast(message, exclude_self: true)
  server.logger.debug { "[ActionCable] Broadcasting to #{broadcasting}: #{message.inspect.truncate(300)}" }

  payload = { broadcasting: broadcasting, message: message, coder: coder }
            ActiveSupport::Notifications.instrument("broadcast.action_cable", payload) do
  encoded = coder ? coder.encode(message) : message
    if exclude_self
      server.pubsub.exclude(self).broadcast broadcasting, encoded
    else
      server.pubsub.broadcast broadcasting, encoded
    end
  end
end
```

THOUGHTS??
ClassName Behaviors
Tags: javascript, css, tricks
Published: 2021-09-03 20:51:53

{% codepen https://codepen.io/ZevanRosser/pen/XWgjWzy default-tab=js,result %}

This associates behavior with class names, so the class names can be combined to mix and match behavior.

Read a <a href="https://snippet.zone/2021/09/02/classname-behaviors/">bit more about it here.</a>

_See more stuff like this over @ [Snippet Zone](https://snippet.zone/)_
async-await in Javascript class
Published: 2021-09-03 20:25:19

One of the projects that I am working on recently has to use async methods and also call it from another method of the same class. Thought of writing this as it may help others

It's actually pretty simple. You can invoke the async method from another method by using an immediately invoking function. 
Let's see it with an example. I have a class Todo, its constructor invokes an async method 
```
class Todo {
    constructor() {
        this.apiUri = 'https://someapiuri';
        (async () => await this.getTodoItems())();
    }

    async getTodoItems() {
        const response = await fetch(this.apiUri);
        return await response.json();
    }
}

```
A simple PSR-4 autoloader
Tags: php, webdev, programming, wordpress
Published: 2021-09-03 19:27:36


Have you even used a `composer.json` file purely for the need of registering a PSR-4 autoloader? I have, and it always felt a little weird to require such a hunk of code for such a simple task. It adds a `vendor` folder and a bunch of empty files. I don't like that overhead when it's not necessary.

So here is a drop-in alternative. You can for example use this in a WordPress theme or plugin. 

```php
spl_autoload_register(function (string $class_name): void {
    // Map the namespace to the corresponding folder
    $namespace_mapping = [
        'DoekeNorg\\BlogTheme' => 'src',
    ];

    foreach ($namespace_mapping as $namespace => $directory) {
        if (
            strpos($class_name, $namespace = trim($namespace, '\\')) !== 0
            || (!$directory = realpath(__DIR__ . DIRECTORY_SEPARATOR . trim($directory, DIRECTORY_SEPARATOR)))
        ) {
            continue; // Class name doesn't match or the directory doesn't exist
        }

        // Require the file
        $class_file = $directory . str_replace([$namespace, '\\'], ['', DIRECTORY_SEPARATOR], $class_name) . '.php';
        if (file_exists($class_file)) {
            require_once $class_file;
        }
    }
});
```

## How to use this autoloader

1. Save this file as `autoload.php` for example, and fill out the correct values for `$namespace_mapping`
2. `require` this file inside your bootstrap file or theme/plugin entry file

That's it. Now you can reference any class with that namespace, and the autoloader will require the correct file.

The mapping is relative to the location of the `autoload.php` file, so you can also do things like this:

```
|-- blog-theme
    |-- src
    |-- vendor
        |-- autoload.php <- the autoloader 
    |-- public
        |-- index.php <- entry file
```

When you require `vendor/autoload.php` inside `public/index.php` you can adjust your mapping to the following,
and the resolving will still work.

```php
 $namespace_mapping = [
    'DoekeNorg\\BlogTheme' => '../src',
];
```

**Couldn't you make this into a nice class?**
Of course, but would that *really* be better?

**Is it a big win over Composer?**
No, a big win it is not, a small one; maybe. It's also not ment to replace Composer in any way, because that is way more optimized. It's just that for a simple plugin or theme you don't need the overhead Composer creates.
Git alias, crie comandos personalizados para turbinar seu git
Tags: git, codenewbie
Published: 2021-09-03 19:26:36

Já pensou em customizar seus comandos do Git?

Os aliases podem turbinar e facilitar o seu dia-a-dia, transformando seus comandos de terminal do git.

Você pode criar aliases para abreviar os comandos ou personalizá-los como quiser 🤩

Vamos lá...

---

💡 *IMPORTANTE: após configurar, é necessário reabrir o terminal para refletir as novas configurações.*

### Criar alias direto no arquivo de configuração

1 - Abra o arquivo `.gitconfig` (localizado no diretório principal), você pode abri-lo através do seu diretório ou via terminal:

```bash
open ~/.gitconfig
```

**este comando irá abrir o arquivo em seu editor padrão para que você possa editá-lo*

2 - Adicione seus aliases da seguinte forma:

```
[alias]
	comando_reduzido = comando_original
	comando_reduzido = comando_original
	comando_reduzido = comando_original
```

Prontinho! ⚡
Agora é só reabrir seu terminal para que os comandos possam começar a funcionar.


### Lista de comandos úteis

arquivo `.gitconfig`

```
[alias]
  cm = commit -m
  acm = !git add -A && git commit -m
  lg = log --oneline
  lgg = log --all --graph --decorate --oneline --abbrev-commit
  b =  branch
  co = checkout
  cb = checkout -b
  st = status
  stt = status -sb
  pl = pull origin
  pu = push origin -u
  plr = pull origin -r
  pp = push origin
  pf = push origin +HEAD
  config = config --global -e
  up = !git pull --rebase --prune $@ && git submodule update --init --recursive
  save = !git add -A && git commit -m '~SAVEPOINT :construction:'
  wip = git add -A && git commit -m '~WIP :construction:'
  undo = reset --soft HEAD~1
  amend = commit --amend
  ops = commit --amend --no-edit
```


## Utilizando os aliases

Vamos supor que eu tenha configurado meus aliases conforme a lista acima, então toda vez que eu quiser utilizar um alias, basta rodar o comando:

```bash
git <alias>
```

👩🏻‍🍳 Exemplo:

```bash
git save
```

Seria o mesmo que digitar

```bash
git add .

git commit -m '~SAVEPOINT :construction:'
```

muito mais prático!



## Criar alias via linha de comando

Também é possível configurar seus aliases via linha de comando:

```bash
git config --global alias.<seu-alias> <comando-original>

# exemplo
# git config --global alias.st status
```

No exemplo acima, depois de configurado, ao invés de ter que digitar `git status`, basta digitar `git st`.

> A opção `–global` quer dizer que o alias será aplicado no arquivo .gitconfig dentro do seu diretório home, e por isso o alias será aplicado em todos seus repositórios. Sem esta opção, o alias será aplicado no .gitconfig do repositório atual, logo só será aplicado apenas a ele.}}

- [https://gist.github.com/kelvinst/331aff32508e2517afbd](https://gist.github.com/kelvinst/331aff32508e2517afbd)

📖 [saiba mais](https://haacked.com/archive/2014/07/28/github-flow-aliases/)



--
*Foto da capa: <a href="https://unsplash.com/@synkevych?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Roman Synkevych</a> on <a href="https://unsplash.com/s/photos/git?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>*
Pizza Cost Per Inch Calculator
Tags: python, computerscience, functional
Published: 2021-09-03 19:23:39

```python
# pizza_cpi_calc.py
#   This program calculates the cost per square inch of a circular pizza,
#   given its diameter and price. The formula for area is A = Pi X radius^2.
# by: Scott Gordon

import math


# Create a function to calculate the area of a pizza.
def area_of_pizza(radius):
    area = math.pi * radius**2
    return area


# Create a function to calculate the cost per square inch of a pizza.
def cost_psi_pizza(price, diameter):
    radius = diameter / 2
    pizza_area = area_of_pizza(radius)
    cost_psi = price / pizza_area
    return cost_psi


# Run both functions to demonstate their output
def main():
    # Get user input for pizza diameter and price.
    pizza_diameter = int(
        input("What is the diameter of your pizza in inches? "))
    pizza_price = float(input("How much did the pizza cost? "))
    print(
        f"Your cost per square inch of your pizza is ${cost_psi_pizza(pizza_price, pizza_diameter):.2f}")


main()
```
Photo by <a href="https://unsplash.com/@iavnt?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Ivan Torres</a> on <a href="https://unsplash.com/s/photos/pizza?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Web Scraping in C#: Building Your First C-Sharp Scraper from Scratch
Published: 2021-09-03 19:22:24

C# is a general-purpose programming language that is mainly used in enterprise projects and applications, with roots in the C family – making it a highly efficient language to have in your tool belt.

Because of its popularity, C# has a vast set of tools that allow developers to implement elegant solutions, and web scraping isn’t the exception.

In this tutorial, we’ll create a simple web scraper using C# and its easy-to-use scraping libraries. Plus, we’ll teach you how to avoid getting your bot blocked with a simple line of code.

However, there are a few things we need to cover before we start writing our code.

scraperapi.com/blog/web-scraping-in-c-sharp/
Introduction to SOAP API
Published: 2021-09-03 19:15:25

SOAP is a necessary protocol that helped introduce the widespread use of APIs.   

SOAP is the acronym for Simple Object Access Protocol. It is a standardized protocol that relies on XML to make requests and receive responses. Even though SOAP is based on XML, the SOAP protocol is still in wide usage.   

SOAP APIs make data available as a service and are typically used when performing transactions involving multiple API calls or applications where security is the primary consideration.     

SOAP was initially developed for Microsoft in 1998 to provide a standard mechanism for integrating services on the internet regardless of the operating system, object model, or programming language.

### How SOAP APIs work

The “S” in SOAP stands for Simple, and for a good reason — SOAP can be used with less complexity as it requires less coding in the app layer for transactions, security, and other functions.   

**Primary characteristics of SOAP**

1. Extensibility
SOAP allows for extensions that introduce more robust features, such as Windows Server Security, Addressing, and more.

2. Neutrality
SOAP is capable of operating over a wide range of protocols, like UDP, JMS, SMTP, TCP, and HTTP.can operate.

3. Independence
SOAP API responses are purely based on XML. Therefore SOAP APIs are platform and language independent.

### When to Use SOAP APIs

Developers continue to debate the pros and cons of using SOAP and REST. The best one for your project will be the one that aligns with your needs.     

SOAP APIs remain a top choice for corporate entities and government organizations that prioritize security, even though REST has largely dominated web applications. It is more secure than REST as it uses WS-Security for transmission along with a Secure Socket Layer.SOAP also has more excellent transactional reliability, which is another reason why SOAP historically has been favored by the banking industry and other large entities. 
 

### Difference between SOAP and REST APIs
 
SOAP is more secure than REST as it uses [WS-Security](https://www.ibm.com/docs/en/app-connect/11.0.0?topic=security-ws) for transmission along with a Secure Socket Layer. SOAP is stateful as it takes the entire request as a whole. REST involves multiple methods while dealing with requests and responses.   

Head over to [RapidAPI Hub](https://rapidapi.com/hub?utm_source=dev.to%2Frapidapi&utm_medium=DevRel&utm_campaign=DevRel) and explore tens of thousands of SOAP APIs you can use with a single API Key.
Enable SQL Server Authentication in SQL-server
Tags: sql, authentication, sqlserver
Published: 2021-09-03 16:53:01

Step by step process for enable SQL server authentication.


SQL-server is a very popular RDBMS. After installation the authentication mode is by default set to Windows Authentication. But in real scenario its not recommended for security purpose. SQL-server also give us the option for SQL-authentication. So today I will show how to configure SQL- authentication in SQL-Server.

**Step by step process**

step 1. First login to sql server using windows authentication.

![1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vv2ih57ugrkofgw4vq2g.PNG)


step 2. Now we need to go to the properties of sql server instance.

![2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bnud32wzwlgqajb1udeg.png)
 

step 3. After that go to security tab and check SQL server and windows authentication mode and click OK.

![3](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qeobzd9n0gxplpyzfud0.PNG)
 

step 4.Now we need to create a user who will access our database as a SQL authentication. For that go to security -> login -> new login options.
 
![4](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yorlic2nywm75lcym23x.png)


step 5. Now give a user name and set up the password for that user.
![5](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vl4ltvjstd7r9595f16v.PNG)
 

step 6. Now give the user role as per requirements. For example I give all the permission for this testuser.
![6](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g15moijd21pb15gjhw0e.PNG)
 

step 7. Also set up the status tab just like this. Permission will be grant and login will be Enabled. 

![7](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/us65q5cv67pmmnladqva.PNG)

So all the necessary setting is done for our new user. Click on the OK button.

Now restart the SQL server and try to login using SQL server authentication mode. Give the user login and password. You will login this time.
 
**#Points of Interest**

Sometimes SQL-server can not login and shows some error like this user can not login. For this case you can restart the sqlexpress from the services. After that try to login again. This will solve the error.
![8](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zvxoyk8evzcwgznedmv5.png)

So after login you will see that the new SQL user is logged in.
![10](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0p0kydl71my7ihpd57ue.PNG)

That's it. Now you can login in to SQL server using SQL authentication as well as windows authentication .
PM2, node, NextJS, Express
Tags: nextjs, node, pm2, express
Published: 2021-09-03 19:02:48

A quick collection of building and monitoring commands in Linux.

To get ExpressJS started under pm2:

```
/home/ec2-user/expressjs/bin

pm2 start --name expressjs www
```


PM2
List the processes:

```
pm2 list
```
NPM build, start process
```
npm ci
npm test --if-present
npm run build
npm run start
pm2 start npm -- start
pm2 start --name AppName npm -- start
```

Restart the processes:
```
pm2 restart all
pm2 restart <app name>
```
10x django developer 
Tags: discuss, webdev, productivity, tooling
Published: 2021-09-03 18:57:57

{% youtube YGjNFdccr0Q %}


if you are wondering what this is using here is the package and don't forget to support it by dropping a star :star:

github repo: [dr_scaffold](https://github.com/Abdenasser/dr_scaffold)

tutorial: [make a full api in seconds](https://dev.to/abdenasser/scaffold-django-apis-like-a-champion-1595)
The Area or Volume of Sphere
Tags: python, computerscience, functional
Published: 2021-09-03 18:51:23

```python
# area_volume_sphere.py
#   This module has two functions in it. The first function calculates the area of a
#   sphere. The second function calculates the volume of a sphere.
# by: Scott Gordon

import math

# Create a function to calculate the area of a sphere.


def sphere_area(radius):
    area = 4 * math.pi * radius**2
    return area


# Create a function to calculate the volume of a sphere.
def sphere_volume(radius):
    volume = (4/3) * math.pi * radius**3
    return volume


# Run both functions to demonstrate their output.
def main():
    print(f"The area of the sphere is {sphere_area(2)}")
    print(f"The volume of the sphere is {sphere_volume(3)}")


main()
```

Photo by <a href="https://unsplash.com/@fakurian?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Fakurian Design</a> on <a href="https://unsplash.com/s/photos/sphere?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
Kotlin for Android Development
Tags: kotlin, android, sharingknowledge, 50daysofcode
Published: 2021-09-03 18:31:02


What should we use for Android Development ,Java or Kotlin ?
➡️ If you are beginner I suggest start Android Development using Java .
Cause Java is used not only in Android application but also for other application too.

And once you learn Java, Kotlin is easier to learn .

But why we should switch from Java to Kotlin after learning Java so well and getting comfortable with it?

The Answer is 👇
1. Less code combined with greater readability :
 ➡️ Spend less time writing your code and working to understand the code of others

Interoperability with Java :
➡️ You can use Kotlin along with the Java programming language in your applications without needing to migrate all your code to Kotlin.

Code safety :
➡️ Less code and better readability lead to fewer errors. The Kotlin compiler detects these remaining errors, making the code safe.

Easy learning :
➡️ Kotlin is very easy to learn, especially for Java developers.

Libraries :
➡️ Just like Python Programming language we have multiple libraries in Kotlin to use for our Android Development.