teleren/devto huggingface dataset:
Advent of Code 2021 Python Solution: Day 7
Tags: adventofcode, python, algorithms
Published: 2021-12-07 05:48:06

I found today's solution to be easier than previous day's.

## Part 1
```python
data,data1 = get_data(day=7)

data = [int(d) for d in data[0].split(",")]
data1 = [int(d) for d in data1[0].split(",")]

l = len(data1)
f = []

for v in range(l):
    f.append((sum([abs(d-v) for d in data1])))
print(min(f))        
```

### One Liner Solution
```python
min([sum([abs(d-v) for d in data1]) for v in range(len(data1))])
```

## Part 2
```python
l = len(data1)
f = []

for v in range(l):
    diff = [abs(d-v) for d in data1]
    diffs = sum([sum(list(range(dif+1))) for dif in diff])
    f.append(diffs)
print(min(f))        
```

### One Liner Solution
```python
min([sum([sum(list(range(abs(d-v)+1))) for d in data1]) for v in range(len(data1))])
```
## Why not read more?
* [Gesture Based Visually Writing System Using OpenCV and Python](https://q-viper.github.io/2020/08/01/gesture-based-visually-writing-system-using-opencv-and-python/)
* [Gesture Based Visually Writing System: Adding Visual User Interface](https://q-viper.github.io/2020/08/11/gesture-based-visually-writing-system-make-a-visual-user-interface/)
* [Gesture Based Visually Writing System: Adding Virtual Animationn, New Mode and New VUI](https://q-viper.github.io/2020/08/14/gesture-based-visually-writing-system-adding-virtual-animation-new-mode-and-new-vui/)
* [Gesture Based Visually Writing System: Add Slider, More Colors and Optimized OOP code](https://q-viper.github.io/2020/08/21/gesture-based-visually-writing-system-add-slider-more-colors-and-optimized-code/)
* [Gesture Based Visually Writing System: A Web App](https://q-viper.github.io/2020/08/29/gesture-based-visually-writing-system-web-app/)
* [Contour Based Game: Break The Bricks](https://q-viper.github.io/2020/08/16/contour-based-game-break-the-bricks/)
* [Linear Regression from Scratch](https://q-viper.github.io/2020/08/07/writing-a-linear-regression-class-from-scratch-using-python/)
* [Writing Popular ML Optimizers from Scratch](https://q-viper.github.io/2020/06/05/writing-popular-machine-learning-optimizers-from-scratch-on-python/)
* [Feed Forward Neural Network from Scratch](https://q-viper.github.io/2020/05/30/writing-a-deep-neural-network-from-scratch-on-python/)
* [Convolutional Neural Networks from Scratch](https://q-viper.github.io/2020/06/05/convolutional-neural-networks-from-scratch-on-python/)
* [Writing a Simple Image Processing Class from Scratch](https://q-viper.github.io/2020/05/30/image-processing-class-from-scratch-on-python/)
* [Deploying a RASA Chatbot on Android using Unity3d](https://q-viper.github.io/2020/08/04/deploying-a-simple-rasa-chatbot-on-unity3d-project-to-make-a-chatbot-for-android-devices/)
* [Naive Bayes for text classifications: Scratch to Framework](https://q-viper.github.io/2020/03/04/text-classification-using-naive-bayes-scratch-to-the-framework/)
* [Simple OCR for Devanagari Handwritten Text](https://q-viper.github.io/2020/02/25/building-ocr-for-devanagari-handwritten-character/)
Leetcode 163. Missing Ranges (javascript solution)

Tags: javascript, algorithms
Published: 2021-12-07 05:33:50

###Description:
You are given an inclusive range [lower, upper] and a sorted unique integer array nums, where all elements are in the inclusive range.

A number x is considered missing if x is in the range [lower, upper] and x is not in nums.

Return the smallest sorted list of ranges that cover every missing number exactly. That is, no element of nums is in any of the ranges, and each missing number is in one of the ranges.

Each range [a,b] in the list should be output as:

"a->b" if a != b
"a" if a == b

###Solution:
Time Complexity : O(n)
Space Complexity: O(1)

```javascript
var findMissingRanges = function(nums, lower, upper) {
    // array to add ranges
    const result = []
    // start at lower - 1 for edge case where lower === nums[0]
    let prev = lower - 1;
    // loop for nums.length times so we can compare the last value with upper
    for (let i = 0; i <= nums.length; i++) {
        // current number to compare to prev
        // when i === nums.length we will compare prev = nums[nums.length-1] and upper
        // the upper+1 is to account for nums[nums.length-1]===upper
        let curr = (i < nums.length) ? nums[i] : upper + 1;
        // check if we need to add a range to the array
        if (prev + 1 <= curr - 1) {
            // if equal then add any of the numbers to the array
            // if < than, then add the range string to the array
            result.push(prev + 1===curr - 1?`${prev + 1}`:`${prev + 1}->${curr - 1}`);
        }
        // set prev to compare in the next iteration
        prev = curr;
    }
    return result 
};
```
API newsapi.org | Express | for beginner
Tags: api, express, node
Published: 2021-12-07 05:32:48

### package.json

```javascript
{
...
  "dependencies": {
    "express": "^4.17.1",
    "newsapi": "^2.4.1"
  }
}
```
---

### index.js

```javascript
/* require newsapi */
const NewsAPI = require('newsapi');
const newsapi = new NewsAPI('YOUR-API-KEY');


/* require express */
const express   = require('express')
const app       = express()

app.get( "/", function( req, res ) {

    // To query sources
    // All options are optional
    newsapi.v2.sources().then( response => {

        console.log( response.sources )

    })

} )

app.listen(4000)
```
---

### References

[npmjs.com/package/newsapi](https://www.npmjs.com/package/newsapi)
[npmjs.com/package/express](https://www.npmjs.com/package/express)

[newsapi.org](https://newsapi.org/)
3 Ways Conditionally Render CSS in ReactJS
Tags: react, css, javascript, webdev
Published: 2021-12-07 05:19:37

Create new react app
```bash
npx create-react-app my-app
cd my-app
npm start
```

## Method 1: 
### Syntax
```bash
{[ your_class_name]: conditon}
```
### Example
In this method, we are going to use CSS modules. In order to merge two classes we use `clsx` library. 

#### Install clsx
```bash
npm install clsx
```

Now once you installed let dive into ``App.js``
```react
import styles from "./styles.module.css";
import clsx from "clsx";

export default function App() {
  let title = true;
  return (
    <div className="App">
      <h1 class={clsx(styles.baseText, { [styles.heading]: title })}>
        Sample Heading
      </h1>
      <h1 class={styles.description}>Here goes description</h1>
    </div>
  );
}

```

``styles.module.css``
```css
.baseText {
  font-size: 20px;
  color: yellow;
}

.heading {
  font-size: 28px;
  color: red;
}

.description {
  font-size: 18px;
  color: aqua;
}

```

### Link
 
## Method 2:
### Syntax
```bash
conditon && yourstyle
```

``App.js``
```react
import styles from "./styles.module.css";
import clsx from "clsx";

export default function App() {
  let title = true;
  return (
    <div className="App">
      <h1 class={clsx(styles.baseText, title && styles.heading)}>
        Sample Heading
      </h1>
      <h1 class={styles.description}>Here goes description</h1>
    </div>
  );
}
```

``styles.module.css``

```css
.baseText {
  font-size: 20px;
  color: yellow;
}

.heading {
  font-size: 28px;
  color: red;
}

.description {
  font-size: 18px;
  color: aqua;
}

```
## Method 3: 
### Syntax
```bash
{`${condition}` ? "classname_1" : "classname_2"}
```
### Example

``App.js``
```react
import "./styles.css";

export default function App() {
  let title = true;
  return (
    <div className="App">
      <h1 class={`${title}` ? "heading" : "baseText"}>Sample Heading</h1>
      <h1 class="description">Here goes description</h1>
    </div>
  );
}
```
``styles.css``
```css
.baseText {
  font-size: 20px;
  color: yellow;
}

.heading {
  font-size: 28px;
  color: red;
}

.description {
  font-size: 18px;
  color: aqua;
}

```
### Result 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cnfckr5j1uklt9o6f6r9.png)

[Source code](https://codesandbox.io/s/amazing-kalam-m9tsi?file=/src/App1.js) for this tutorial
Deleting records from a Supabase database
Tags: nextjs, react, database
Published: 2021-12-07 05:04:53

I'm sure you saw this article coming after we just learned [how to insert records in a Supabase database](https://daily-dev-tips.com/posts/adding-new-records-to-a-supabase-database/).

Let's say we accidentally added the wrong country that we want to remove...

How do we go about that?

## Rendering a delete button

The first thing we want to add is a delete button so we have something to click on.

We'll use a button with the raw `svg` from a [Fontawesome icon](https://fontawesome.com/v6.0/icons/trash-can?s=solid).

```jsx
<button onClick={() => deleteCountry(country.id)}>
  <svg
    xmlns='http://www.w3.org/2000/svg'
    aria-hidden='true'
    focusable='false'
    role='img'
    viewBox='0 0 448 512'
    width='0.75rem'
  >
    <path
      fill='currentColor'
      d='M32 464C32 490.5 53.5 512 80 512h288c26.5 0 48-21.5 48-48V128H32V464zM304 208C304 199.1 311.1 192 320 192s16 7.125 16 16v224c0 8.875-7.125 16-16 16s-16-7.125-16-16V208zM208 208C208 199.1 215.1 192 224 192s16 7.125 16 16v224c0 8.875-7.125 16-16 16s-16-7.125-16-16V208zM112 208C112 199.1 119.1 192 128 192s16 7.125 16 16v224C144 440.9 136.9 448 128 448s-16-7.125-16-16V208zM432 32H320l-11.58-23.16c-2.709-5.42-8.25-8.844-14.31-8.844H153.9c-6.061 0-11.6 3.424-14.31 8.844L128 32H16c-8.836 0-16 7.162-16 16V80c0 8.836 7.164 16 16 16h416c8.838 0 16-7.164 16-16V48C448 39.16 440.8 32 432 32z'
    />
  </svg>
</button>
```

You might have spotted the `deleteCountry` function above. We pass the country id to this function.

So let's go ahead and create the function.

## Deleting records from Supabase

This delete country function is super easy, as we can leverage our Supabase setup and simply execute a delete query.

```js
const deleteCountry = async (countryId) => {
	try {
	  await supabase.from('countries').delete().eq('id', countryId);
	  setCountries(countries.filter((country) => country.id != countryId));
	} catch (error) {
	  console.log('error', error);
	}
};
```

Here you can see the delete query is as simple as calling the `delete()` method on a row that equals this id.

Then we filter the country from the existing list of countries we are showing to the user.

And all this will result in the following action:

![Deleting records from a Supabase database](https://cdn.hashnode.com/res/hashnode/image/upload/v1637937459640/vjWsKHtGN.gif)

I hope you enjoyed this article. I've uploaded everything to [GitHub](https://github.com/rebelchris/next-supabase/tree/supabase-delete-row) if you wish to look at your own pace.

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
New app release called "AppDEV PPT-Creator"
Tags: python, programming
Published: 2021-12-07 04:51:07

Hey There Devs,
It's me Dave again, we have again created a new app called "AppDEV PPT-Creator" it can create ppts but not as you expect since it is still under development.
Live Link: https://app.codingrooms.com/w/QfGmy2bAiuK7
Don't forget to click the run button and it's Console based

Contact: davidjeremiah050708@gmail.com
Discord: DJ050708#7940
Github: david050708

Thank You
New Website Launch
Tags: html, webdev
Published: 2021-12-07 04:23:44

Hey there Devs,
It's me Dave again, we have launched our new website so that  you can download our apps [here](https://david050708.github.io/appdevdownload.github.io/)

We have released a new app called NoteWritePad, it's free easy to use and user-friendly.

About:
I am a 14 year old boy from Tamil Nadu, India. First I thought programming was "ugly", but after I saw my friend creating apps, I was fascinated by the beauty of programming and from then on I started my journey as developer

Contact = davidjeremiah050708@gmail.com
Discord = DJ050708#7940
Github = david050708

Thank You
Working with Form Validation in Blazor Rich Text Editor Component
Tags: webdev, blazor, dotnet, csharp
Published: 2021-12-07 04:14:15

Learn how to work with Form validation in the Syncfusion [Blazor Rich Text Editor (RTE)](https://www.syncfusion.com/blazor-components/blazor-wysiwyg-rich-text-editor) in a Blazor WebAssembly app. This video explains how to set the validation rules, customize the validation messages, and set the maximum number of characters allowed in the RTE. 

Example project: https://github.com/SyncfusionExamples... 

Explore tutorial videos: https://bit.ly/3fAz0Ch
{% youtube diCS3f8Anys %}
Fiverr is the upcoming king of freelancing platform, But Why?
Tags: freelancing, webdev, programming, fiverr
Published: 2021-12-07 03:32:40

There aren't many bigger freelance websites than Fiverr. It's been around since 2010 and claims to be used by more than three million employers, including big companies like Netflix and Facebook.

> If you're struggling with not getting **clicks**, **impressions** and **ORDERS** in Fiverr, you must [ask some Fiverr experts](https://webmatrices.com/t/fiverr) to check it once. So, here are the experts who will help you to make your GIG rank on the top.

Fiverr's sheer size means that employers can find every kind of freelancer on the site, and if you're a freelancer you'll be able to find opportunities no matter what kind of work you do. Whether you're after a long project, a small job, or anything in between, you'll be able to find it here, and at all sorts of budgets. Free listings also mean there are plenty of low-cost opportunities here too.

It's free to join the site and free to list opportunities on Fiverr, and everyone can benefit from protected payments and 24/7 support. Businesses can also pay to enjoy an upgraded package that offers verified freelancers, hand-picked talent matching, and a dashboard to manage your projects.

Fiverr has plenty going for it, not least its size, but its low barrier to entry means that you may have to sift through many unsuitable projects or freelancers before you find the right fit. Free listings also mean that Fiverr's eventual transaction fees are a little higher than many other sites.

### Why Fiverr is the king of freelancing platform?
Fiverr is a platform that connects freelancers with business owners looking for services in various digital projects, including website design, content writing, and voice-overs. 

This freelance website provides a streamlined method for both freelancers and business owners to interact with one another. Note that on the website, freelancers are called sellers, their services – gigs, and business owners – buyers. 

Instead of sending out bids, sellers can sign up for free, list their gigs, and set their prices. Meanwhile, buyers can simply browse through different categories to purchase. 

Whenever a buyer purchases a gig, the system automatically charges their account and puts the money on hold. The system will then take a commission fee and send freelancers 80% of the offered price.

Depending on each freelancer’s seller level, it can take up to 14 days to withdraw their earnings. There are multiple options to withdraw the payments, such as debit card, PayPal, and wire transfer.
CyberSecurity in times of coronavirus
Tags: cybersecurity, python, javascript, java
Published: 2021-12-07 03:24:26

It´s no secret to anyone that the covid modified our reality to the point that people who were previously "threatened" by technology today use it as a way of life, a clear example of this are doctors and health personnel in general, people whose technological interest was small but for reasons that we all know, life taught them that technology is more an ally than an enemy, of course it is well managed.

However, this unique smell since the birth of the Internet of noobs has brought with it a massive amount of failures that we formerly considered unimportant but that is the reason for the massive migration of people to the Internet, we have discovered that they do enjoy an importance and not exactly minor.

Hackers generally spent our days solving relatively fictitious problems in blogs and more communication networks to satisfy a little our hunger and thirst for new real challenges, however since the beginning of the pandemic we have seen an increase in cases of virtual scam o Physhing quite worrying things like "The nitro discord scam" or as I like to call it the scam of the young easy gamers is a scam that basically seeks the massive obtaining of privileged data in a free and "safe" way by a not so well known means , like these there is a huge list of physhing cases reported only in December 2021 but hey I'll leave that for another post

without further ado I say goodbye and as I always say good luck have fun
Ciberseguridad en tiempos de CoVid-19 
Tags: cybersecurity, python, vue, java
Published: 2021-12-07 03:22:03

Para nadie es un secreto que el covid modifico nuestra realidad al punto de que las personas que antes se mostraban "amenazadas" por la tecnologia hoy la ocupan como metodo de vida, un claro ejemplo de esto son los doctores y personal de salud en general, personas cuyo interes tecnologico era infimo pero que por razones que ya todos conocemos la vida les enseño que la tecnologia es mas un aliado que un enemigo, claro esta bien manejada.

Sin embargo esta oliada sin igual desde los tiempos del nacimiento del internet de noobs ha traido en si una masiva cantidad de fallos que antiguamente considerabamos sin importancia pero que ha razon de la migracion masiva de personas al internet hemos descubierto que si gozan de una importancia y no precisamente menor.

Los Hackers generalmente pasabamos nuestros dias resolviendo problemas relativamente ficticios en blogs y de mas redes de comunicacion para satisfacer un poco nuestra hambre y sed por conocer nuevos retos reales, sin embargo desde el inicio de la pandemia hemos visto un incremento en los casos de estafa virtual o Physhing bastante preocupante cosas como "La estafa del discord nitro" o como me gusta llamarla la estafa de los jovenes gamers facilistas es una estafa que basicamente busca la obtencion masiva de datos privilegiados de forma gratis y "segura" por un medio no tan conocido, como estos ahi una enorme lista de casos de physhing reportados solo en diciembre del 2021 pero bueno eso lo dejare para otro post

sin mas me despido y como siempre digo good luck have fun
Code Smell 109 - Automatic Properties
Tags: oop, webdev, codenewbie, tutorial
Published: 2021-12-07 03:01:02

*What happens if you combine 4 code smells?*

> TL;DR: Avoid Getters, Avoid Setters, Avoid Metaprogramming. Think about Behavior.

# Problems

- Information Hiding Violation

- [Mutability](https://dev.to/mcsee/the-evil-powers-of-mutants-1noo)

- [Fail Fast Principle](https://dev.to/mcsee/fail-fast-48dm) violation

- Duplicate code when setting properties

# Solutions

1. [Remove automatic setters and getters](https://dev.to/mcsee/refactoring-001-remove-setters-26cg)

# Context

Setters and getters are a bad industry practice.

Many IDEs favor this code smell. 

Some languages provide explicit support to build anemic models and DTOs.

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/2353f11cfb336aaeda194c4a11a21324)
```csharp
class Person
{
  public string name 
  { get; set; }
}
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/198d8a232bd1abf52cda0884fb96bc5f)
```csharp
class Person
{
  private string name  
  
  public Person(string personName)
  {
    name = personName;
    //imutable
    //no getters, no setters
  }

  //... more protocol, probably accessing private variable name
}
```

# Detection

[X] Automatic 

This is a language feature.

We should avoid immature languages or forbid their worst practices.

# Tags

- Encapsulation

# Conclusion

We need to think carefully before exposing our properties.

The first step is to stop thinking about properties and focus solely on behavior.

# Relations

{% post https://dev.to/mcsee/code-smell-28-setters-2hih %}

{% post https://dev.to/mcsee/code-smell-68-getters-o12 %}

{% post https://dev.to/mcsee/code-smell-70-anemic-model-generators-1jpl %}

{% post https://dev.to/mcsee/code-smell-40-dtos-4426 %}

{% post https://dev.to/mcsee/code-smell-01-anemic-models-4dg2 %}

# More Info

- [W3 schools](https://www.w3schools.com/cs/cs_properties.php)

- {% post https://dev.to/mcsee/laziness-i-meta-programming-32a9 %}

- {% post https://dev.to/mcsee/laziness-ii-code-wizards-56p0 %}

- {% post https://dev.to/mcsee/refactoring-001-remove-setters-26cg %}

- {% post https://dev.to/mcsee/the-evil-powers-of-mutants-1noo %}

- {% post https://dev.to/mcsee/fail-fast-48dm %}

# Credits

Photo by <a href="https://unsplash.com/@konyxyzx">Kony</a> on <a href="https://unsplash.com/s/photos/shoot">Unsplash</a>
  
* * *

> Nothing is harder than working under a tight deadline and still taking the time to clean up as you go.

_Kent Beck_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Setup MERN by GitHub Actions
Tags: actionshackathon21, github, opensource, deployment
Published: 2021-12-07 02:55:21

---
title: Setup MERN by GitHub Actions
published: true
description: My submission to the GitHub Actions x DEV Hackathon 2021!
tags: actionshackathon21, github, opensource, deployment
---

Dependencies are frequently dealt with in typical MERN stack applications.
This workflow aims to install dependencies on the server and client sides automatically based on package.json. 

### My Workflow
[Close Count GitHub](https://github.com/phonist/close_count)
Close Count is an example project in which end users can create multiple timers for their events.

There are two major folders: server and client.

As stated in the title, the project is built on top of MERN.

Install dependencies for each server and client side package by package.json

### Submission Category: 

Wacky Wildcards

### Yaml File
When changes are pushed to the master branch, the actions will be triggered. In fact, the master branch serves as the production deployment.

```
name: Production script

on:
  push:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-20.04

    steps:
      - uses: actions/checkout@v2
      - name: Install Nodejs and NPM
        run: |
          curl -sL https://deb.nodesource.com/setup_16.x | sudo -E bash -
          sudo apt install nodejs
      - name: Install nodejs, npm and yarn
        run: |
          curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg
          sudo apt-key add -echo "deb https://dl.yarnpkg.com/debian/ stable main" 
          sudo tee /etc/apt/sources.list.d/yarn.list
          sudo apt update && sudo apt install yarn
          echo nodejs version
          node -v
          echo npm version
          npm -v
          echo yarn version
          yarn -v
  server:
    needs: build
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v2
      - name: Install server dependencies
        working-directory: ./server
        run: |
          yarn install
  client:
    needs: build
    runs-on: ubuntu-20.04
    steps:
      - uses: actions/checkout@v2
      - name: Install client dependencies
        working-directory: ./client
        run: |
          yarn install     

```

Ubuntu-20.04 was chosen as the operating system for the workflow.
First, install the YARN package manager.
After that, run yarn install in both the server and client folders to install all required dependencies.