teleren/devto huggingface dataset:
81. Search in Rotated Sorted Array II
Tags: 100daysofcode, java, algorithms, programming
Published: 2022-01-10 11:55:18

# [Description](https://leetcode.com/problems/search-in-rotated-sorted-array-ii/)

There is an integer array `nums` sorted in non-decreasing order (not necessarily with **distinct** values).

Before being passed to your function, `nums` is **rotated** at an unknown pivot index `k` (`0 <= k < nums.length`) such that the resulting array is `[nums[k], nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]]` (**0-indexed**). For example, `[0,1,2,4,4,4,5,6,6,7]` might be rotated at pivot index `5` and become `[4,5,6,6,7,0,1,2,4,4]`.

Given the array `nums` **after** the rotation and an integer `target`, return `true` *if* `target` *is in* `nums`*, or* `false` *if it is not in* `nums`*.*

You must decrease the overall operation steps as much as possible.

## Example 1:

```
Input: nums = [2,5,6,0,0,1,2], target = 0
Output: true
```

## Example 2:

```
Input: nums = [2,5,6,0,0,1,2], target = 3
Output: false
```

## Constraints:

- `1 <= nums.length <= 5000`
- `104 <= nums[i] <= 104`
- `nums` is guaranteed to be rotated at some pivot.
- `104 <= target <= 104`

---

# Solutions

## Solution 1

### Intuition

just get in the sorted part

### Code

```java
class Solution {
    public boolean search(int[] nums, int target) {
        int l = 0, r = nums.length - 1;
        while (l <= r) {
            while (l < r && nums[l] == nums[l + 1]) {
                l++;
            }
            while (l < r && nums[r] == nums[r - 1]) {
                r--;
            }

            int mid = l + r >> 1;
            if (nums[mid] == target) {
                return true;
            }

            if (nums[l] <= nums[mid]) {
                if (nums[l] <= target && target < nums[mid]) {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            } else {
                if (nums[mid] < target && target <= nums[r]) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            }
        }
        return false;
    }
}
```

### Complexity

- Time: O(logn)
- Space: O(1)

---
Hello world in nodeJS
Tags: tutorial, javascript, node, beginners
Published: 2022-01-10 11:49:15

## Download & Install Node.js
To use node.js, we must first download and install the most recent version from the https://nodejs.org/en URL. When we open the URL, it will automatically determine our operating system and display the appropriate download link, as shown below.

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

We can test that node.js is installed correctly on our machine by entering node -v at the command prompt. If node.js was successfully installed, it will display the version of node.js on our machine. To do so, open a command prompt and run the command ```node -v```.

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

Once we made sure node is installed we will use npm to create our first node project, 
First, let’s create our project directory, open the folder in vscode and run the command `npm init` in the terminal as follows 

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

we can leave everything as default and your directory should look something like this

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

The express package will be used to create our first REST resource. Express is your most dependable friend in Node.js. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. 

To install it type `npm install --save express` or `npm i --save express`, where 'i' is short for install

This is what our index.js file should look like.

 `  var express = require('express');
   var app = express();`

`  app.get('/', function (req, res) {
    res.send('Hello World!');
  });`
  `app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
  });`
So let me explain the code we just wrote 

The first line declares a variable that will hold the express module, which is retrieved from the node modules folder. 

In reality, the module is a function. By assigning the function call to a different variable, you have access to a predetermined set of tools that will greatly simplify your life. You may think of the variable app as an object whose methods you're using to create the program.

The listen method establishes a server and listens for connections on port 3000.

For get requests to the root URL (/), it answers with "Hello World!" It will return a 404 Not Found response for all other paths.

Now we just run the app by typing `node index.js` and there you have it ! use the tools of your choice to test it you can either use postman or simply your web navigator 

Using postman type the url 127.0.0.1:3000/ and here's what you'll get

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

The response code is 200 OK and the response body is 'hello world!'
Integración de Tawk.to con GatsbyJs
Tags: gatsby, react, chat, tawkto
Published: 2022-01-10 11:40:02

Esta semana me asignaron la tarea de integrar [Tawk.to](tawk.to), un live chat (Gratis) para conectar con posibles clientes en tiempo real.

