teleren/devto huggingface dataset:
Curse of dimensionality...
Tags: machinelearning
Published: 2022-04-02 13:17:02

**Prerequisites : Familiarity with KNN**

Most of us know that, more features(data) leads to more accuracy for a particular Machine Learning model. But for [K Nearest Neighbours Classifier](https://en.wikipedia.org/wiki/K-nearest_neighbors_algorithm), things are a bit different. If it finds an irrelevant feature, it will still use it as a useful data, and eventually lead to noise/fallacy.
There is another instance. Let's suppose there's a data with 2 or more features with relatively the same meaning/values. Then our classifier will treat 2 features as seperate, and that feature will get eventually more weightage/importance. This can also lead to bad results.

Thus, _one way_ is to **assign weights** to our features.
Instead of using summation of the [Euclidean](https://xlinux.nist.gov/dads/HTML/euclidndstnc.html)/[Manhattan](https://xlinux.nist.gov/dads/HTML/manhattanDistance.html) distance as our parameter, we should use summation of weight[i]*distance(between 2 data-points) as our parameter. Calculating the weight is not really difficult. We can assign random weights to the respective feature value. Then we can calculate the best suited weight[i] with the help of Cost(error) function and [Gradient Descent](https://en.wikipedia.org/wiki/Gradient_descent) to minimise the cost.

_Another way_ is to use **feature selection**.
Generally in KNN, we use **backward elemination** for this purpose. It basically means that we calculate the accuracy of the ML model while keeping the feature and removing the feature. Accordingly it keeps or eleminates the feature(s) based on higher accuracy value. This is easier to implement for a dataset, than the previous one.


**Question :**
Consider the dataset given below :-

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

If we decide to give weights to manage our features in KNN and we have our data as shown below, what might possibly be the weights assigned to feature1 and feature2? There are other features also present in the data-set which are not shown for clarity purposes. Assume that weights vary between 0 and 100. Max weight is 100 and min weight is 0.

_Answer_ - As we can notice that both the features are having similar values we give importance to only one feature and assign less weight to the other. Any one of the two features can be given higher weight.

**Links :**

- [Github](https://github.com/AryaChakraborty)
- [Twitter](https://twitter.com/ChakrabortyAry1)
Principal Component Analysis (PCA), Python Code
Tags: machinelearning, datascience, python, programming
Published: 2022-04-02 12:34:12


[![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oer5a4j30lwsm5xyzto3.png)](https://laid-back-scientist.com/en/pca-imple)
In this article, we will implement Principal Component Analysis using Python.
👇
https://laid-back-scientist.com/en/pca-imple
Book Club: "Test Driven Development: By Example" #2
Tags: books, tdd, discuss
Published: 2022-04-02 12:26:28

---
title: Book Club: "Test Driven Development: By Example" #2
published: true
description: A chapter by chapter discussion of "Test Driven Development By Example" by Kent Beck
tags: books, tdd, discussion
series: Book club TDD By Example

---

> The goal is clean code that works
<sup>- Ron Jeffries</sub>

## Chapter 2: Degenerate Objects

Part of the process of writing tests in small steps is iterating to improve and _design_ your code. As a result, the code is easy to understand, and works (at least to your most-current level of understanding).

"Write a test. Make it run. Make it right." It's tempting to make it right before making it run, but then you don't have the safety of your tests to allow you refactor and explore more elegant or efficient solutions.

Beck talks about two strategies to get your tests to run,

* Return a constant and replace with variables one by one until the code works
* Use the real implementation from the start -when it's obvious

I typically use the approach of writing out in plain English my given/when/then scenario, which I can build on with code that returns constants, then build out with code that really works. Most of the time though, the test I'm working out in plain English isn't obvious to me... this seems to be a skill that comes with practise and experience. 

> Once we decide on the correct behavior, we can talk about the best way of achieving that behavior.

Beck mentions the the habit of TDD creates awareness of _when something isn't right_ in the design (he gives 'disgust at side effects' as an example). This is difficult to hone, but determining the _behaviour_ first is important.


🔎 View my code-along repo at https://github.com/ruthmoog/test-driven-development-by-example 

---------

![Book cover](https://learning.oreilly.com/library/cover/0321146530/250w/ ) Kent Beck's "[Test Driven Development: By Example](https://www.oreilly.com/library/view/test-driven-development/0321146530/)" was released in 2002. The book aims to explain how to use TDD to write quality code that works.
MongoDB CRUD Operations
Published: 2021-12-23 07:33:50

##  	**MongoDB CRUD Operation:**
CRUD stands for
C- create,
R- read, 
U-update, 
D- delete
**Create Operations:**
MongoDB has two insert method:

1.db.collection.insertOne() 
2. db.collection.insertMany() 
**InsetOne Method:**

```
await db.collection('inventory').insertOne({
  item: 'canvas',
  qty: 100,
  tags: ['cotton'],
  size: { h: 28, w: 35.5, uom: 'cm' }
});
```
**InsetMany Method:**

```
await db.collection('inventory').insertMany([
  {
    item: 'journal',
    qty: 25,
    tags: ['blank', 'red'],
    size: { h: 14, w: 21, uom: 'cm' }
  },
  {
    item: 'mousepad',
    qty: 25,
    tags: ['gel', 'blue'],
    size: { h: 19, w: 22.85, uom: 'cm' }
  }
]);


Read Operations:
Read operations retrieve documents from a collection.
db.collection.find()
Find METHOD:
const cursor = db.collection('inventory').find({
  status: { $in: ['A', 'D'] }
});
```

**Update Operations:**
Update operations modify the existing documents in a collection. MongoDB provides the following methods.
	

1. db.collection.updateOne()
2. db.collection.updateMany()
3. db.collection.replaceOne()
**UpdateOne Method:**

```
db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

```

**UpdateMany Method:**

```
db.collection.updateMany(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        
   }
)
```
**Replace One Method:**

```
db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     hint: <document|string>                   
   }
)
```

**Delete Operations:**
Delete operations remove documents from a collection. 

1. db.collection.deleteOne()
2. db.collection.deleteMany()

**DeleteOne Method:**

```
db.collection.deleteOne(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>,
      hint: <document|string>        // Available starting in MongoDB 4.4
   }
)
```
**Delete Many Method**

```
db.collection.deleteMany(
   <filter>,
   {
      writeConcern: <document>,
      collation: <document>
   }
)


```
 	

## **Relational Database**

**What is a Relational Database?**
A relational database defines database relationships in the form of tables. The tables are related to each other - based on data common to each.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5s7o8n2jeqqyn4uftmzt.png)
In Above Fig, Structure of the relational database Each box on the figure above contains one table called here the relation of the database.
**

 

## Express.js Hello World Example:
```
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

```
Devs for friends, advisers, collaborators
Tags: webdev, programming, python, career
Published: 2022-04-02 12:01:13

Let's build something.
I ' been working with python Django framework for web dev for sometimes now. I'm working on a project currently it's a kind of all these crypto websites but I'm using some APIs for the development of the project such as the buying and selling and receiving of coins and the exchange rate changes. 
I really don't know if it's a cool project tho, but I know it's awesome anyway.
I'm just looking for collaborators, not sort of collaborators tho but actually devs that has been in this world of tech for a very long time, they're experienced enough to know what it's gonna be like, they've gone through this process actually. What process I'm I talking about 🙄, developing on their own, they know what it looks like working alone they know how tedious it is when they're no advisers, when you're going through developing alone.
I don't mind Devs that can be friends for advising or putting me through some tangled stuffs . Thanks
MyBatis en tiempos de Java 8-17
Tags: java, mybatis, oracle
Published: 2022-04-02 11:50:59

Podríamos considerar a MyBatis, como la versión ligera de Hibernate. El cual se mantiene presente y adaptándose a los cambios de Java, en sus últimas versiones.

La versión estable corresponde a _3.5.9_.

```groovy
dependencies {

    implementation 'org.mybatis:mybatis:3.5.9'
    implementation 'com.oracle.database.jdbc:ojdbc8:19.6.0.0'
}
```
Estos son dos ejemplos que bien deberíamos usarlos, al utilizar MyBatis en nuestros proyectos.

1) Ya no necesitamos cerrar la sesión de forma explícita. Con
_Try-With-Resources_ (Java7) dejamos esa acción a la JVM. 
Y al emplear _Local-Variable_ (Java10), hacemos más legible el código.
```java
try (var sqlSession = sqlSessionFactory.openSession()) { //.1
            MapperRecaudacion mapper = sqlSession.getMapper(MapperRecaudacion.class);
            mapper.getTipoCambio3(mapParametros);
            vTipoCambio = (BigDecimal)mapParametros.get("nValorTipoCambio");
        } catch (Exception e) {
            log.error("", e);
        }
```
2) Para construir la sentencia SQL (el ejemplo corresponde a un SP de Oracle), nos valemos de _Text Block_ (Java15).
```java
    @Select(value = """
            {call #{nValorTipoCambio, mode=OUT, jdbcType=NUMERIC} := 
                FARMA_UTILITY.OBTIENE_TIPO_CAMBIO3(
                    #{cCodGrupoCia_in},#{cCodCia_in},#{cFecCambio_in},#{cTipo})}""") //.2
    @Options(statementType = StatementType.CALLABLE)
    void getTipoCambio3(Map<String, Object> mapParametros);
```
3) Adicionalmente, podemos reemplazar el operador ternario con _Optional_ (Java8).
```java
        //return vTipoCambio == null?0.0:vTipoCambio.doubleValue();
        return Optional.ofNullable(vTipoCambio)
                .map(BigDecimal::doubleValue)
                .orElse(0.0); //.3
```
---
## Documentación
{% embed https://github.com/edgargs/mybatis-oracle %}
[Try-With-Resources](https://docs.oracle.com/javase/7/docs/technotes/guides/language/try-with-resources.html)
[JEP 286: Local-Variable Type Inference](https://openjdk.java.net/jeps/286)
[JEP 378: Text Blocks] (https://openjdk.java.net/jeps/378)
[Optional](https://www.baeldung.com/java-8-new-features#optional)
Augmenting GitHub repository stats and insights
Tags: github, devops, opensource, nuxt3
Published: 2022-04-02 11:49:35

While GitHub is amazing (hence, their insane market share), they unfortunately provide only very limited insights for the repositories that they host. Moreover, most of the stats in the "Insights" tab are only available for PRO users when the repo is private.

Therefore, I set out to build a tool that augments those insights with loads of cool charts and cards. You can read the full story on why in [this post](https://dev.to/toniengelhardt/i-made-a-github-repo-tracker-with-nuxt-3-to-track-when-nuxt-3-is-ready-47l4). 

--- 

![RepoTracker Dashboard Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/222xhkcs3yox04cwfxx5.png)

---

RepoTracker is designed for two user groups:

1. Open source devs and -users that want to keep up with the latest changes, issues, etc. in the pre-rc repositories that they are working/playing with.

2. Professional software developers and dev ops peeps that need to know which of the packages their software depends on are properly maintained and which are not.

---

![RepoTracker Repository Details Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/06ye7f1aanzgh2478do7.png)

---

If you breathe software, try it out at [www.repo-tracker.com](https://repo-tracker.com), it's free! 

I'd love to hear what you think about the project and which metrics you would be interested in as a developer ✌🏽

Made with [Nuxt 3](https://v3.nuxtjs.org/).
Ways to Reduce your Front-End Codes
Tags: javascript, tutorial, css, beginners
Published: 2022-04-02 11:44:18

Here, several approaches will be introduced to reduce your front-end code base, especially, for reducing css codes. 

## Tailwind

* Link: [tailwindcss](https://tailwindcss.com/docs/installation) 

`tailwindcss` provides fast, flexible, reliable css classes. Using `tailwind` you can save time writing your css codes.

For instance, `truncate` for:
```
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
```

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

#### To optimize css codes in production

* Refer to [cssnano](https://cssnano.co/) and [Brotli](https://en.wikipedia.org/wiki/Brotli) as mentioned in [tailwind docs](https://tailwindcss.com/docs/optimizing-for-production)

## css-checker

* Link: [css-checker](https://github.com/ruilisi/css-checker) 

Wonder how to find your duplicated css codes? There is a automatic tool that can help you scanning all your css & styled-components codes and show similar classes with diffs.

![DEMO](https://assets.ruilisi.com/css-checker-demo.gif)

* To Install:
```
npm install -g css-checker-kit
```
* To Run: 
```
css-checker
```

## Using useSWR

* Link: [useSWR](https://swr.vercel.app/en-US)

* `useSWR` can help you to reduce parsing states between components, just call `useSWR` in anywhere you wish to use the states.

* `useSWR` can also help you to reduce duplicated requests and auto-fetch after users' re-focus.

> The name “SWR” is derived from stale-while-revalidate, a HTTP cache invalidation strategy popularized by HTTP RFC 5861. SWR is a strategy to first return the data from cache (stale), then send the fetch request (revalidate), and finally come with the up-to-date data.

* To use it, it's quite simple:
```
import useSWR from 'swr'

function Profile() {
  const { data, error } = useSWR('/api/user', fetcher)

  if (error) return <div>failed to load</div>
  if (!data) return <div>loading...</div>
  return <div>hello {data.name}!</div>
}
```
Optimize query size in Django
Tags: database, queries, django
Published: 2022-04-02 10:35:03

### Problem

When your project grows, it's possible that with time you'll start having models with more and more fields. 
What are the consequences of that? Well, if you have a model with more than 30 fields and you are trying to retrieve an object or a list of objects from the database, the return `queryset` will be really heavy. 
And it's possible you won't definitely need all the fields. 

## How to optimize the query?

Django provides the `only()` method that returns a `queryset` with objects that only contain the list of fields and the values specified in the `only(*args)`.
As stated in Django, 

Here's an example: 

```python
from django.db import models


class User(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(max_length=254)
    bio = models.CharField(max_length=50)
    
    def __str__(self) -> str:
        return "%s (%s)" % (self.name,
            ", ".join(profile.first_name for profile in self.profile_set.all()))
```
And here's the `queryset`:
```python
users = User.objects.only('name', 'email').all()
```

There is also the `defer()` method -- opposite to `only` -- that can be used to remove fields you don't want to use in a particular query. 
Following this, these two queries are identical if the `User` table has only `name`, `email`, and `bio` fields.

```python
users = User.objects.only('name', 'email').all()

users = User.objects.defer('bio').all()
```

*Article posted using [bloggu.io](https://bloggu.io). Try it for free.*
How To Install Node.js and NPM on Ubuntu 20.04
Tags: ubuntu, node, npm, linux
Published: 2022-04-02 11:18:06

Run following commands on terminal

```
sudo apt update
```

```
sudo apt install nodejs
```
To check which version of node is installed on machine type following command

```
node -v
```

To install NPM (Node Package Manager) run following command on terminal

```
sudo apt install npm
```

---
[GitHub](https://github.com/G-Sudarshan) | [LinkedIn](https://www.linkedin.com/in/g-sudarshan/) | [Twitter](https://twitter.com/g_sudarshan11)
Search for objects and check the property before buying
Published: 2022-04-02 11:10:12


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

To apply for an online real estate inspection report, enter the cadastral number or address of the property. Next, find an object and arrange a property inspection service before buying. After payment, your E-mail will receive a full report on checking the property for legal purity within a few hours (the timing depends on the database's workload).

Execution time - 6-24 hours.
Urgent inspection reports are completed within 6-12 hours. The maximum formation time is three enslaved people. Day.

Relevance and reliability
Verification reports are based on up-to-date real estate data.

Order Fulfillment Guarantee
In case the object is not found, or there are those. Failures, a full refund is guaranteed at the request of citizens of the india Federation.

**Information and Sample Property Inspection Reports**

Checking the apartment before buying
An apartment inspection report is required when buying a home on the secondary market. Allows you to verify the actual owner's ownership of the property. The sample is on the right.
Execution time: 12-24 hours (terms depend on the workload of the base)
Format: Electronic document in PDF format

Online services for checking the legal purity of real estate before buying:

**Checking the apartment upon purchase**

The service will check the apartment for jur. Cleanliness, availability of collateral, and encumbrances. The ownership and debts of the owner.

**Land check**

An online check of the land plot by cadastral number for pledge, arrest, and information about the owner.

**Checking the property, buildings, structures**

I was inspecting the property by cadastral number online.

**Reference information on all real estate objects in the india Federation**

The online service is a complete database of all [real estate listing directory](
https://www.properties.dialnumber.in/) objects for free provision to citizens of the india Federation The formation of this service has become necessary to provide full and open information about land plots, apartments, garages, and parking spaces. Each user will be able to check the property before buying for legal purity and protect [themselves](https://www.merriam-webster.com/dictionary/themselves).

Since 2017, instead of brilliant green, extracts are required in each case for sales transactions and execution of other documents related to real estate. A section is a legal document that confirms the right to own an object and indicates the current owner.This service provides free information about objects and allows you to get a legal check of the thing before buying.
The Ultimate Client to Dev Win-Win Situation
Tags: career, showdev, discuss, programming
Published: 2022-04-02 11:05:23

Ever stuck on what to program next? Well, I am basically always stuck on what to program next. When we devs get an idea, do you ever consider the possibility of no one liking it?

Well, let me tell you one thing, I got a solution. Is there a platform where people in need can give you some inspiration on what to program next? Please comment below if you know a platform like this.

If there is this dream platform, which connects clients and developers, making them all happy. Just imagine the idea of having a list of billion dollar start-ups right on your browser?

I know, this sounds like a bit of a promotion, but sadly, I've got nothing to promote, yea, I just got this idea, and if someone has the time, please build this dream platform. 

Tell me if I suck and such a platform already exists, but if it doesn't, and no one is willing to make it, I'll have to use my final resort, doing it myself.

I am going to leave this article for 3 days, and if no one tells me that they are making this community, then I'll just have to do it myself, please comment below if you would like to join me in this journey!

Farewell fellow developers, see you next time!
what to do if i want to visible mat-sidenav on drawer closed using angular material 13.3.2
Published: 2022-04-02 10:21:21

using below not working
  .mat-sidenav:not(.mat-drawer-opened) {
    transform: translate3d(0, 0, 0) !important;
    visibility: visible !important;
    width: 60px !important;
    overflow: hidden;
  }
100 Days of Code: The Complete Python Pro Bootcamp for 2022 - Day 2 (Tip Calculator)
Published: 2022-04-02 10:09:40

Exercise 1 - Data Types
````python
#🚨 Don't change the code below 👇
two_digit_number = input("Type a two digit number: ")
#🚨 Don't change the code above 👆

####################################
#Write your code below this line 👇
first_digit = two_digit_number[0]
second_digit = two_digit_number[1]
int_first_digit = int(first_digit)
int_second_digit = int(second_digit)
result = int_first_digit + int_second_digit
print(result)
```
Exercise 2 - BMI Calculator
````python
#🚨 Don't change the code below 👇
height = input("enter your height in m: ")
weight = input("enter your weight in kg: ")
#🚨 Don't change the code above 👆

#Write your code below this line 👇
bmi = int(weight) / float(height) **2
bmi_int = int(bmi)
print(bmi_int)
```
Exercise 3 - Life in weeks
````python
#🚨 Don't change the code below 👇
age = input("What is your current age?")
#🚨 Don't change the code above 👆

#Write your code below this line 👇
days = 90 * 365 - int(age) * 365
weeks = 90 * 52 - int(age) * 52
months = 90 * 12 - int(age) * 12

print(f"You have {days} days, {weeks} weeks, and {months} months left.")
```
Project Day 2 - Tip Calculator
````python
#If the bill was $150.00, split between 5 people, with 12% tip. 
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60

#Tip: There are 2 ways to round a number. You might have to do #some Googling to solve this.💪

#Write your code below this line 👇
print("Welcome to the tip calculator")
bill = int(input("How much is your bill? $ "))
tip = int(input("How much tip do you want to leave? 10, 12 or 15 percent? "))
people = int(input("How many people will split the bill? "))
bill_with_tip = tip / 100 * bill + bill
split = (bill_with_tip / people)

#Note - The round function did not produce the result asked so had #to change it the below. Thank you google lol

total_bill_split = "{:.2f}".format(split)
print(f"Each person should pay ${total_bill_split} ")
```
Error: Multipart: Boundary not found
Tags: axios, reactnative, multer, node
Published: 2022-04-02 10:04:38

I got this when uploading files to my nodejs API from my react and react-native apps and the problem was with my axios version. i was running the latest at the time which is 0.25.0 so i had to downgrade to 0.21.4.
first uninstall axios
```
npm uninstall axios
```
then install version 0.21.4 or any other version that you have used before that works without getting this error. in my case it was version 0.21.4
```
npm install axios@0.21.4
```
Hope it works for you