teleren/devto huggingface dataset:
Add leading zeros to a number in JavaScript
Tags: javascript, typescript
Published: 2023-08-05 11:12:33

---
title: Add leading zeros to a number in JavaScript
published: true
date: 2023-01-14 17:00:00 UTC
tags: JavaScript,TypeScript
canonical_url: https://wojciech.space/add-leading-zeros-to-a-number-in-javascript/
---

 ![Add leading zeros to a number in JavaScript](https://wojciech.space/content/images/2023/01/trailing-zeros.png)

As I was looking for a more subtle solution for inserting leading zeros to a number than ``if (number < 10) return `0${number}`;``, I found [this answer on StackOverflow](https://stackoverflow.com/questions/8089875/show-a-leading-zero-if-a-number-is-less-than-10/8089938#8089938), which I want to expand to near-one line code snippet.

### TypeScript:

```typescript
// pad-number.ts
const padNumber = (number: number, leadingZeros: number): string => {
  return `${number < 0 ? "-" : ""}${String(Math.abs(number)).padStart(leadingZeros, '0')}`;
}
```

### JavaScript:

```javascript
// pad-number.js
const padNumber = (number, leadingZeros) => {
  return `${number < 0 ? "-" : ""}${String(Math.abs(number)).padStart(leadingZeros, '0')}`;
}
```
Mastering the Fundamentals: Essential JavaScript Concepts Every Developer Must Know
Tags: webdev, javascript, beginners, programming
Published: 2023-01-14 16:45:29

JavaScript is a powerful and versatile programming language that is widely used in web development. It is essential for front-end developers to create interactive and dynamic user interfaces, and it is also used in back-end development to create powerful server-side applications.

However, with its versatility also comes a steep learning curve. As a developer, it is important to have a solid understanding of the fundamental concepts of JavaScript in order to effectively use the language.

One of the most important concepts in JavaScript is its object-oriented nature. Understanding how to create, manipulate, and inherit objects is essential for creating complex and maintainable code.

Another key concept is the use of variables and data types. Being able to properly declare and use variables, as well as understanding the different data types available in JavaScript, is crucial for creating efficient and effective code.

JavaScript also has a unique feature that is called closure. Closure is an important concept that allows developers to create functions that are independent of the context in which they were created. This allows for greater flexibility and reusability of code.

Event handling is also a crucial concept for JavaScript developers. Understanding how to properly handle events, such as user interactions or asynchronous operations, is essential for creating responsive and high-performance web applications.

Finally, understanding the Document Object Model (DOM) is essential for creating dynamic web pages. The DOM is a programming interface for HTML and XML documents, and understanding how to interact with it is crucial for creating web pages that respond to user input and update in real-time.

In conclusion, mastering these fundamental concepts of JavaScript is essential for any developer looking to effectively use the language in web development. By understanding the object-oriented nature of JavaScript, variables and data types, closure, event handling, and the DOM, you can unlock the full power and versatility of this language.
Unlocking the Power and Versatility of JavaScript: Why Every Developer Should Love this Language
Tags: webdev, javascript, programming, beginners
Published: 2023-01-14 16:43:27

`JavaScript` is a versatile and powerful programming language that has become an essential part of the web development ecosystem. As a developer, I have found that there are many reasons to love JavaScript and here are just a few of them.

First, JavaScript is incredibly versatile. It can be used on the front-end to create interactive and dynamic user interfaces, as well as on the back-end to create powerful server-side applications. This means that with just one language, you can create a complete web application.

Second, JavaScript has a very active and supportive community. The language is constantly evolving and improving, and there is a wealth of resources and libraries available to developers. Whether you're looking for a specific library to solve a problem or just need help with a tricky issue, there is always someone out there who can help.

Third, JavaScript's ability to handle asynchronous operations makes it well-suited for creating responsive and high-performance web applications. Asynchronous programming allows you to execute multiple tasks simultaneously, which can greatly improve the user experience of your application.

Fourth, JavaScript is a language that is easy to learn and use, even for beginners. Its syntax is simple and intuitive, making it accessible to developers of all skill levels. Moreover, the availability of many frameworks and libraries for javascript makes it easier for developers to create complex apps.

Fifth, JavaScript is supported by all major web browsers, which means that your code will run on any device with a browser.

In conclusion, JavaScript is a powerful, versatile, and widely-supported language that is well-suited to a wide range of web development tasks. Its active community, ability to handle asynchronous operations, ease of use, and browser support make it an excellent choice for any developer. I have found that it is a great pleasure to work with javascript and I will always love it.
Best way to Inspect JSON in Chrome DevTools
Tags: webdev, javascript, beginners, programming
Published: 2023-01-14 16:36:34


Have you ever found yourself in a situation where you need to inspect the JSON data in developer tools? If so, you might click through properties to expand them and see what is inside. However, with a nested JSON it could take some clicks to get to what you are looking for. What if there is a better way? Well, there is :)

## Did you know you could recursively expand JSON objects in Chrome DevTools?

You can expand a JSON object recursively in chrome developer tools by either right clicking on the object and choosing the expand recursively option from the context menu or using a keyboard shortcut for the same, which is `ALT + Click` on Windows and `Command + Click` on Mac.

If you prefer video format please do check out my YouTube video:

{% youtube DaHV34tMMeQ %}

---

I hope you find this tip interesting and helpful.
If you did, please give it a like and share it with someone who might benefit from it.

My name is Ashutosh, and apart from working as a software engineer, I love to share my learning with the community.
You can connect with me on [LinkedIn](https://www.linkedin.com/in/iamashutoshbhardwaj/) and follow me on [Twitter](https://twitter.com/BhardwajAshu96).
An Introduction to Smart Contract - Part 2
Tags: web3, blockchain, smartcontract, solidity
Published: 2023-01-14 16:22:55

Although smart contracts express and enforce all contractual provisions, a court of law does not comprehend the code. This dilemma presents various legal concerns concerning smart contracts: Can it be created in a manner that a court would accept and understand? Is it possible to incorporate dispute resolution inside the code? Before smart contracts are utilized as effectively as conventional legal agreements, regulatory and compliance issues must also be addressed.

Despite their name, smart contracts perform exactly what they are intended to do, which is excellent since this characteristic assures that smart contracts provide the same outcome every time they are run. Due to the persistent consensus needs of blockchain systems, smart contracts are deterministic. So smart contracts are just doing what they are supposed to do.

This creates a wide divide between the actual world and the blockchain realm. In this case, the smart contract cannot comprehend plain language, and the code cannot grasp the natural world. So, how can real-life contracts be put on a blockchain? How can this real-world-to-smart-contract bridge be built?

The above questions provide for making smart contract code intelligible by both computers and humans. Smart contracts may be more acceptable in legal contexts if they are written in code that both humans and computers can comprehend. This desired attribute has been extensively researched to solve problems about contract semantics, meaning, and interpretation.

Smart contracts must be determined by definition. This characteristic allows any network node to execute a smart contract and obtain the same outcome. If the outcome varies marginally across nodes, then the distributed consensus paradigm on blockchain may fail. The contract language itself should be deterministic to ensure the smart contracts' integrity and stability. The language is deterministic since it has no non-deterministic functions that may yield different outputs on different nodes.

Deterministic smart contracts deliver the same outcome for a given input. That is, when programs are performed, they provide dependable and accurate business logic that meets all criteria defined in high-level code.

A smart contract has four properties:

- Automatically executable
- Immutable
- Enforceable
- Deterministic

- Semantically sound (Optional)
- Unbreakable (Optional)

The first four qualities must be met, whereas the final two may not be needed or feasible in certain cases. For example, a financial derivatives contract should be instantly executable and enforceable at a minimum.


An Introduction to Smart Contract Part 1 - https://dev.to/shlok2740/an-introduction-to-smart-contract-3bai

For more content, follow me on - https://linktr.ee/shlokkumar2303
The never type in typescript
Tags: typescript, never, webdev, tutorial
Published: 2023-01-14 16:09:42

### The never type

The never type is used when you are sure that something is never going to happen. It simply represents a state which shouldn’t exist.

It might be return type of function that never returns. 
```ts

function throwError(errorMsg: string): never { 
    throw new Error(errorMsg); 
}

function loop(): never {
    while(true) {}
}
```
Here, both reportError and loop type function either throw errors or return infinite loop that will be analyzed by TypeScript control flow as functions with unreachable endpoints, thus specifying their return type as never.

**Note** When a function is throw-only, it gets the type never if it's an expression, and void if it's a declaration.

```ts
function foo() { 
    throw new Error("Should never get here");
}
```
here foo is () => void. Read more about it in [StackOverFlow answer](https://stackoverflow.com/questions/40251524/typescript-never-type-inference)

### Exhaustiveness checking

you can use never type for narrowing and turning up to do exhaustive checking in a switch statement.

```ts
type Shape = Circle | Square;
 
function getArea(shape: Shape) {
  switch (shape.kind) {
    case "circle":
      return Math.PI * shape.radius ** 2;
    case "square":
      return shape.sideLength ** 2;
    default:
      const _exhaustiveCheck: never = shape;
      return _exhaustiveCheck;
  }
}
```
Here getArea function which tries to assign the shape to never will raise the issue that every possible case has not been handled.

### Assignability in TypeScript

The never type is assignable to every type; however, no type is assignable to never (except never itself).It can be understood as "the smallest type".

```ts
 // ✨ `never` is assignable to all types.
  // It is a subtype of all types.
  let neverValue: never = getNever();

 
  let numberValue: number = neverValue;  // ✅
  let stringValue: string = neverValue;  // ✅
  let objectValue: object = neverValue;  // ✅
  let unknownValue: unknown = neverValue;  // ✅
  let anyValue: any = neverValue;  // ✅
  let neverValue1: never = neverValue;  // ✅


  neverValue = 1; // ❌
  neverValue = '1'; // ❌
  neverValue = {}; // ❌
  neverValue = anyValue; // ❌
```

### Void Vs Never

The never type looks very similar to void. But the void type can have undefined or null as a value where as never cannot have any value.

```ts
let something: void = null;
let nothing: never = null; // Error: Type 'null' is not assignable to type 'never'
```

### Intersection and Union with never type

In intersection types, it absorbs all types, and in union types all types absorb it. This is because never is a subtype of all types.

```ts
 type anyTypeUnion = never | any; // any
 type anyTypeIntersection = never & any; // never
```

### References

1. -  [Everyday Types](https://www.typescriptlang.org/docs/handbook/2/everyday-types.html)
2. - [Stackoverflow](https://stackoverflow.com/questions/42291811/use-of-never-keyword-in-typescript)
3. - [TypeScript Release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#the-never-type)
A poem written on me - "Lakin: A Coder Extraordinaire" by ChatGPT
Published: 2023-01-14 16:04:44


## Lakin: A Coder Extraordinaire

Lakin, with code as his art,
Crafts lines that flow like a symphony chart.
Hacking, cracking, cyber security,
His hobby and passion, a true rarity.

In Medium, Dev.to, LinkedIn, he writes
Technical articles that enlighten and invite.
With a curious mind and a leader's heart,
He sets out to solve every coding part.

His YouTube channel now shines bright
Showing his skills with code that's right.
Lakin, a master of his craft,
Guiding others, his passion will last.

With each line of code, he creates magic
Making the impossible, now quite tragic.
Lakin, a coder extraordinaire
We stand in awe, and stop to stare.

So here's to Lakin, and his coding ways
May his passion for it, always stay ablaze.
Leading the future, with code as his guide,
In the world of technology, he'll forever reside.
CodePen Designs - 20 : NightLight
Tags: codepen, css, design, webdev
Published: 2023-01-14 15:52:56

### We are excited to introduce our new series that will explore the best design ideas from the Codepen community. 

We will be publishing these each day and hope you find them insightful and inspiring as we showcase some of the most talented designers in this space.

---


#### Codepen Design - 20

---

{% codepen https://codepen.io/prisoner849/pen/VwBPEJO %}


---
## For more information

1. Check my GitHub profile
[https://github.com/amitSharma7741](https://github.com/amitSharma7741)

2. Check out my Fiver profile if you need any freelancing work
[https://www.fiverr.com/amit_sharma77](https://www.fiverr.com/amit_sharma77)

3. Check out my Instagram
[https://www.instagram.com/fromgoodthings/](https://www.instagram.com/fromgoodthings/)

4. Linktree
[https://linktr.ee/jonSnow77](https://linktr.ee/jonSnow77)

5. Check my project

- EVSTART: Electric Vehicle is the Future
[https://evstart.netlify.app/](https://evstart.netlify.app/)
-  News Website in react
 [https://newsmon.netlify.app/](https://newsmon.netlify.app/)
-  Hindi jokes API
 [https://hindi-jokes-api.onrender.com/](https://hindi-jokes-api.onrender.com/)


---
---
Let's built an image generator using openai Dall-e and flask python
Tags: python, programming, openai, ai
Published: 2023-01-14 15:45:16

In this article, I will show you how to use the OpenAI Image Generator in a web application built with the Flask framework. The OpenAI Image Generator is a deep learning model that can generate images from text prompts, making it a powerful tool for creating custom images for various purposes such as website backgrounds, illustrations, or even creating data sets for machine learning.

The first step is to install the necessary libraries. You will need to install Flask, the web framework we will be using to build the application and openai, the python library that provides access to the OpenAI API. You can install them by running the following command:

```
pip install flask openai
```

Next, you will need to create a new Flask application and define a route for it. The following code sets up a basic Flask application and defines a single route that generates an image when accessed.

```
from flask import Flask, render_template
import openai

app = Flask(__name__)

# Authenticate with the OpenAI API
openai.api_key = "Your_openai_api_key" #get them here https://beta.openai.com/account/api-keys

@app.route('/')
def generate_image():
    # Specify the image prompt
    prompt = "cat swimming in a river"

    # Generate the image
    response = openai.Image.create(prompt=prompt, n=1, size="256x256")

    # Get the URL of the generated image
    image_url = response['data'][0]['url']

    return render_template('image.html', image_url=image_url)

if __name__ == '__main__':
    app.run(debug=True)

```
The first step is to authenticate with the OpenAI API by setting the api_key. This is a unique key that is generated when you create an account on the OpenAI website. The @app.route('/') decorator is used to define the default route for the web application. When this route is accessed, the generate_image() function is called.

This function first specifies the image prompt, which is a text description of the image that the model should generate. In this example, the prompt is "cat swimming in a river". The openai.Image.create() method is then called, passing in the prompt and other parameters such as n and size. The n parameter specifies the number of images to generate and the size parameter specifies the size of the generated images.

The response from the API is a JSON object that contains the URL of the generated image. The image_url is extracted from the response and passed to the render_template() function. This function renders the image.html template and passes the image_url to it.

The image.html template is a simple HTML file that displays the generated image using an img tag. The src attribute of the tag is set to the image_url, so the browser will load the image from that URL.

```
<!DOCTYPE html>
<html>
  <head>
    <title>Generated Image</title>
  </head>
  <body>
    <img src="{{ image_url }}" alt="Generated Image" />
  </body>
</html>

```
Online Jobs for Undocumented Immigrants
Published: 2023-01-14 15:26:46

Finding a job can be challenging for anyone, but it can be especially difficult for [undocumented immigrants](https://www.askpeek.com/2023/01/05/online-jobs-for-undocumented-immigrants/). However, with the rise of online jobs, there are now more opportunities than ever for undocumented immigrants to earn a living. Here are some online jobs that are available to undocumented immigrants:

Virtual Assistant - Virtual assistants provide administrative support to businesses and entrepreneurs remotely. They can perform tasks such as scheduling appointments, managing email, and conducting research. Virtual assistant jobs often do not require a traditional resume, and many are willing to hire undocumented immigrants.

Data Entry Clerk - Data entry clerks work remotely to input information into databases. They can work with a variety of types of data, including financial information, customer records, and inventory lists. Many data entry jobs do not require prior experience, making them a great option for undocumented immigrants.

Online Tutor - Tutoring jobs are an excellent option for undocumented immigrants who have a subject matter expertise. Many online tutoring jobs do not require a traditional resume and can be done from the comfort of one's own home.

Customer Service Representative - Many companies are now offering remote customer service positions. These jobs involve assisting customers over the phone or via chat. Undocumented immigrants with strong language skills may be well-suited for these jobs as many companies are looking for bilingual customer service representatives.

Online Freelancer - Online freelancing platforms such as Upwork and Fiverr allow individuals to offer their services to clients worldwide. Undocumented immigrants can use these platforms to find work as writers, graphic designers, web developers, and more.

It's important to note that while these jobs may not require traditional documentation, they may still require a valid ID number and/or social security number to get paid, so it's important to check with the employer before applying. Furthermore, it's important to be aware of the laws and regulations in your area regarding employment for undocumented immigrants, as laws and regulations may vary depending on the jurisdiction.

In conclusion, the rise of online jobs has created new opportunities for undocumented immigrants to earn a living. By considering the options above and being aware of the laws and regulations in your area, you can find a job that fits your skills and interests.
Fun Remote Jobs that Pay Well
Published: 2023-01-14 15:23:55

Are you tired of the daily commute and looking for a change in your career? Remote jobs offer the flexibility and freedom to work from anywhere, and there are many fun and high-paying options available. Here are some [fun remote jobs that pay well](https://www.askpeek.com/2023/01/11/fun-remote-jobs-that-pay-well/):

Virtual Event Planner - With the rise of remote work and virtual events, the demand for virtual event planners has increased. These professionals plan, organize, and execute virtual events such as webinars, conferences, and trade shows. The average salary for a virtual event planner is $60,000 per year.

Online Tutor - If you have a passion for teaching and a subject matter expertise, becoming an online tutor may be a great fit for you. Online tutors work remotely to provide one-on-one or group instruction to students via video conferencing. The average salary for an online tutor is $40,000 per year.

Social Media Manager - Social media managers are responsible for creating and managing a company's social media presence. This includes creating content, engaging with followers, and analyzing the success of social media campaigns. The average salary for a social media manager is $50,000 per year.

Travel Agent - As a travel agent, you can work from anywhere and help people plan their dream vacations. Travel agents have access to exclusive deals and can help clients save money on flights, hotels, and rental cars. The average salary for a travel agent is $40,000 per year.

Graphic Designer - Graphic designers use design software to create visual concepts for websites, brochures, and other materials. They work remotely with clients to create designs that are both visually appealing and effective in conveying a message. The average salary for a graphic designer is $50,000 per year.

These are just a few examples of fun and high-paying remote jobs available. With the growing demand for remote work, there are many opportunities to find a career that aligns with your interests and skills.