teleren/devto huggingface dataset:
A smart way to close files
Tags: emacs
Published: 2022-06-30 17:54:47

Originally posted in [my blog](https://in.comum.org/smart-way-to-close-files.html)

Have you tried to close a file and your editor asks you if you are sure you want to proceed because there are unsaved changes? But all that it gives you is Yes, No or Cancel options? I believe computers should help us in our daily tasks, and we should delegate as much as possible, so that the machine could help us free our minds to think, chill, dream and do what they can't do. That's why I ask myself why my text editor doesn't help me to understand what the differences are before I close the file. So, that I'll be able to make better decisions with data and don't need to remember if/and what I had changed on the document.

Fortunately, I use Emacs and after a little search I discovered that, it is easy to do, thanks to the answers in [stack exchange](https://emacs.stackexchange.com/questions/3245/kill-buffer-prompt-with-option-to-diff-the-changes/3363#3363)
```emacs-lisp
(defun my-kill-this-buffer ()
  (interactive)
  (catch 'quit
    (save-window-excursion
      (let (done)
        (when (and buffer-file-name (buffer-modified-p))
          (while (not done)
            (let ((response (read-char-choice
                             (format "Save file %s? (y, n, d, q) " (buffer-file-name))
                             '(?y ?n ?d ?q))))
              (setq done (cond
                          ((eq response ?q) (throw 'quit nil))
                          ((eq response ?y) (save-buffer) t)
                          ((eq response ?n) (set-buffer-modified-p nil) t)
                          ((eq response ?d) (diff-buffer-with-file) nil))))))
        (kill-buffer (current-buffer))))))
```
This code snippet does the trick! Now, every time I try to close an unsaved file, Emacs will help me, by asking if I want to see the diff, not only Yes, No or Cancel \o/

I have used Emacs since 2011, but recently, I started to understand and feel the power of Emacs. When I heard people saying Emacs is not only a text editor, I was always confused. I know we can read emails, use Slack, play games and a plenty of other things. But, only after reading this [article](https://batsov.com/articles/2022/06/01/who-needs-modern-emacs/), I understand and agree that “Emacs isn’t an editor, it’s a building material for you to create the best editor for yourselves.” Now, the snippet above makes a lot of sense.

Let's understand what is happening there:

The snippet creates a function that checks if the buffer you are currently in, was modified since its file was last read or saved and prompts you four options: quit, save, set as not modified, show the difference between current and previous state. After you choose the option, it will kill the current buffer.

On your Emacs config you can remap your keystroke to kill buffers to call `my-kill-this-buffer` and that's the way you can change how Emacs works and create your dream editor.

That's all folks, see you next post.
the thin strip of freedom
Tags: devjournal, beginners
Published: 2022-06-30 17:41:28

NOWADAYS, the better part of the new devs coming in every year are joining because IT grants a feel of freedom and happiness. At least compared to other promising careers, this is true. But to what degree?

People tend to believe that the amount of freedom we (DEVs) have is retirement level freedom (not that retirement is freedom), but this isn't true.

The amount of freedom a DEV actually has, depends on how good of a DEV the DEV wants to be. the more you want, the higher you want to achieve, the bigger you want to get, the less freedom you will have.
From WordPress to Gastby
Tags: gatsby, wordpress, webdev
Published: 2022-06-30 17:37:26

In the past I had to take over the management of the family hotel website, a site created with **WordPress** in the distant past (not from me) and never properly maintained.

In order to not reinvent the wheel, I chose to keep the existing technology stack, renewing it in terms of: UI, functionality and performance.
The results were poor, with a site soon becoming unmanageable and with an ever-growing fear of making significant changes.

The pinnacle was reached when we had to use a plugin to manage the restaurant menu in order to "simplify" the input from the end user. The plugin, inevitably, was very limited and could only expose a couple of UIs (not properly done).

---

After accumulating some experience with **GatsbyJS** (this is the second time I go into production with it) I decided to do a graphic makeover, a simplification of the UX and a better manageability of the contents.

📜 The menu is now generated from a simple JSON that dynamically creates the web page based on the contents. Changing the content has become too easy and the UI has been created ad-hoc (clean and readable), respecting the wishes of the owner.

⭐ Review ratings on major online portals are now displayed from a JSON file. Before, I had to create images by hand with the reported vote, at each change of vote. Now this process can be automated.
Bonus: the review collection is a component, reusable in the whole website avoiding copy-past errors.

📝 The writing of the articles has been converted to simple **markdown** files which then allow you to generate web pages according to a predefined template. The latter is essential because it allows you to have consistent and error-free pages. Again, it prevents to have strange copy-past errors of WordPress pages.

⚡ The performances, needless to say, shot up. This is because a static site builder offers many features: progressive image loading, page loading speed, and general optimizations.
Here you can find [my article](https://dev.to/lomby92/progressive-image-loading-with-gatsby-2ldi) about progressive image loading.

💻 Let's not forget that as a developer the goal is always to optimize time and having created the site with Gatsby made it possible for me to have excellent security and speed in releases and updates, because I can try the site on my PC before make a release (automated of course). This thing on WordPress was unthinkable, I would have had to provide myself with a staging site, make the changes and then replicate them on production.

---

For the more curious, this is the site: https://www.hotelmodernoassisi.com/
Breast Cancer ML - Sage Maker Canvas
Tags: breastcancer, machinelearning, sagemaker, aws
Published: 2022-06-30 17:23:31

We can approach a Machine Learning model in many ways. A tool that greatly simplifies our task is SageMaker Canvas from AWS. Here we can see a small model that I have built for Breast Cancer and that, in a few steps, exceeds 96% accuracy.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nbweg1clq3obeaz13kp9.jpeg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vd8o6lzecf0q12ko0tsj.jpeg)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hd0qva7pcfavp669w4qx.jpeg)
Build a custom time picker React component
Tags: react, timepicker
Published: 2022-06-30 17:29:31

---
title: Build a custom time picker React component
published: true
date: 2022-06-30 17:17:01 UTC
tags: React, Timepicker
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mub075pnbdh4x7vtiijp.png
canonical_url: https://anlisha.com.np/blog/build-a-custom-time-picker-react-component/
---

In this article, we’ll create a custom time picker component combining react-datetime and react-input-mask packages.

### **Step1 — Start Basic CRA**

```
npx create-react-app axon
```

### **Step2 — Install react-datetime and react-input-mask packages**

```
cd axon
npm i react-datetime react-input-mask moment
```

### **Step3 — Setup time picker component**

{% embed https://gist.github.com/anlisha-maharjan/4371c5604a0795e7f62bd87d2dd3ba63 %}

### **Step4 — Style time picker component**

{% embed https://gist.github.com/anlisha-maharjan/3ab43016b6b7995a30addbd26f4098be %}

### **Step5 — Import CustomTimePicker component in App.js**

```
import React from "react";
import CustomTimePicker from "./custom-time-picker";
import './custom-time-picker.scss';
function App() {
  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        width: "100vw",
        height: "100vh",
      }}
    >
      <CustomTimePicker name="time" label="Time" />
    </div>
  );
}
export default App;
```

**And that’s it!**

The post [Build a custom time picker React component](https://anlisha.com.np/blog/build-a-custom-time-picker-react-component/) first appeared on [Anlisha Maharjan](https://anlisha.com.np/blog).
Enrol student in a course programmatically.
Tags: moodle, php, beginners
Published: 2022-06-30 17:06:59

Hello there,

I am back with an easiest way to enrol a student in a course programmatically. Just five line of code to get it done.
Try the below code:

_Step-1: Must include the below code at the top of your file._
```
require_once($CFG->dirroot . '/lib/enrollib.php');
```
_Step-2: Put the `enrol_user` function in your PHP script._

```
function enrol_user($courseid, $userid){
    global $DB;
    // Enrol the user in the course.
    $studentrole = $DB->get_record('role', array('shortname' => 'student'));
    $maninstance1 = $DB->get_record('enrol', array('courseid' => $courseid, 'enrol' => 'manual'), '*', MUST_EXIST);
    $manual = enrol_get_plugin('manual');
    $manual->enrol_user($maninstance1, $userid, $studentrole->id);
}
```
_Step-3: Call the enrol_user function._
```
enrol_user($courseid, $userid)
```

Happy learning!
Arphire Network
Tags: web3, emercoin, cryptocurrency
Published: 2022-06-30 16:49:15

Recently started working on a web3.0 project, which is a service platform for users, where they can create their own services and use ready-made ones. And all this on blockchain with as few fees as possible.
Details can be found on the project's Telegram channel: https://t.me/arphire
Tempo para o 1º Engajamento nos Pull Requests
Tags: codereview, git, segurancapsicologica, github
Published: 2022-06-30 16:45:32

---
title: Tempo para o 1º Engajamento nos Pull Requests
published: true
description: Geralmente utilizamos para medir quanto tempo se passou para a primeira interação com o Pull Request acontecer.
tags: codereview, git, segurancapsicologica, github
canonical_url: https://wevtimoteo.medium.com/tempo-para-o-1%C2%BA-engajamento-nos-pull-requests-cf365671af48
# Use a ratio of 100:42 for best results.
---

Essa é uma métrica valiosíssima para times grandes. Geralmente utilizamos para medir quanto tempo se passou para a primeira interação com o Pull Request acontecer.

Você pode medir isso tanto para Pull Requests que estão em aberto, para servir de termômetro, ou para os que já foram fechados/mergeados, para ter uma ideia como o time tem trabalhado.

## Sabe aquele Pull Request que você solicita revisão e fica horas sem ninguém comentar ou revisar?

O contrário também é um problema: em menos de 1 minuto você já recebe uma aprovação sem comentário algum.

Para times com esse problema do tempo longo de revisão recomendo os revisores utilizarem pequenas janelas de tempo da rotina de trabalho para revisar: pausa para o café, intervalos entre tarefas/User Stories, antes e depois do almoço e/ou antes/depois de reuniões.

Para times que revisam o Pull Request muito rápido é interessante pensar na causa: as pessoas estão apressadas porque existe uma pressão para entregar algo? Ou simplesmente não veem valor na revisão de código?

## O ambiente é seguro?

Algumas vezes, a causa da falta ou demora de engajamento é porque as pessoas não se sentem à vontade para revisar um Pull Request de uma pessoa com mais experiência. Fique atento para essas situações, caso aconteça tente criar um ambiente com maior Segurança Psicológica.

Um ambiente seguro para errar é o melhor dos ambientes para promover uma cultura de aprendizado e colaboração. Trabalhando para isso, com certeza vai refletir na prática de revisão de código.
What is the Internet? How is Data Transmitted Across Networks?
Tags: webdev, beginners, internet, discuss
Published: 2022-06-30 16:37:19

The web is one of the many applications to access the internet, and web browsers are just a computer program that enables you to view and download webpages. What happens when you click enter on the address bar?

## What is the Internet?
The internet is a decentralised network of networks (of computers). Each connected computer have an unique address called IP (Internet Protocol) address. The internet is composed of three parts:
1. **The last mile**, provided to homes and businesses through TV companies, fibre optics, telephone cables, towers (wireless).
2. **Data centres**, rooms of servers that store data and host content.
3. **The backbone**, networks that carry data between data centres and consumers.

Data Centres <--> Backbone <--> Last Mile (Consumers)

You can use the built-in _ping program_ to see if your computer is alive on the internet. Open the terminal and type the following command:
```bash
ping www.google.com
```
The ping program maps the domain name to the computer's IP address, sends a ICMP (Internet Control Message Protocol) request and comes back with a reply.

## Transmission of Data
The human readable data needs to be resolved into electronic signals for machines before it reaches the backbone, protocol stack in the operating system takes care of this job.

Message on the sender machine goes through 4 protocol layers in a broad sense:
1. **Application Protocol Layer**, where user interacts and specific for each application e.g. HTTP
2. **Transmission Control Protocol (TCP) Layer**, directs packets of data to the correct application (i.e. listening port) once it arrives on the target computer
3. **Internet Protocol Layer**, packets directed to computer associated with the IP address
4. **Hardware layer**, converts between binary data and network signals

TCP/IP standard is the foundation of modern internet, which is why the protocol stack is also known as TCP/IP stack.

The packets then will make their journey through several routers and backbones until they find the target destination. Each router knows its sub-networks and holds an IP address table for that region, it acts as a packet switch to direct packets in the routing hierarchy. Use the _trace route program_ to see the path taken in action:
```bash
traceroute www.google.com
```

On the receiver side, the packets of data goes through the layers in reverse order to reconstruct the original message. 

## Well Known Port Numbers

| Protocol    | Port   |
| ----------- | -------|
| FTP         | 20/21  |
| Telnet      | 23     |
| SMTP        | 25     |
| HTTP        | 80     |

## References
[The Internet Explained](https://www.vox.com/2014/6/16/18076282/the-internet)
[How Does the Internet Work?](https://web.stanford.edu/class/msande91si/www-spr04/readings/week1/InternetWhitepaper.htm)
Quiz: SQL query
Tags: quiz, sql
Published: 2022-06-30 16:30:49

Hello, coders! :computer:

Today's quiz taken from a real world task is SQL related.

## Database structure
There are two tables (very simplified for the sake of this quiz):
1. `companies` with two columns: `id` and `name`
2. `users` with two columns: `company_id` and `is_pro` (boolean)

## Task
> write a query to find all companies that only have pro users (`is_pro=1`).

## My take on this

{% details Click to see my solution using MySQL %}

```sql
SELECT
    c.name as company
FROM
    users u
JOIN companies c ON
    c.id = u.company_id
GROUP BY
    c.id
HAVING
    SUM(IF(is_pro, 0, 1)) = 0;
```

`IF(is_pro, 0, 1)` means that I give 0 points to users that are pros (counter-intuitive but bear with me!). If all users are pros then the sum of points should be 0, right? That's what `HAVING IF(is_pro, 0, 1)) = 0` does.

There you have it!

How would you have done it?

:pencil: Edit 
As pointed out by @geraldew using `SUM` to `COUNT` is hacky and as such I'd better use `COUNT` and `CASE`:
```sql
SELECT
    c.name as company,
    COUNT(
        CASE WHEN can_use_app = 1 THEN 'x'
    END
    ) isPro,
    COUNT(
        CASE WHEN can_use_app = 0 OR can_use_app IS NULL THEN 'x'
    END
    ) isNotPro
FROM
    users u
JOIN companies c ON
    c.id = u.company_id
GROUP BY
    c.id
HAVING
    isPro > 0 and isNotPro = 0;
```

{% enddetails %}

Happy coding! :keyboard:
CuteUpload - Encrypted PHP file uploade
Tags: php, mysql, programming, github
Published: 2022-06-30 16:21:21



Cute upload is file uploader written in PHP (version used is PHP 8), also uses MySQL database.
Files uploaded with Cute upload will be **ENCRYPTED** with AES-256.
I will say that this is just a beta, a lot of functionality will be added after.

**HOW TO USE IT**

 1. You need to setup your PHP server and MySQL database
 2. Import **cuteupload.sql** to your database.
 3. You need to edit **engine/database.php** according to your settings.
 4. Opontional - you can change encryption key and iv in **engine/enc.php**

**HOW DOES IT WORK**

 1. You upload your file - you can add password and description.
 2. After file is uploaded without any errors you will get information about uploaded file, like md5 hash of file sha1 of file, file name and **most importantly you will get CUTE CODE - code that will be used to download file you uploaded**. It will be 21 character alphanumeric string.
 ![generating code for download](https://i.ibb.co/Pz3ZtL8/ss1.png)
 3. This file for example "Capture.PNG" is now **encrypted with AES-256**. File name is **hashed**, and file is now stored in random generated folder name. All information is logged in database.
 4. Now go back to the main page. And type CUTE CODE.
 ![downloading file](https://i.ibb.co/fG1pqSq/ss2.png)
 5. If file with this code exists you will see a page that looks like this.
 ![enter image description here](https://i.ibb.co/rvPycCW/ss3.png)
 6. After you click button for download, file will be **decrypted**, file name will be **de-hashed** - than **downloaded**.
 7. For security reasons whenever someone downloads file folder where file is located will be renamed and file will be **encrypted** again.

 **SECURITY**
 
 12. [x] SQL Injection protected, XSS also.
 13. [x] CSRF token is implemented.
 14. [x] Files are encrypted and hashed, untraceable.

**WILL BE ADDED/CHANGED IN FUTURE**

 1. Option to log in and register
 2. API
 3. About page
 4. Option to report file (for malware, abuse etc...)
 5. QR code for downloading files
 6. Option to remove files after some time (7 days, 1 day, month)
 7. To download file as zip.
 8. Change a code, so it isn't so messy.
 9. Bug fixes.

GITHUB LINK : [CHECK OUT HERE](https://github.com/jolovicsharp/cuteupload)
How do you solve this problem using javascript
Published: 2022-06-30 16:04:15

While a user is downloading a file which is X bytes in size, your job is to provide a function to estimate the time remaining in minutes. The system has a record of the amount (in bytes) B downloaded each minute.

If the file is not completely downloaded, estimate the rate by taking the simple average of the last Z observations.

Write a function:

function solution(X, B, Z);

that returns the amount of time remaining in minutes. X is an integer representing the file size. B is an array of integers listing the bytes downloaded at each minute starting from the beginning of the download until now. Return an integer representing the number of minutes remaining. Z is an integer. You may assume that all the values are reasonable.

Example:

X=100, B=[10,6,6,8], Z=2 30 bytes = 10+6+6+8 have been downloaded. So 70 bytes remain. The average of the last two minutes (Z=2) is 7=(6+8)/2. So the function should return 10 minutes (=70/7).
Note that:

If there are fewer than Z observations, use what you do have.
Your estimate should be rounded up to the nearest integer (ceiling).
If the download is done, return 0
If you are unable to produce an estimate, return -1.
How do you write a javascript function for this problem
Published: 2022-06-30 16:02:15

From an integer X representing a time duration in seconds produce a simplified string representation.

For example, given:
100
You should output:
"1m40s"

Use the following abbreviations w,d,h,m,s to represent:
* 1w is 1 week
* 1d is 1 day
* 1h is 1 hour
* 1m is 1 minute
* 1s is 1 second

Only the two largest non-zero units should be used. Round up the second unit if necessary so that the output only has two units even though this might mean the output is for slightly more time than X seconds.

Write a function:

function solution(X);

that, given an integer X, returns a string representing the duration.

Examples:
1. Given X=100, return "1m40s"
2. Given X=7263, return "2h2m". (7263s=2h1m3s, but this uses too many units, so we round the second largest unit up to 2h2m)
3. Given X=5, return "5s"
Hello Flutter Developers👋
Tags: flutter, dart, programming, showdev
Published: 2022-06-30 16:00:45

🛡️ Did you know you can customize the Flutter red-screen of death?😈

We understand that facing the red screen of death can be terrifying and eye-boggling, so here’s a

## **Tip😃:**
To customize the red screen of death, you can call the ‘ErrorWidget.builder( )’ widget in you void main( ) { } method and customize your red screen.

```
import 'package:flutter/material.dart';

import 'home.dart';

void main() {
  ErrorWidget.builder = (FlutterErrorDetails details) => Material(
        child: Container(
            padding: const EdgeInsets.symmetric(vertical: 30, horizontal: 20),
            child: Center(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                  Image.asset("assets/error.png"),
                  const SizedBox(height: 20),
                  const Text(
                    'Error',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        color: Colors.red,
                        fontSize: 20,
                        fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 20),
                  Text(details.exceptionAsString(),
                      textAlign: TextAlign.center,
                      style: const TextStyle(
                          color: Colors.red,
                          fontSize: 18,
                          fontWeight: FontWeight.normal))
                ]))),
      );
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'E-Learning App',
      theme: ThemeData(
        scaffoldBackgroundColor: Colors.grey[900],
        primarySwatch: Colors.blue,
        fontFamily: 'Urbanist',
      ),
      home: const HomeScreen(),
    );
  }
}

```

Give it a try and let me know how it went!

## **Support Me:**
[Instagram](https://www.instagram.com/_flutter.queen/)
[Facebook](https://www.facebook.com/profile.php?id=100082330156711)
[Github](https://github.com/Flutter-Queen)
[Medium](https://medium.com/@flutterqueen)