teleren/devto huggingface dataset:
DAY 52 - Peak Index in a Mountain Array
Tags: leetcode, cpp, algorithms, tutorial
Published: 2023-07-25 17:50:12



## Question:

_An array arr a mountain if the following properties hold:_

`arr.length >= 3`
_There exists some_ `i` _with_ `0 < i < arr.length - 1` _such that:_
`arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` 
`arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`
_Given a mountain array_ `arr`, _return the index_ `i` _such that _`arr[0] < arr[1] < ... < arr[i - 1] < arr[i] > arr[i + 1] > ... > arr[arr.length - 1]`.

_You must solve it in_ `O(log(arr.length))` _time complexity._

---

**_Example 1:_**

> **Input:** arr = [0,1,0]
> **Output:** 1

**_Example 2:_**

> **Input:** arr = [1,2,3,2,1]
> **Output:** 2

---



## Intuition:

- Let's start with breaking down the question.
- Basically we are given an array which contains two parts inside an array.
- One which is in strictly increasing order and after that one which is strictly in decreasing order.
- _Example:_ `{1,2,3,4,5,4,3,2,1}`
- Now it's obvious that there will be an element which separates those two sections is 5.
- Here we need to find that element's index.

- We can look this as two arrays who are sorted, one in increasing order and one in decreasing order.
- We can use binary search that is applicable on sorted arrays to find our element.
- Refer to algorithm for more understanding.


---

## Algorithm: Binary Search

### Initializing variables:
- We need two variables start and end which refer to our starting and ending points in a binary search.
- MID of an array is nothing but (start + end )/2.

### Traversion:
- We then traverse the array and find the middle each time our loop runs.
- If the element we are currently at is less than the element it's next , it means we are in the left section(strictly increasing section) of our array and need to go ahead.
So we jump our start  to `mid+1`.
- If it's not greater , it consequently means we are in the right section of our array and need to shift our end back to the mid element.
- When we are not able to traverse anymore that's when our start and end have reached an element that satisfies neither of the if conditions.

- Hence we return our answer which is the element start is pointing to.

---

## Code:

```
class Solution {
public:
    int peakIndexInMountainArray(vector<int>& arr) {
        int start = 0;
        int end = arr.size() -1;
        
        while (start < end){
            int mid = start + (end-start)/2;
            if (arr[mid] < arr[mid+1]){
                start = mid +1;
            }
            else{
                end = mid;
            }
            

        }
        return start;
    }
};
```

### Complexity Analysis:

> **_Time:_** O(logN)
> **_Space:_** O(1)
Iframe document write doesn't update JavaScript
Tags: javascript, html, iframe
Published: 2023-07-25 17:39:36

Here's a basic HTML editor:

## CSS

```
textarea,
iframe {
  width: 400px;
  height: 300px;
}
```

## HTML

```
<textarea></textarea>
<iframe></iframe>
```

## JavaScript

```
var textarea = document.querySelector('textarea'),
  iframe = document.querySelector('iframe');

function preview() {
  var iframeDoc = iframe.contentDocument;
  iframeDoc.open();
  iframeDoc.write(textarea.value);
  iframeDoc.close();
}

textarea.addEventListener('input', preview);
```

