teleren/devto huggingface dataset:
Javascript Hoisting
Tags: webdev, programming, javascript, algorithms
Published: 2022-01-02 16:34:16



## What is

Hoisting is basically a behavior from javascript that we can see in execution time, it makes functions and variables go to the top of the scope in which they were declared.

---

## Const, let & var
Before see some examples, we need to understand the difference between these three ways to declare a variable.

- **var**: On the start of javascript, we had only var, currently, we don't have reasons to use it, the hoisting concept is applied just to this type of declaration, and, it can be problematic by some reasons I will explain later. Another point we can say here is, its value can be reassigned.

- **let**: unlike var, hoisting is not applied to let, it's a reason to prefer it, but, like var, its value can be reassigned.

- **const**: like let, hoisting is not applied to it, another point about const is that it can't has its value reassigned.

---

**to stay tuned**: in this case, reassigned means that variable can or not has a new value, don't think that it applies to object and arrays manipulation, we can do this normally.

---

**resume**: with const and let among us, prefer use they, when you will need to change the value from any variable in execution time, prefer let, unlike it, prefer const.

---

## Operation


**Functions**


```
hoistMe() // output: I'm being executed by hoisting

function hoistMe() {
   console.log('I\'m being executed by hoisting')
}
```

In the example above, the hoisting works effective, repair we call the function before its initialization!


**Variables**

In the example below, we use a _const_, referring to it, we repair that hoisting is not applyied!

```
console.log(assignedToConst) // output: cannot access before initialization

const assignedToConst = 'hoisted'
```

OBS: with let the result would be the same

---

Now we can see a interesting behavior from hoisting

```
console.log(assignedToVar) // output: cannot access before initialization

const assignedToVar = 'hoisted'
```

executing this piece of code above, we see the specified output, it occurs because hoisting not assign the value, just declares on top, the assignment occurs where it was really implemented! Pay attention with this behavior, it makes your code ready to bugs!

---

Unusual use case but worth understanding:

```
handle = '\'hoisted\'';

console.log(handle); // output: 'hoisted'

var handle;
```

if we assign the value before and declare it later the hoisting is done successfully

---

## Considerations
This explained concept works independent the scope, still the presented examples be all at global scope, for example:

```
function anotherHoistTest() {
   hoistMe()
   function hoistMe() {
      console.log('hoisted');
   }
}
anotherHoistTest() // output: hoisted
```

---

I think is good say to you do not enjoy from this behavior, it makes your code more fragile and less readable and concise.

---

## Author

Follow me:
- https://linktr.ee/nate.sfteng
Day 2: API Foundations
Tags: 100daysofcode, typescript, career
Published: 2022-01-02 15:52:12