La comunidad de Gatsby es muy grande y al buscar en su lista de plugins encontré gatsby-plugin-tawk pero desafortunadamente en la actualidad no funciona.

Así que buscando encontré una forma de agregarlo bastante simple.

Lo primero que debemos hacer es ir tawk.to y crear tu widget.

Luego ir a gatsby-browser.js y utilizar una de sus APIs [onInitialClientRender](https://www.gatsbyjs.com/docs/reference/config-files/gatsby-browser/#onInitialClientRender). Si no tienes este archivo puedes crearlo en tu directorio base.

Agregamos el siguiente código: 


```
export const onInitialClientRender = () => {}
```


y dentro del mismo agregamos nuestro código del widget que nos suministra tawk.to de la siguiente forma, eliminando el tag script y los comments.

```
export const onInitialClientRender = () => {
  var Tawk_API=Tawk_API||{}, Tawk_LoadStart=new Date();
  (function(){
  var s1=document.createElement("script"),s0=document.getElementsByTagName("script")[0];
  s1.async=true;
  s1.src='https://embed.tawk.to/{TU-KEY}/{TU-ID}';
  s1.charset='UTF-8';
  s1.setAttribute('crossorigin','*');
  s0.parentNode.insertBefore(s1,s0);
  })();
  }
```

`gatsby develop` y listo!

Con eso te debería de funcionar correctamente.
Portal to submit hackathon entry 
Tags: atlashackathon
Published: 2022-01-10 08:18:13

[Instructions]: # (To submit to the MongoDB Atlas Hackathon on DEV, please fill out all sections.)


### Overview of My Submission
🎊A portal to showcase MongoDB hackathon projects.


### Submission Category:📢 

Choose Your own adventure


### Link to Code✨

{% github larsonjack05/atlashackathon-project %}


[Source Code](https://github.com/larsonjack05/atlashackathon-project
)

### Additional Resources / Info📙
Expressjs as server
I used google authentication for login functionality and MongoDB for storing user posts.
Multer for form processing.
Passportjs and session for user user authentication.
#Video 🎥
YouTube: {% youtube wKdpuagfhNs%}

[Note]: # (Be sure to include the DEV usernames of your collaborators, if any. Prizes for winning projects with multiple collaborators will be sent to the person who posts this submission and they will distribute the prize evenly.)
PM PT/2 AM ET on January 14th, 2022/6 AM UTC on January 14th, 2022).
Incremental Static Regeneration (ISR) com Nextjs
Tags: nextjs, node, react, javascript
Published: 2022-01-10 11:34:17

## Static-Site Generation

A ideia principal deste conceito é a geração de páginas estáticas durante o tempo de build. Essas páginas podem ser enviadas para uma CDN e disponibilizadas globalmente em poucos segundos. Como nem tudo são flores, temos um probleminha. Vamos imaginar um e-commerce com 10000 produtos e para cada produtos temos que gerar uma página estática. Se essas páginas são geradas no build da aplicação, vamos ter um atraso considerável até que todas as páginas estejam prontas. Sendo assim, quanto mais páginas eu tenho que gerar de forma estática maior será o tempo de build.


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

O problema com a geração de sites estáticos: como o tempo de construção aumentam linearmente com o número de páginas, você pode ficar preso por horas até que seu site seja construído.

Mesmo que cada página fosse gerada estaticamente em torno de 1 ms, ainda levaria horas para reconstruir todo o site. Para grandes aplicações da web, escolher a geração completa de sites estáticos não é o primeiro passo. As equipes em grande escala precisam de uma solução híbrida mais flexível e personalizada.

Veja o post completo neste link: https://andersonnsilva.site/post/incremental-static-regeneration-isr-com-nextjs
namespace ra :: Random Prime No. Generator
Tags: cpp, opensource, showdev, tutorial
Published: 2022-01-10 09:56:23