[**DEMO**](https://labground.github.io/iframe-document-write-doesn%27t-update-javascript.html)

It updates the HTML and CSS you put in the `textarea`, but you can’t use JavaScript `const` or `let` variables as it throws the following syntax error as soon as you edit the inserted code:

`Identifier * has already been declared`

To see what I mean, insert the following sample code in the `textarea`:

```
<!doctype html>
<html lang="en">
<head>
  <title>Sample Code</title>
</head>
<body>
  <p>Hello!</p>
  <script>
    const p = document.querySelector('p');
    p.style.color = 'blue';
  </script>
</body>
</html>
```
Now change `Hello!` to `Hello, world!`, or `blue` to `red`.

What’s the solution so the user can keep editing the code without getting that error?
My Journey with the OpenAI API
Published: 2023-07-25 17:38:44

A few months ago I had the chance to speak to my sister's class of eighth graders about AI — which made this talk for adults at Philly Tech Week much better. If you need an overview that gets really basic before digging into how you can integrate it yourself, I think I can help. Thanks to Apostrophe for supporting my work on this and to Philly Tech Week for having me!

{% embed https://www.youtube.com/watch?v=nQor7L3HPlI %}
Valibot: JavaScript Schema Validator
Tags: javascript
Published: 2023-07-25 17:31:27


---
title: Valibot: JavaScript Schema Validator 
published: true
description: If you like JavaScript&#8217;s Zod to validate your types at runtime, you&#8217;ll Valibot. Like Zod, however, you can also use it with TypeScript to get compiler help. Their current claim to fame is the Lodash style of &#8220;1 function per file&#8221; which makes it easier for bundlers to shrink the code down super small. https://www.builder.io/blog/introducing-valibot
tags: JavaScript
canonical_url: https://jessewarden.com/2023/07/valibot-javascript-schema-validator.html
cover_image: 
---

If you like JavaScript’s [Zod](https://zod.dev/) to validate your types at runtime, you’ll [Valibot](https://www.builder.io/blog/introduci). Like Zod, however, you can also use it with TypeScript to get compiler help. Their current claim to fame is the Lodash style of “1 function per file” which makes it easier for bundlers to shrink the code down super small.

<https://www.builder.io/blog/introducing-valibot>
How to check if there are changes in your formik form
Tags: react, formik
Published: 2023-07-25 17:30:44

## Introduction
Sometimes, when you are building a form using formik, you need to know if there has been a change in any of the fields to execute an action, in my case for example to enable or disable the save button. Many tutorials suggest to compare the `initialValues` object with current `values` object using `lodash` or comparing field by field.

But there is a property in formik called `dirty` that saves you all that work and tells you if there was a change in your form, according to the formik documentation:

_`dirty` property returns `true` if values are not deeply equal from initial values, `false` otherwise. `dirty` is a readonly computed property and should not be mutated directly_ 

## Implementation
We create a very simple form with two fields and a sumbit button because we will focus only in the `dirty` property, in this we assign initial values to our form supposing that it is an edit form and we want to enable the submit button only when there is a change in some input, in the example we are receiving the `dirty` property whose initial value is false and we use it to disable the submit button, in case there are changes the value of the `dirty` property will be true, and when denying it the value of the disabled property will be false, therefore the submit button will be enabled.

```
import React from 'react';
import { Formik, Form, Field } from 'formik';
import * as Yup from 'yup';

const initialValues = {
  name: 'John Doe',
  email: 'john.doe@example.com'
};

const SimpleForm = () => (
  <div>
    <Formik
      initialValues={initialValues}
      // Here you can handle the logic to send the data
      onSubmit={(values) => {}}
    >
      {({ values, handleChange, dirty }) => (
        <Form>
          <div>
            <Field type="text" id="name" name="name" placeholder="name" value={values.name} onChange={handleChange} />
          </div>
          <div>
            <Field type="text" id="email" name="email" placeholder="email" value={values.email} onChange={handleChange} />
          </div>
          <button type="submit" disabled={!dirty}>
            Save
          </button>
        </Form>
      )}
    </Formik>
  </div>
);

export default SimpleForm;
```

## Conclusion
Using the dirty property you can save a lot of time comparing value by value in formik forms, especially if they are large forms and you only need to know if there was any change in some input no matter what it was.
Importance of Multi-Factor Authentication in Cybersecurity
Tags: cybersecurity, digitalprivacy, career
Published: 2023-07-25 17:26:15

Implementing strong security measures is essential in the modern digital environment where cyber threats are becoming more sophisticated in order to safeguard sensitive data and guard against unauthorized access.** Multi-Factor Authentication (MFA)** is one of the best defenses against cyberattacks. The traditional username-password login process is made more secure by MFA, which asks users for several forms of identification before granting access to their accounts or systems.

MFA typically combines two or more of the following elements: something you are (biometric data like a fingerprint or facial recognition), something you have (a physical object like a smartphone or smart card), and something you know (a password or PIN). By incorporating these additional elements, MFA significantly enhances security, as even if one factor is compromised, the cybercriminal would still need to bypass the other factors to gain access.

To equip yourself with the necessary knowledge and skills for a successful career in cybersecurity, enrolling in a comprehensive [cybersecurity course](https://prerogative.in/courses/cyber-security-course-certification/) is highly recommended. Such courses cover various topics, including network security, ethical hacking, cryptography, incident response, and more. By staying updated with the latest threats, vulnerabilities, and defense mechanisms, individuals can effectively contribute to the ever-evolving landscape of cybersecurity and play a vital role in securing digital environments against cyberattacks.
Fix VS Code Explorer for Content Projects
Tags: vscode, coding, productivity, webdev
Published: 2023-07-25 16:48:23

The [VS Code explorer][] displays folders at the top of a directory.
This is a common hierarchy that I like in _most_ cases.

**But I hate it for content.**

For content sites — like [chan.dev][] — I prefer alphabetical order.
I want to see my files and folders all _mixed_ up together.

![Screenshot of the Visual Studio Code Explorer, showing several markdown posts. With `explorer.sortOrder: mixed`, a directory of the same name as a post appears next to a post with the same name.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wjt86nho0oz6mk391tt3.png)

## How to change the setting

To change the default behavior, open Settings and find the option for `Explorer: Sort Order`.

![Screenshot of VS Code Settings, for the option Explorer: Sort Order. Selected is the `mixed` option.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqa22p6ero83idnwwzbq.png)

With this option enabled, files and folders are interwoven in the explorer.

## Why I prefer mixed sort order

On [chan.dev][], I have lots of markdown files.
Some of them have images.
And I want to keep those images in a folder nearby.
I ain't tryna faff with Cloudinary or hunt down shared `/assets/images` folder.
_I want them right next to my post._

This makes it easy to keep my place on the file system.

## Take it further with workspaces

As mentioned, I prefer the default sort order for most projects.
So, I keep this setting stored in my [chan.dev][] [workspace][].
And only _this_ project is impacted by the setting.

```json
// chan.dev/.vscode/settings.json
{
  "explorer.sortOrder": "mixed"
}
```

[chan.dev]: https://chan.dev/ "The irrational home web home of chantastic"
[workspace]: https://code.visualstudio.com/docs/editor/workspaces 'What is a VS Code "workspace"?'
[VS Code explorer]: https://code.visualstudio.com/docs/getstarted/userinterface#_explorer

{% youtube https://www.youtube.com/embed/RvYvyzsnFm8 %}
D2 #100daysofOSS
Tags: 100daysofcode, 100daysofoss, opensource, programming
Published: 2023-07-25 16:33:27

D2 #100daysofOSS with @saucedopen
 
Today, I Dove deep into #ConventionalCommits 📘 - a game-changer for clear commit messages. Spent quality time exploring #DataWarehousing & sharpening my #SQL skills 🔧. Also made meaningful contributions on GitHub!

#100DaysOfCode #opensauced
What’s New in Go 1.21 a Comprehensive Notes
Tags: go, programming, webdev, opensource
Published: 2023-07-25 16:27:38

The Go programming language has released its first Release Candidate (RC) for version 1.21, which is packed with new features, improvements, and performance enhancements. This article provides an overview of the notable changes and features in Go 1.21, along with some exciting additions to the standard library.

[Continue Reading](https://younisjad.medium.com/whats-new-in-go-1-21-a-comprehensive-notes-96017750b390)
Aprendiendo y desaprendiendo
Tags: writing, spanish
Published: 2023-07-25 16:27:35

A veces me siento un poco frustrado porque no tengo una ultra especialización en una tecnología. Tengo lenguajes de programación que llevo años utilizando (PHP y Java) y algunos nuevos que estoy aprendiendo (JavaScript, Kotlin, Python) pero en esto de las TI la ultra especialización es la ruta a seguir, por que digo tiene cierta parte de sentido. Si yo fuera un cliente yo quisiera tener en mi equipo alguien que sé que me va a resolver los problemas, y no va andar dando vueltas hasta que resuelve el problema irremediablemente pero tal vez en el doble o triple de tiempo.

Siempre he sido una persona muy curiosa y me gusta estar aprendiendo constantemente. He participado en muchos proyectos unos han salido bien y otros tremendamente mal, he aprendido muchas cosas y de muchas personas y siento que la gran mayoría de esa experiencia se complementa en un momento.

Siguiendo las buenas practicas de indentación se vuelve relativamente rápido la adopción de por ejemplo Python, vas a poder hacer bien los archivos de configuración yaml de Docker. Entender el flujo de un programa te permite trackear un problema por ejemplo en un servidor viendo directamente los logs.

En este mundillo también he aprendido muchas veces por la mala que tu ego te juega malas pasadas, entre mas aprendo de herramientas, tecnologías y demás, te das cuenta que menos sabes y esto no es malo sino que la gran mayoría de las veces vas a tener que desaprender y reinventarte. Nuestro trabajo es altamente demandado pero también con grandes cargas de estrés. Yo siempre he dicho la cantidad de dinero que ingresa a tus bolsillos es inversamente proporcional a la cantidad de estrés que debes de manejar y cargar.

La mejor forma de acortar la curva de aprendizaje de ciertos temas es encontrando y pagando por ese conocimiento, si eres un profesional de las TI y no ves tu educación constante como una inversión te vas a quedar atrás y va ser muy complicado que vuelvas a retomar el ritmo porque esto es muy vertiginoso.

La gran mayoría del tiempo te vas a sentir muy pipiolo y es completamente normal hay que saber navegar a través de la incertidumbre, que stack elegir, que servidor elegir, será bueno cambiar de lenguaje ahora o mejor cuando este este en un etapa mas madura, etc.
Install PostgreSQL 12 on Ubuntu 22.04
Tags: apacheage, postgressql, ubuntu
Published: 2023-07-25 16:22:47

This blog will walk you through the process of installing PostgreSQL 12 on an Ubuntu 22.04. PostgreSQL is one of the most extensively used object-relational database management systems. PostgreSQL 12 has been made available for general use and is suitable for all production and development use cases.

Visit the [PostgreSQL 12 release notes](https://www.postgresql.org/about/news/postgresql-12-released-1976/) page to see all the new features and improvements in PostgreSQL 12 and to review the most significant updates. Let's jump right into installing PostgreSQL 12 on Ubuntu without further ado.


## Step 1: Update System

If it's a fresh server instance, it's advised to upgrade your current system packages.
`sudo apt update
sudo apt -y install vim bash-completion wget
sudo apt -y upgrade
`
After an upgrade, you must reboot.
`sudo reboot`


## Step 2: Add PostgreSQL 12 Repository

We must add the PostgreSQL 12 repository to our Ubuntu computer and import the GPG key. To do this, enter the commands below.
`curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc|sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/postgresql.gpg`

Add repository contents to your Ubuntu 22.04 system after importing the GPG key:
`echo "deb http://apt.postgresql.org/pub/repos/apt/ `lsb_release -cs`-pgdg main" |sudo tee  /etc/apt/sources.list.d/pgdg.list`

The newly added repository includes a variety of packages, including add-ons from third parties.


## Step 3: Install PostgreSQL 12 on Ubuntu

Update the package list and install the PostgreSQL server and client packages on your Ubuntu 22.04 Linux system after successfully adding the repository.

`sudo apt update
sudo apt -y install postgresql-12 postgresql-client-12
`
A message similar to the one seen in the following screenshot indicates that the installation was successful.

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

You can check PostgreSQL status using the following command:

`systemctl status postgresql.service`

To set come up after every system reboot using the following command:

`systemctl status postgresql@12-main.service`
firstDuplicate. Given a string which might have duplicate letters, write a function to find the first duplicate.
Tags: javascript, programming, beginners, interview
Published: 2023-07-25 16:19:32


Good morning! Here's your coding interview problem for today.

## This problem was asked by Apple.

**Given a string which might have duplicate letters, write a function to find the first duplicate.**

```
Example
function firstDuplicate(str) {

}

console.log(firstDuplicate('abca')) // 'a'
console.log(firstDuplicate('abcdefe')) // 'e'
console.log(firstDuplicate('abcdef')) // null
```
**Notes: What is the time & space cost of your approach ?**

**Solution**

```
function firstDuplicate(str) {
  let chars = {};
  
  for (let char of str) {
    if (chars[char]) {
      return char;
    }
    
    chars[char] = true; 
  }
  
  return null;
}
```

**Explanation**

- Use an object (chars) to keep track of characters we've seen
- Loop through each character in the input string
- If we've seen the character before (exists in chars), return immediately
- Otherwise, add the character to chars as a key
- Return null if no duplicate is found


This runs in O(n) time and O(n) space. By short-circuiting and returning when we find the first duplicate, we avoid looping through the entire input when not needed.
ADD EVENT LISTENER IN JavaScript
Tags: javascript, programming, frontend, backend
Published: 2023-07-25 16:17:05

Here's an example of how to add an event listener in JavaScript:

Suppose you have an HTML button with the ID "myButton," and you want to add a click event listener to it. When the button is clicked, an alert will display a message.

**HTML**:
```html
<button id="myButton">Click Me</button>
```

**JavaScript**:
```javascript
// _Get a reference to the button element by its ID_
const myButton = document.getElementById("myButton");

// _Add a click event listener to the button_
myButton.addEventListener("click", function() {
  // _Code to be executed when the button is clicked_
  alert("Button clicked!");
});
```

In this example, when you click the "Click Me" button, the event listener function will be executed, and it will display an alert with the message "Button clicked!".

You can similarly add event listeners to other HTML elements and for various events like "mouseover," "keydown," "change," etc. Just replace "click" with the appropriate event type you want to listen for.
Do you balance High-Tech with Low-Tech?
Tags: discuss, productivity, career, motivation
Published: 2023-07-25 16:15:00

Technology today is an immersive experience, and as professionals in the space we tend to be above average in terms of our adoption and interconnectivity.  Today we have an app for nearly every idea imaginable, providing significantly more value-add to our daily lives than the generations that preceded us.  Technology however can be a double-edged sword, and the potential value-add and ease of access to so many options can lead to behaviors detrimental to our well-being.  Doom-scrolling is a solid example of this, where apps have created such a focus on retaining attention that we spend an unhealthy amount of time glued to our screens.  

In the early 2010s, I had come to this realization as I learned from the successes (and many, many failures) of my 20s, and actively began to seek out low/no technology counter-balances to foster healthier long-term personal growth.  

For myself, these counter balances came in a variety of forms over the years, some that come to mind: 
- Note taking using Moleskine notebooks
- Indoor gardening 
- Marathon training

Have you found yourself needing to counter-balance our technology-focused lives with low/no tech? Share your own experience and ways you've created a balanced lifestyle in the comments below ⬇️
68 berufliches Vorwärtskommen: Wie wird man zum Karriere-Weg-Nicht-Helfer?
Tags: deutsch, career, motivation, discuss
Published: 2023-07-25 16:12:00

Moin Moin,

nachdenkend über [den letzten Beitrag→](https://dev.to/amustafa16421/67-berufliches-vorwartskommen-karriere-weg-nicht-helfer-3ced), frage ich mich warum es Leute gibt, die unbedingt nicht helfen wollen. Also bspw. Jugendlichen nicht helfen, die entweder ein bestimmtes Netzwerk nicht haben oder die bestimmte Mittel nicht haben.
Was sind deren Beweggründe?

Hatten sie selbst kein Netzwerk?
Haben sie alles selbst finanziert?

Andersherum gibt es so viele Menschen, denen es eine Freude bereitet anderen zu helfen und der Gesellschaft etwas zurückzugeben.


1) Was meinst du woher dies rührt?


Lass uns mittels Kommentaren austauschen.

Beste Grüße,
Mustafa

Oder auch mittels E-Mail: mustafa.kevin.dwenger@posteo.de
Betreff: Austausch