After scaffolding the project on [Day 1](https://dev.to/theaccordance/day-1-project-scaffolding-4dfi), it's now time to start building out an application.  Today's work encompassed getting a functional foundation for the API in place, that way I can focus on building the endpoints related to the actual feature in future days.  

## Progress Summary
- Installed [Express](https://www.npmjs.com/package/express), [Body Parser](https://www.npmjs.com/package/body-parser), [Compression](https://www.npmjs.com/package/compression), [Cors](https://www.npmjs.com/package/cors), [Express Request ID](https://www.npmjs.com/package/express-request-id), and [Morgan](https://www.npmjs.com/package/morgan) for the foundation of the API.  
- Installed [Convict](https://www.npmjs.com/package/convict) & wrote a configuration file with default values and environment variable mappings.  
- Installed [Winston](https://www.npmjs.com/package/winston) & implemented a customized logger.
- Implemented a `.well-known/` endpoint that describes the state of the API. 
- Installed [Git Rev Sync](https://github.com/kurttheviking/git-rev-sync-js) to provide local values for the current git commit and branch, which will be included in the well-known endpoint.  
- Added an npm script `start:api` to launch the API.

![Accessing the API from the browser](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sghf1rdixtvxivhxbni0.png) 

Interested in seeing the code changes?  Check out the diff by reviewing this [Pull Request](https://github.com/theaccordance/100-days-of-code/pull/2) for Day 2.
Paracetamol.js💊| #1: ¿Cuales son los presentes tipos de datos de JavaScript?
Tags: javascript, beginners, spanish, webdev
Published: 2022-01-02 15:50:48

# **Tipos primitivos:**

```js
console.log(typeof "Rojo"); // string
console.log(typeof 21); //number
console.log(typeof true); // boolean
console.log(typeof undefined); // undefined
console.log(typeof Symbol()); // symbol
console.log(typeof 2n); // bigint

console.log(typeof null); // object
```

`null` es primitivo pese a que nos da `object`, ello por un bug que tiene el lenguaje como tal.

## **Objetos**

```js
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof function () { }); //function
```

Las funciones son utilizan el constructor `Object` pero con una pequeña variante, pero en el fondo son objetos.
AWS Basics - Beginner's Guide to EBS
Tags: aws
Published: 2022-01-01 16:40:07

## EBS Volumes

EBS stands for **Elastic Block Store** - Virtual disks in the cloud (spread across regions) that we attach to EC2 instances.

EBS volume attached to an EC2 instance is called ***root device volume***.

EBS volumes can be used to

1. create a file system
2. run a database
3. run an OS
4. store data
5. install applications

EBS volumes are designed for

1. mission critical workloads
2. **highly available** - auto-replicated within a single availability zone to protect against hardware failures
3. **scalable** - dynamically increase capacity or change type of volume with zero downtime or performance impact on live systems

### Available EBS volume types

#### General purpose SSD (GP2)
- ***Balances both price and performance***
- 3 IOPS (Input/output operations per second) per GB
- Up to 16,000 IOPS per volume
- GP2 volumes smaller than 1 TB can burst upto 3,000 IOPS
- good for boot volumes, dev/test applications and anything that is latency insensitive

#### Provisioned IOPS SSD (IO1)
- ***High performance and most expensive*** 
- 50 IOPS per GiB
- Up to 64,000 IOPS per volume
- greater than 16,000 IOPS 
- good for I/O intensive applications or latency sensitive applications

#### Provisioned IOPS SSD (IO2)
- Latest gen
- 500 IOPS per GiB
- Higher durability (99.999%) and more IOPS
- same price as IO1
- Max limit same as IO1

#### Throughput Optimized HDD (ST1)
- for big data, data warehouse, ETL, log processing 
- cannot be a boot volume
- additional volume
- low cost
- 40 MB/s per TB
- burst up to 250 MB/s per TB
- max throughput of 500 MB/s per volume

#### Cold HDD (SC1)
- low cost storage
- file server
- cannot be a boot volume
- baseline 12 MB/s per TB
- burst up to 80 MB/s per TB
- max throughput of 250 MB/s per volume

#### Magnetic (Standard)
- Ideal for workloads where data is accessed infrequently
- legacy
- useful when lowest storage cost is important

### Creating an EBS Volume Type and attaching it to a host

1. Go to `EC2 Dashboard`.
2. Select `Volumes`.
3. Select `Create volume`.

To attach a volume to an existing EC2 instance, select `Actions` and `Attach Volume`.

> Creating a volume with a snapshot ID leads to creating a replica of the original volume used to create the snapshot. 

> Volumes that are created from encrypted snapshots are automatically encrypted, and volumes that are created from unencrypted snapshots are automatically unencrypted. 

> If no snapshot is selected, we can choose to **encrypt** the volume and **specify your own key</b>.**

### IOPS vs Throughput

| **IOPS** | **Throughput** |
| - | - |
| measures the number of read and write operations per second | measures the number of bits read or written per second (MB/s) |
| for quick transactions, low latency apps, transactional workloads | for large datasets, large I/O sizes, complex queries |
| has the ability to read and write quickly | works well with large datasets |
todo list app (CRUD operations) using only useState hook | react | tailwind css |  next
Tags: tailwindcss, react, tutorial, nextjs
Published: 2022-01-02 15:38:59

todo list app (CRUD operations) using only useState hook | react | tailwind css |  next
https://www.youtube.com/watch?v=fDKUjwUPBNs
if you liked our content please subscribe to the channel and leave a nice comment
Please remove that .DS_Store
Tags: cybersecurity, security, macos, git
Published: 2022-01-02 15:26:42

macOS automatically creates `.DS_Store` when you open a folder with Finder, the default file manager. The operating system stores some information in binary in this file, for example, the list of files inside the folder.

You cannot read a `.DS_Store` file just by opening it (binary data), but it's pretty easy to decode. If for some reason, the file gets deployed to a webserver, things can turn nasty:

* it might disclose some information such as the name of some removed files as `.DS_Store` files are only updated by Finder
* it might also be used to [download files recursively](https://github.com/lijiejie/ds_store_exp) from the webserver 🔥

How the heck can you deploy such files on production?

It happens more often than you might think, for example, when you don't ignore `.DS_Store` files in your project's `.gitignore.` I see it very frequently, including in public repositories.

The best approach, to me, is to configure it globally on your machine. This way, even if you forget to ignore those files in your particular project, it will be skipped anyway.

The following command will locate your global `.gitignore` file:

```
git config --global core.excludesfile  
```

Open it and verify that `.DS_Store` files are in the list. 

If the ignore file does not exist yet, create a `.gitignore` file at the root of your home directory and run this:

```
git config --global core.excludesfile ~/.gitignore
```

It will set the file as the global ignore file. You can find plenty of templates on the web to get a robust list for various usages.

To list and remove potential existing `.DS_Store` in your repository:

```
find . -name .DS_Store -print0 | xargs -0 git rm -f --ignore-unmatch
```

Be safe.
Thread Congestion In Java
Tags: java
Published: 2022-01-02 14:19:24

**_Thread Congestion_** can occur when two or more threads are trying to access the same, guarded data structure at the same time. "Guarded" mean that the data structure is guarded using synchronized blocks or a concurrent data structure so that the data structure is thread safe. The resulting thread congestion means that the threads trying to access the shared data structure are spending a high amount of time waiting in line to access the data structure - wasting valuable execution time on waiting.

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

## Thread Blocking Data Structure May Cause Thread Congestion
A data structure which blocks threads from accessing it - depending on what other threads are currently accessing it, may cause thread congestion. If more than one thread accesses such a data structure at the same time, one or more of the threads may be queued up waiting to access the data structure. The queueing of threads is not visible in code. This queueing happens inside the JVM. Therefore thread congestion is not easy to spot simply by looking at the code. We need profiling tools to detect thread congestion.

## A Blocked Thread Loses Execution Time
While a thread is blocked trying to execute a blocking data structure, it cannot do anything. While being blocked the thread loses possible execution time. The longer the thread is blocked, the more potential execution time it loses.

## More Threads - Higher Congestion
The more the number of threads that attempts to access a shared data structure, the higher the risk of thread congestion.

## Alleviating Thread Congestion
To lessen thread congestion we must reduce the number of threads trying to access the blocking data structure at the same time. There are several ways to reduce thread congestion namely:

- Multiple Data Structures
- Non-blocking Concurrency Algorithms

1. Multiple Data Structures
   One way to alleviate thread congestion is to give each consuming thread its own queue, and have the producing thread distribute the objects among those data structures.

2. Non-blocking Concurrency Algorithms
   Another way is to use "non-blocking concurrency algorithms" where the threads accessing the data structure are never blocked.
Binary Search explained in PHP
Tags: php, binarysearch, algorithms
Published: 2022-01-02 15:02:56

In this article, I will discuss how to apply binary search in PHP.

See the code example below:
```tsx
<?php
function binarySearch($array, $element) {
    $start = 0;
    $end = count($array) - 1;
    
    while($start <= $end) {
        $mid = floor(($start + $end) / 2);
        
        if ( $element == $array[$mid] ) {
            return $array[$mid];
        } elseif ( $element > $array[$mid] ) {
            $start = $mid + 1;
        } else {
            $end = $mid -1;
        }
    }
    return -1;
}

$number = [3,6,8,10,44,56,58,89,90,100,300];

echo binarySearch($number, 58);
```

## #step 1:
We have to define the starting point. Initially, this would be the first index of the array which is 0.
## #step 2:
We have to define the ending point. In this case, the last index of an array would be the total element of the array minus 1. Because array starts with index 0; Which is in PHP count($array) - 1;
## #step 3:
The middle point of an array would be in PHP floor( (start index + end index) / 2 ); This is a simple equation for getting the middle point of the array.
## #step 4:
Now the fun part begins. We have to define a while loop that will loop through the array if the starting point is greater than or equal to the ending point condition is meet. 

**First of all**, we will check if the given element is greater than or equal to the array mid-value is true. If this condition is true then we will return the array mid-value. Because this is the value we are looking for.

**Secondly**, if the element is greater than the value of the array mid-value, then we will reset the starting point to the midpoint with added 1. Because in this case, we know that the left part of the array is useless and the desired value would be in the right part of the array and we want to leave the left portion from the loop.

**Lastly**, if the element is smaller than the value of the array mid-value then we will reset the ending point to the midpoint by subtracting 1. Because the desired value would be the left portion of the array.

If no condition is applied that means we did not find our desire number and we will return -1. Because the number does not exist in the array list.

## Conclution:
This was a simple example to understand the binary search in PHP.
ASMR for productivity!!
Tags: asmr, bell, focus, productivity
Published: 2022-01-02 14:53:49

Many prefer some kind of music when they work. There are folks who listen to specific ASMRs for concentration. Few days back I came across *"Crystal Bell asmr"* category which made the use of bowl vibrations for focus and concentration. 

Below are the top 5 recommendations that you must try listening to:

1. [Crystal singing bowls](https://www.youtube.com/watch?v=nDBKREP3LkU)🌸
2. [Tibetan singing bowls](https://www.youtube.com/watch?v=TAESZsLJdVw)🏵
3. [3 hour crystal singing bowl](https://www.youtube.com/watch?v=gq8snFSEwlU)🌺
4. [70 minuts~7 chakras](https://youtu.be/iT6w3cEkpm0) ☘

-------------------------------------------------------
1. [Sunflower seed removal](https://www.youtube.com/watch?v=OU6qjcqrq2c) 🌻

-------------------------------------------------------

I hope you feel relaxed when you hear these!!🎈
First Vlog on Logic Code
Tags: opensource, programming, node, hdl
Published: 2022-01-02 14:32:04

{% youtube HJyFJ9Cb7p0 %}


It's my first video explaining the working with logic code. I feel like its too long for some but if you only want to see usage of the program skip to the last part. 
If you don't know what logic code is Read my previous post:
{% link https://dev.to/sachindas246/create-a-new-language-for-logic-circuits-b21 %}
My Django dev utilities
Published: 2022-01-02 14:30:31

# My Django dev utilities
* [.gitignore](#gitignore)
* [Docker](#docker)
* [Dev scripts](#dev-scripts)
* [Test scripts](#test-scripts)

These are some useful scripts I usually use while developing Django+Svelte apps. You can find the code [here](https://github.com/besil/django-svelte-sample-app/tree/docker).

The sample app is described in my previous article: [My Django-Svelte setup for fullstack development](https://dev.to/besil/my-django-svelte-setup-for-fullstack-development-3an8)

## .gitignore <a name="gitignore"></a>
My .gitignore is the following
```
echo '.venv
.vscode
.idea
db.sqlite3
__pycache__
**.pyc
staticfiles
.coverage
.pytest_cache' > .gitignore
```

## Dockerfile <a name="dockerfile"></a>
```
mkdir docker
touch docker/Dockerfile
touch docker/entrypoint.sh
```

docker/Dockerfile
```docker
FROM python:slim
ENV PYTHONUNBUFFERED 1
RUN pip install poetry

RUN mkdir /code
WORKDIR /code

COPY pyproject.toml /code
COPY poetry.lock /code
RUN poetry install

ADD frontend /code/frontend/
ADD myapp /code/myapp/
COPY manage.py /code/
ADD docker/entrypoint.sh /code

#ENTRYPOINT ["/bin/bash"]
CMD ["bash", "entrypoint.sh"]
```

docker/entrypoint.sh
```
PORT=${1:-8000}
poetry run python manage.py makemigrations
poetry run python manage.py migrate
poetry run python manage.py collectstatic --noinput
poetry run gunicorn --bind 0.0.0.0:$PORT myapp.wsgi
```


## Dev scripts <a name="dev-scripts"></a>
```bash
mkdir -p scripts
echo 'export DJANGO_DEBUG=ON
export LOGGING_LEVEL=DEBUG
poetry run python manage.py "$@"' >> scripts/manage.sh
echo "bash scripts/manage.sh runserver" >> scripts/run-dev-server.sh
echo "bash scripts/manage.sh makemigrations" >> scripts/migrate.sh
echo "bash scripts/manage.sh migrate" >> scripts/migrate.sh

mkdir -p scripts/docker/
echo "docker build -f docker/Dockerfile -t myapp:latest ." > scripts/docker/build.sh

echo "docker run -it --rm -p 8000:8000 myapp:latest" >> scripts/docker/run.sh
```

## Test scripts <a name="test-scripts"></a>
```
poetry add pytest pytest-cov pytest-xdist pytest-django pytest-watch --dev
```
``` bash
echo "[pytest]
log_cli = 1
DJANGO_SETTINGS_MODULE = myapp.settings
python_files = tests.py test_*.py *_tests.py" > pytest.init
```

``` bash
echo "export DJANGO_DEBUG=ON
export LOGGING_LEVEL=DEBUG
poetry run pytest -n 4 --cov=myapp $1" > scripts/run-tests.sh
```

``` bash
echo 'export DJANGO_DEBUG=ON
export LOGGING_LEVEL=DEBUG
poetry run ptw -c -p --runner "pytest --last-failed --new-first $1"' > scripts/run-tests-watch.sh
```
Building a NFT marketplace frontend (Typescript + Next JS + Tailwind CSS)
Published: 2022-01-02 14:16:06

Warning: I don’t want to waste you time here is nothing very important. It’s just few of my thoughts what I’m using to build a NFT market place theme. 

For a long time really wanted to build something with Next JS. But didn’t really get the time or patience to build it. First thought I would build a e-commerce website and Shopify API with it. As  WEB 3.0 and NFT’s is taking over the internet I thought why not build a NFT marketplace. Design mainly taken from opensea. I’m using Typescript instead of using JavaScript. And for styling I’m using Tailwind CSS. 

## Typescript

TypeScript is **a superset of the JavaScript language** that has a single open-source compiler and is developed mainly by a single vendor: Microsoft. The goal of TypeScript is to help catch mistakes early through a type system and to make JavaScript development more efficient. 

Actually, speaking truth I have never used JavaScript that much. After reading some article and watching YouTube video it was clear to me Typescript is a better option. 

## React JS

React is best for building complex UI. Where every single day there is development of JavaScript framework or library, React is by far the most used JavaScript library/framework to build UI. React component principle is great to write clean code and maintaining your code base. 

## Next JS 12

Next JS is a JavaScript framework build on the top of React which is really great to build complete website. React is mostly used to build Single page application(SPA) which not that great for SEO. In next js you have option for server side rendering(SSR) or Static Generation (SSG) which is great for SEO. Also it’s much easier to build website like this with Next Js as it has many of things like routing, image processing build in. 

## Tailwind CSS 3

Tailwind CSS basically is a CSS framework. It is base on utility principle. You need to add some class names in your html tags for styling. Tailwind really makes life really easy.  It’s really easy to make responsive design with it. Tailwind prioritize mobile first designing. Where you first write code for mobile screen.
Refactoring 003 - Extract Constant
Tags: oop, programming, refactoring, cleancode
Published: 2022-01-02 14:12:45

*You need to use some values explaining their meaning and origin*

> TL;DR: Name all your magic numbers

# Problems Addressed

- Readability

- Complexity

- Code Reuse

# Related Code Smells

- {% post https://dev.to/mcsee/code-smell-02-constants-and-magic-numbers-obb %}

# Steps

1. Move the constant code fragment to a constant declaration

2. Replace the values with a reference to the constant.

# Sample Code

## Before

[Gist Url]: # (https://gist.github.com/mcsee/4beca4e8726130c29a74b956df6aefe2)
```java
double energy(double mass) {
  return mass * 300.000 ^ 2;
}
```

## After

[Gist Url]: # (https://gist.github.com/mcsee/17728639113169878b08a95a373624e3)
```java
//1. Move the constant code fragment to a constant declaration
final double LIGHT_SPEED = 300.000;

double energy(double mass) {
  //2. Replace the old code with a reference to the constant.
  return mass * LIGHT_SPEED ^ 2;
}
```

# Type

[X] Automatic

Many IDEs support this safe refactoring.

# Why code is better?

Constant names add meaning to our code.

Magic numbers are difficult to understand and change.

Code must be as declarative as possible.
 
# Tags

- Readability

# Related Refactorings

{% post https://dev.to/mcsee/refactoring-002-extract-method-1eee %}

# Credits

Image by <a href="https://pixabay.com/users/tumisu-148124/">Tumisu</a> from <a href="https://pixabay.com/">Pixabay</a>

* * * 

This article is part of the Refactoring Series.
Codepedia
Tags: beginners, tutorial, discuss
Published: 2022-01-02 14:06:05

Hii we have recently launched  [Codepedia](https://onlinecodepedia.blogspot.com/2022/01/codepedia-learn-coding-world-for-free.html) where youngsters can learn coding words for free. Please if you know some words related to coding then please add them [here](https://onlinecodepedia.blogspot.com/2022/01/codepedia-learn-coding-world-for-free.html) it will be a great help.
Sort NumPy arrays in Python
Tags: python, programming
Published: 2022-01-02 14:04:41

---
title: Sort NumPy arrays in Python
published: true
description: 
tags: #python #programming
//cover_image: https://direct_url_to_image.jpg
---

NumPy Sort Algorithms
Sort in Ascending Order
Sort in-place
Sort by making a copy of the array
Sort in Descending Order
Sort in-place
Sort by making a copy of the array
Sort 2D Array
NumPy Axes
Sort 3D Array
Sort by Column
Sort Using Order
Sort by Multiple Columns
Sort by Row
Sort by Column till Specified Row or from Specific Row
Sort by Datetime
Sort with Lambda
Sort with NaN Values
Sort NumPy Array Containing Floats
Conclusion

https://likegeeks.com/sort-numpy-array/