### Aim: 
To create a random number engine that generates prime number on the go! Here the link [GitHub](https://github.com/ra101/Random-Prime-Number-Generator-Engine-cpp) repo


### Plan of Attack:
- Since finding prime number in constant time is impossible by the math at the moment, So We are going to use a database-based approach. Lets store all the prime number in `primeDB` file
- Since `C++` already have [random engines](https://en.cppreference.com/w/cpp/numeric/random), Let us create a wrapper around that using [templates](https://en.cppreference.com/w/cpp/language/templates)

### Objective:
- [Container](https://en.cppreference.com/w/cpp/container) that takes in engine class and override all the engine functions, also takes in filepath for database
- Functions to override
  -  `()` -> returns random prime number
  -  `min()` -> returns min prime number
  -  `max()` -> returns max prime number
  -  `<<` -> save the state to `std::stringstream`
  -  `>>` -> restores the state from `std::stringstream`

### Code:

- Private Members:
 - `template <typename Engine> Engine eng;`
 - `int min_prime;`
 - `int max_prime;`
 - `char const *db_filepath;`


- Public Members:
 - `Constructor`
 - `int operator()();`
 - `friend stringstream &operator<<`
 - `friend stringstream &operator>>`

#### Constructor: takes in `seed` and `filepath`

```C++
#define DB_FILEPATH "primeDB"

template <typename Engine>
random_prime_engine<Engine>::random_prime_engine(unsigned long rand_seed, char const *db_filepath=DB_FILEPATH)
{
    // Get DB path
    this->db_filepath = db_filepath;
    eng.seed(rand_seed);
}
```
```C++
// Usage

ra::random_prime_engine<std::default_random_engine> rpe_2(rand_seed);
```
<br>
<br>
#### `()` operator,
```C++
#define DB_SIZE 10000

template <typename Engine>
int random_prime_engine<Engine>::operator()()
{
    int idx = eng() % DB_SIZE; // to get a index within file
    int rand_prime;

    // Open the file
    std::ifstream file;
    file.open(db_filepath);

    // update rand_prime till it gets the value at index
    for (int i = 0; i <= idx; i++)
        file >> rand_prime;

    file.close();
    return (rand_prime);
}
```
```C++
// Usage

std::cout << rpe()
```
<br>
<br>
#### `min` and `max`
```python
# pseudo code
# initialize min/max with 0, for lazy initialization

{
    # return min or max if once found
    if bool(min/max):
        return min/max

    min = file.first_line
    max = file.last_line

    return min/max
}
```
<br>
<br>
#### `>>` and `<<`
```C++
// Friend Functions
#define stringstream SS
function SS &operator<>(SS&in/out, rpe){
    in/out >> rpe.eng;
    return in/out
}
```
```C++
// Usage

std::stringstream state;
state << rpe; //save current state
state >> rpe; //restore old state
```

All the code can be found at the below link:
https://github.com/ra101/Random-Prime-Number-Generator-Engine-cpp
My 2nd Project | Day 7
Tags: webdev, programming, react, javascript
Published: 2022-01-10 11:06:27

**So I have made a Dice Game** 👇


![React Project](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kbir71si8e9i6np4j2n1.GIF)

It have 3 Compnent

**App**                             

   **Rolldice**

  **Die**

**Die Component Consists of a Die which is rendered on the type of props passed.**

**In the Rolldice Component we Have 2 Die and a Button.**

Whenever we click the button it will call a Function that Randomly give the value and change the values of state and then I pass the state as a props in the Die Component.

**Code link** 👇

https://github.com/Developer-io-web/Dice-Excercise

### Things learnt by Doing This Project →

1. **How to use the Font-awesome Icons in your React Project** 
    
      **To start using them we 1st have to install some packages.**
    
    ```jsx
    npm i --save @fortawesome/fontawesome-svg-core
    npm install --save @fortawesome/free-solid-svg-icons
    npm install --save @fortawesome/react-fontawesome
    ```
    
    **Then u have to Import them into each `Component`.**
    
    ```jsx
    import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
    import { <icon-name> } from '@fortawesome/free-solid-svg-icons'
    import { <icon-name> } from '@fortawesome/free-brands-svg-icons'
    ```
    
    **U can use them like this** 👇
    
    ```jsx
    <FontAwesomeIcon icon="<icon-name>" />
    ```
    
2. **Method which calls the function after a particular  time.**
    1. **`setTimeout`: calls a function once after a particularized delay.**
    2. **`setInterval`: calls a function repeatedly, beginning after some time, then repeating continuously at the given interval.**
    
    **I actually know about them earlier but doesn’t know the difference about them.**
    
    **Syntax:**
    
    `**SetTimeout**`
    
    ```jsx
    setTimeout(()=>{
    	console.log('Repeat once after  1 second.')
    },1000);
    ```
    
    **`setInterval`**
    
    ```jsx
    setInterval(()=>{
    	console.log('Repeat after every one minute');
    },)
    ```
CSS Reset
Tags: css, tutorial
Published: 2022-01-10 11:00:10

Hey **fellow creators**

A *CSS reset* is a nice way to start from a blank canvas in HTML/CSS and in web development in general, because some HTML elements have default values to their properties.
 
If you prefer to watch the video **version**, it's right here :

{%youtube kCp-jIS1yS4%}

##1. The short reset I use in most of my videos and tutorials.

Here’s the code you can add to your CSS style that will remove all of the margin and padding:
```css
*, ::before, ::after {
	box-sizing: border-box;
	margin: 0;
	padding: 0;
}

```
It will also take into account the padding and the borders when calculating the height and the width of an element thanks to the "border-box" value.
&nbsp;

##2. But there’s another option!
If you want a more complete CSS reset, you can simply google *Reset CSS* and you’ll find the famous "mayer CSS reset" : https://meyerweb.com/eric/tools/css/reset/

It's a very popular way to reset the value of a lot of property when starting a new project.
Here it is :
```css
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}
```
&nbsp;
This will allow you to have a nice and clean canvas to work from!
There are a lot of different CSS resets and you can literraly build your own if you have some preferences.

&nbsp;
Come and take a look at my **Youtube channel**: https://www.youtube.com/c/TheWebSchool

*See you soon!*

Enzo.
clay.css - micro CSS util for creating claymorphic UI
Tags: webdev, css, html, productivity
Published: 2022-01-10 10:55:33

# clay.css

Extensible and configurable micro CSS util class and SASS mixin for adding claymorphism styles to your components.

Check out the [repository](https://github.com/codeAdrian/clay.css) and the [demo page](https://codeadrian.github.io/clay.css/)

![](https://raw.githubusercontent.com/codeAdrian/clay.css/gh-pages/assets/social.jpg)

## About

Claymorphism is a fresh new concept. The name was coined by [Michał Malewicz](https://hype4.academy/articles/design/claymorphism-in-user-interfaces) and the designers are excited to explore the possibilities of this approach to UI design.

It features inflated fluffy 3D elements which look charming and introduce a much more vibrant look compared to the usual flat designs.

What sets claymorphism apart from neumorphism is that it floats above the background instead of being connected to it, eliminating accessibility issues and design restrictions of the latter.

## Installation
### CDN

```
<link
  rel="stylesheet"
  href="https://unpkg.com/claymorphism-css/dist/clay.css"
/>
```

### NPM

```
npm i claymorphism-css
```

```
yarn add claymorphism-css
```

### Manual

Download and add the `dist/clay.css` or `dist/clay.scss` manually.

## Usage

This is a minimal, single class CSS util that applies only basic claymorphism styles:
* Background
* Border radius
* One outset shadow
* Two inset shadows

```html
<div class="clay">
  Fluffy ipsum dolor sit amet consectetur...
</div>
```

![](https://raw.githubusercontent.com/codeAdrian/clay.css/master/docs/example1.png)

This CSS class allows you to easily change the claymorphic styles via CSS properies. These changes and additional styles should be applied with the extending class.

```html
<div class="clay card">
  Fluffy ipsum dolor sit amet consectetur...
</div>
```

```css
.card{
  /* Modify clay.css properties */
  --clay-background: #f76d6d;
  --clay-border-radius: 48px;

  /* Extended styles */
  color: #f1f1f1;
  padding: 48px;
}
```

![](https://raw.githubusercontent.com/codeAdrian/clay.css/master/docs/example2.png)


## Options (CSS Variables)

```
--clay-background
--clay-border-radius
--clay-shadow-outset
--clay-shadow-inset-primary
--clay-shadow-inset-secondary
```

![](https://codeadrian.github.io/clay.css/assets/diagram-min.png)

## SASS Mixin

SASS mixin allows you more flexibility in applying claymorphism styles to your components. For example, this way you can easily add styles to pseudo-elements or pseudo-selectors or use the mixin in other SASS mixins or functions.

```
@import "claymorphism-css/dist/clay.scss";

@import @include clay(
  $background: [value],
  $border-radius: [value],
  $shadow-outset: [value],
  $shadow-inset-primary: [value],
  $shadow-inset-secondary: [value]
);
```


## Demo page
Check out the [demo page](https://codeadrian.github.io/clay.css/)
WatchVideoByLink
Tags: javascript, webdev, github, opensource
Published: 2022-01-10 10:50:45

WatchVideoByLink - Takes a public URL and displays the video in a video player that has features which make watching the provided video an enjoyable process with the ability to Watch/Download/Organize MP4/WebM/HLS/MPEG-DASH video types

Github - https://github.com/MohamedBakoush/WatchVideoByLink


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mq5w7q4tgo4au3ryux7p.jpeg)
RudderStack Unaffected by Log4j Vulnerability
Tags: security, log4j, dataprivacy, customerdata
Published: 2022-01-10 10:45:15

You may be aware of the widespread security issue relating to the Log4j vulnerability that has affected many companies and vendors. We are happy to report that our systems are unaffected by this vulnerability.

What is the scope of the Log4j vulnerability?
---------------------------------------------

Apache Log4j is a popular Java-based logging library that gives developers an easy way to build a record of activity that can be used for auditing, data tracking, troubleshooting and more. Many companies around the world use Log4j to configure their applications. Last week, a vulnerability involving remote code execution was discovered. While that vulnerability is now patched, cybersecurity experts are raising concerns as thousands of hacking attempts are occurring per hour.

Why is RudderStack a safer solution for customer data pipelines?
----------------------------------------------------------------

RudderStack does not use Log4j or any software impacted by this vulnerability. Our approach is warehouse-first and we do not store sensitive information. With RudderStack, your warehouse is turned into a data pipeline infrastructure. Our customers can implement the RudderStack SDKs just once and then automatically send data to their warehouse and business tools without API changes and broken pipelines.

If you are interested in exploring a safer way to set up, collect, transform, and route your customer data, [try RudderStack for free](https://app.rudderstack.com/signup?type=freetrial).
SWIFT - Adaptation of new platform
Published: 2022-01-10 10:27:10

‘Lyft’ was the San Francisco-based driver-on-demand car service and Uber’s Competitor. Soon after the 2014 WWDC, they investigated the usage of Swift for their app and finally redo its complete iOS app from scratch in Apple’s new language ‘Swift 4.0’.

Lyft decided to pivot from being a conventional ride-sharing service into something more directly competitive with Uber. A bit over a year after Apple’s announcement, it was ready with an all-Swift version of Lyft. The company believes that it’s the largest app to make the move, both in terms of lines of code and the number of users.

You could see the advantages of Swift, just in compactness and the more modern programming paradigm that came into play.

Pete Morelli, Lyft’s VP of engineering

Appleinsider also interviewed various Business Houses and Enterprise, who already started using Swift after its debut in 2014 WWDC to understand how the industry is accepting the new language. Following are some insights and verdicts.

Raphael Miller (Getty Images) noted that while the initial Swift betas were "pretty raw," since then "each release has gotten better." While there are "still some crashes in XCode" related to compiler issues and some problems with intermixing Objective-C and Swift, Miller said that the success of Stream--which is written entirely in Swift--has his team "ready to start the conversion of all our apps to Swift," with the full Getty Images app targeting a near term goal of reaching 50 to 60 percent Swift code.

Swift has "people banging on our door.

Raphael Miller, Manager of Application Development at Getty Images

Phillip Easter (American Airlines) noted Swift's tangible benefits include higher quality code that's easier to maintain along with related performance enhancements and said American is "definitely adopting Swift going forward."

What Apple is doing with Swift is a great addition.

Phillip Easter, American Airlines

SlideShare's Engineering Manager Francisco Meza stated that the "timing worked perfectly for us to develop a brand new application completely in Swift (except for the little pieces of Objective-C required for interoperability), as we were just finishing the first early prototype of what would become the SlideShare iOS app."

I must say that I am very satisfied by runtime performance of Swift based on the comparison of performance tracking metrics for similar pages of both SlideShare's app (Swift) and LinkedIn's flagship app (Objective-C).

Francisco Meza, SlideShare's Engineering Manager