teleren/devto huggingface dataset:
Best Time To Buy Stock
Tags: javascript, leetcode
Published: 2022-09-27 17:57:29

Solution 1: 
```js
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function(prices) {
    let minPrice = prices[0];
    let profit = 0;
    for(let i=0; i<prices.length; i++){
        if(prices[i] < minPrice){
            minPrice = prices[i];
        }else if (prices[i] - minPrice > profit){
            profit = prices[i] - minPrice;
        }
    }
    return profit;
}

```

Solution 2 : 

```js
var maxProfit = function(prices) {
    let buy = prices[0]
    let profit = 0
    for (let price of prices) {
        if (price < buy) {
            buy = price
        }
        profit = Math.max(price - buy, profit)
    }
    return profit
};

```
Best Time to Buy and Sell Stock II -

 Input: prices = [7,1,5,3,6,4]
 Output: 7
 Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
 Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

```js
/**
 * @param {number[]} prices
 * @return {number}
 */
var maxProfit = function (prices) {
  let left = 0;
  let profit = 0;

  for (let i = 0; i < prices.length; i++) {
    if (prices[i] > prices[left]) {
      let currentProfit = prices[i] - prices[left];
      profit = currentProfit + profit;
      left++;
    } else {
      left = i;
    }
  }

  return profit;
};

```
I reduced an npm package size by 50% with minification
Tags: javascript, webperf, opensource, react
Published: 2022-09-27 17:16:36


Web performance is something that a lot of people do not consider when they set out to build software that works on the web. 

Everyone should strive to meet or at least work to ensure that the projects they build on the web are performant. You do not need to be an expert at this, anyone can start by making the web less cluttered than the way we met it.

The amount of unused code that we ship sometimes contains the bulk of problems related to performance that a lot of people experience. From sites that are lagging to the ones that take so much time to be interactive, you name them.

## One step towards this practice is minification. 

I've been working on this [opensource project](https://www.npmjs.com/package/status-modal) for a while now and the unpacked size of the first stable version was around **53.2kB**, Take a look at the image below. 


![status-modal-before-minification](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vz8t4s2w3akxn7lri6x7.png)

**fifty-three kilo-byte** was a little bit large, and since the bundler I'm using for this package is [rollup.js](https://rollupjs.org/), all I needed to do was install the terser &mdash; [a JavaScript compressor toolkit for ES6](https://terser.org/) &mdash; plugin for rollup.

I went on to edit the config file of my package to accommodate the plugin by adding it to the list of plugins in the rollup config.

```js
// rollup.config.js
import babel from "rollup-plugin-babel";
import { terser } from "rollup-plugin-terser";

const dev = process.env.NODE_ENV !== "production";

export default {
  input: "src/index.js",
  output: {
    file: "dist/index.js",
    format: "cjs",
  },
  plugins: [
    terser({
      ecma: 2015,
      mangle: { toplevel: true },
      compress: {
        toplevel: true,
        drop_console: !dev,
        drop_debugger: !dev,
      },
      output: { quote_style: 1 },
    }),
  ],
};
``` 

With the config above, the package size went from 53.2kB to **29.2kB**. That's around 50% of the package size gone.

![status-modal after minification](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rtbs6o7oelzwuwfqzmgj.png) 

## Final thoughts

There's a popular phrase on the internet about web performance. Some folks say "fixing web performance is as easy as drawing a horse".

I can agree with that, as it is a gradual process. You can start by running your app through Lighthouse on chrome DevTools to see how you can improve the performance.

With the 50% of the npm package gone, you've reduced a very small amount of the chunk of code you're sending to your users. Do that for a lot of other packages, routes, or components and see the result. That's how you start.

Thank you for reading, and I hope this article has been helpful.
Display Hello World on Screen in React Native
Tags: reactnative, javascript
Published: 2022-09-27 17:16:08

import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaView, Text, View } from 'react-native';


export default class App extends React.Component {
  render() {
    return (
      <SafeAreaView style={android.mainScreen}>
        <View style={android.screen}>
          <Text style={android.text}>React Native</Text>
        </View>
      </SafeAreaView>
    )
  }
}

const android = {
  mainScreen: {
    height: "100%",
    width: "100%",
  },
  screen: {
    height: "100%",
    width: "100%",
    backgroundColor: "black",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
  },
  text: {
    color: "dodgerblue",
    fontWeight: "bold",
    fontSize: "25px",
  },
};

/*
i have written this code into App.js file of react native project file. and get following result

*/

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3amqdawzhljeyvh5vis5.png)
MY JOURNEY INTO THE TECH WORLD
Published: 2022-09-27 16:55:25


MY JOURNEY INTO TECH
My name is Uzoma Esther Ogbu and this is my journey into the tech industry .
I have a always been a tech enthusiast, I have had this passion for a long period of time . But before I got into tech , I was a teacher and then one day I sat down and spoke to myself “I knew that I was meant for more , it was time to chase my dream of becoming a software developer” , so my journey started , first off I got to know about a very renowned coding academy (CodeLab) through a friend, he even helped me get a form (did I mention it was a scholarship ?)
It was a scholarship program , thereby there is a high chance of you not getting in but I put that aside and decided to go head on even though in was afraid of the outcome. So we went through so many interviews and screenings …….long story short , I got in (I was among the lucky twenty -five ) and yeah I was so happy even though I felt like I didn’t deserve it and that fueled my determination and zeal to learn and acquire knowledge.
Before I started coding , I had absolutely ZERO knowledge in tech , I was clearly a novice but I knew that that was not what I wanted , I wanted to be the best or one of the best and that was it about that
Now, I am two months into the tech world learning software development at the best academy CodeLab and I can proudly say that I have improved and grown in so many areas of my life . my vision is clear , I know what I want and I am so determined to get it
NOTHING CAN STOP A MAN WITH A STRONG ZEAL AND DETERMINATION
BEST REGARDS
OGBU UZOMA ESTHER
imma leave this one right here
Published: 2022-09-27 16:55:16


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


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


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


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


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


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


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


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


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


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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iwkuf10ixhebbn5s83eb.png)
Adding more functionalities
Tags: javascript, webdev, github, git
Published: 2022-09-27 16:46:04

>Language Support

For this week's content, I added a single functionality for my current SSG project. The purpose is to allow the converted html files to be that of a specified language provided by the user; in default the language will be "en-CA". What type of language is essential for the files during conversion.

>Markdown Support: Horizontal Line

Some files will not have a horizontal line, but some will. By adding this functionality, it ensures that all files that the user provides regardless on whether they have an hr or not, will ensure for the best results.

>Problems

The problem that I had with this week's content is the "git merge", it was a little bit confusing. I mean having two separate branches to do two smaller tasks doesn't sound appealing. After doing it, and failing miserably the first few times allowed me to finally understand why having this is a great idea. Having multiple branches ensures that when pushing my code, it is well organized and not cluttered out when committed.


[Project Repo](https://github.com/Ririio/ririio-ssg)
Microservices are bad for some cases…
Tags: microservices, monolith, dokcer, kubernetes
Published: 2022-09-27 16:37:32

Microservices are bad (for some cases as well)!
One of the most trickiest things to have when dealing with Microservices is that sometimes there are chances to have problems during the communication between services, maybe one of the services is down at the moment, one solution for that is having some replicas for that service (like having PaaS tools like Kubernetes or Docker Swarm to orchestrate your services).

Having said that, it may become difficult to manage large amount of services, especially when some services are dependent to other ones.

One of the hardest things as well is that the testing may become complex over a distributed environment. Sometimes you may create some fake APIs for your testing to unit test your single service, it’s not ideal but it can do the job.

So keep in mind, not all solutions are the ideal ones, there are always drawbacks and challenges to deal with them. Sometimes your problem can be solved in a Monolithic architecture instead of Microservices, maybe you want vertical scale instead of horizontal scale? It’s always about choosing the path and design your system that suits your problem..
How To Pass Arguments To The Vuex Getters
Tags: javascript, vue, vuex
Published: 2022-09-27 16:30:09

We use **Vuex** to do more systematic state management with **Vue JS**.

**Getters** with a **Vuex** property are written like functions but work like computed properties.

Sometimes; When using **getters** in **Vuex**, in some cases we may want to send some arguments to our **getters**.

To do this we can use the "Method-Style Access" method provided by vuex.

Using this method we should define our getters like this:

Defining:
```javascript
getterName: (state) => (parameter) => { // get the parameter
    return state.data.find(item => item.id === parameter)
}
```

Using this defining method, we can send arguments to the getters we define.

Usage:
```javascript
store.getters.getterName(2); // we sent 2 as getter parameter
```


But sometimes we can include our getters with the "mapGetters" helper. 
In this case, we must use a different method to send arguments to the getters.


## Sending arguments to getter included with mapGetters

After defining the getter with the same method, we include it in the component with "mapGetters".

To send an argument to a getter included with mapGetters; we need to define a new computed property.

This new computed property will take parameter like a function. It will send this parameter as an argument to the getter that comes with mapGetters and return this value.

```javascript
import { mapGetters } from 'vuex';

  computed: {

    // import the getters with mapGetters
    ...mapGetters([
      'getterName',
    ]),

    //Define New Computed Property
    newGetter(parameter){ // get the parameter
      return this.getterName(parameter) // return the value
    }

  }
```

Thus, the arguments we send to our getter named **newGetter** will be sent to the getter we include with mapGetters.


Method-Style Access:
[https://vuex.vuejs.org/guide/getters.html#method-style-access](https://vuex.vuejs.org/guide/getters.html#method-style-access)
Expanding cards with CSS
Tags: css, html, showdev, beginners
Published: 2022-09-27 16:24:51


I saw a brilliant course by @florinpop17 on YouTube and wanted to try some projects myself.

##Overview
Create a cards of pictures and expand that card on hover.

##Implementation
I started by placing five pictures in one section.
```javascript
  <section>
    <img src="assets/hawai.webp" />
    <img src="assets/bamboo-forest.webp" />
    <img src="assets/cappadocia.webp" />
    <img src="assets/Lake-Croatia.webp" />
    <img src="assets/mount-fuji.webp" />
  </section>
```
and styled it
```javascript
    section {
      display: flex;
      flex-direction: row;
    }
    img {
      width: 50px;
      height: 340px;
      object-fit: cover;
      border-radius: 40px;
      margin-right: 10px;
      cursor: pointer;
    }
```
Images will begin showing just like this
![img-cards](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wj9ibezxv6iptdsia7o8.png)

Now I added `:hover` selector with width property and increased the card width. I have also added a `transition` property to make it smooth.
```javascript
  img {
    ...
    transition: width 0.5s ease-in-out;
  }
  img:hover {
    width: 400px;
  }
```
and that's it! You get very pleasing expanding cards.

{% codesandbox picture-slide-i10kw9 %}
Thank you for reading!
Feel free to connect on [Twitter](https://twitter.com/Aneeqa_Khan25)
How to add shake animation on input:invalid
Tags: webdev, html, css, keyframe
Published: 2022-09-27 16:21:17

In this short article we'll create a simple HTML with an input tag in a form tag and animate the input when user input is not valid.
This might seem a bit difficult and you may think  you need Javascript to complete this task,but with only HTML and CSS(keyframes) we'll get this done.

Let's write some code

### Adding our HTML
```
<!DOCTYPE html>
<head>
    <meta charset="UTF-8" />
</head>
  <body>
     <form action="">
        <input type="text" minlength="5" />
      </form>
  </body>

</html>
```
### Using the :invalid pseudo selector
In our css we style the input with the :invalid pseudo selector
```
<style>
input:invalid{
animation:shake .3s
}
</style>
```
### Adding shake animation with keyframes 
Animations in CSS are mostly done with keyframes and so will our shake animation 
```
<style>
.....
@keyframes shake{
25%{transform:translate(4px)}
50%{transform:translate(-4px)}
75%{transform:translate(4px)
}}
</style>
```

### Final Results
We set the minimum length of our input to 5, this means the input is invalid if the user enters less than 5 characters.
And the input box shakes when the user input is less than 5 , thus the form is invalid
Miniconda in WSL
Tags: datascience, anaconda, linux, wsl
Published: 2022-09-27 16:16:10

# Install
Download the latest version of miniconda:
```
wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
```
Install it:
```
bash Miniconda3-latest-Linux-x86_64.sh
```

# After Installation

To install conda's shell functions, first restart your shell, then: 
```
conda init
```

If you'd prefer that conda's base environment is not activated on startup, set the auto_activate_base parameter to false: 
```
conda config --set auto_activate_base false
```

Remove the installation file from your directory:
```
rm Miniconda3-latest-Linux-x86_64.sh
```

# Using Miniconda

To get into your conda environment 
```
conda activate
```

To create a new environment:
```
conda create --name <new-env-name> 
```

To view all your environments:
```
conda env list
```

Conda cheat sheet PDF [here](https://docs.conda.io/projects/conda/en/4.6.0/_downloads/52a95608c49671267e40c689e0bc00ca/conda-cheatsheet.pdf).

## Other useful things to know
Open current directory in file explorer
```
explorer.exe .
```
A few days ago, Nicolas Rabault and the Luos team had the pleasure to participate to the NuttX 2022 online conference.
Tags: opensource, microservices, nuttx, luos
Published: 2022-09-27 16:14:03

▶️ https://www.youtube.com/watch?v=af70koiSFxs

We presented our vision, our technology and a way to contribute to the integration of NuttX with Luos.

Thanks again to Alan and the organizing committee for this opportunity, great things are ahead! 😃

Workshop Committee: Espressif, Sony, Verge Aero, Technolution, NscDg, PHI Innovations, IQ-Analog, Sony Corp, Xiaomi.
Getting started with Poetry
Tags: python, beginners
Published: 2022-09-27 16:06:42

## Installation & environment activation
Install Poetry (Linux/WSL. For others, see [Poetry docs](https://python-poetry.org/docs/#installation)):
```
curl -sSL https://install.python-poetry.org | python3 -
```
Create new project: 
```
poetry new <project-name>
```
Navigate to project directory:
```
cd <project-name>
```
Activate virtual env from directory:
```
poetry shell
```

## Installing packages
Installing packages:
```
poetry add <package-name>
```

From a requirements.txt ([more info](https://danielms.site/blog/requirements-txt-to-poetry-pyproject-toml/)):
```
cat requirements.txt | grep -E '^[^# ]' | cut -d= -f1 | xargs -n 1 poetry add
```

See more useful commands [here](https://realpython.com/dependency-management-python-poetry/#command-reference).
How do you focus??
Tags: webdev, productivity, discuss, beginners
Published: 2022-09-27 15:58:55

How do you guys focus in an increasingly noisy/busy atmosphere?

I'm the eldest child at home so I'm the constant go to for menial house chores. It's gotten so bad that I started listening to music so I can act like I can't hear them🥴

I thank God that I found out about J Dilla and Lo-fi music because any fast or lyric-filled song would always disrupt my train of thought. 

What are other things do you guys use to focus? What do you think would help me in my quest of peace and quiet?
Decimal to Binary conversion in C++
Tags: cpp
Published: 2022-09-27 15:47:01

You can access this code on my [Github](https://github.com/MadhubanKhatri) profile.

```
#include<iostream>
using namespace std;

int main(){
	int n;
	cout<<"Enter a Number: ";
	cin>>n;
	int rem=n%2;
	while(true){
		
		if(rem==0){
			n=n/2;
			int rem=n%2;
			cout<<rem;
		}
		else{
			int rem=n%2;
			n=n/2;
			cout<<rem;
		}
		
		if(n==0){
			break;
		}
	}
}```
My own preferable way to make memories of my own project
Tags: github, productivity, devjournal
Published: 2022-09-27 15:46:05

I have been developing my own project, which is replicating [Quora](https://www.quora.com/) website for my own portfolio and skill improvement in web development. The project's still in progress, there's still a lot of improvement to make. For a better understanding of what I make, this is the original [Quora](https://www.quora.com/)'s home page(before they updated to last version).

![This is the original Quora's home page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7fuy90gl1p1y7d6sl82p.png)

And this is my own version of Quora, using React JS for frontend, NodeJS for backend and PostgreSQL for database
![This is my own version of Quora](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fk9mslaiwv5vkhoa74qa.png)

Now, how do I make my project more memorable? I make a Word file inside the project's repository which contains the project's development from the first day. Each time I have done with my project development, I will write everything of what I've done to the project for the day. For more details you can check my [Github repository](https://github.com/kevincp17/QuoraReactVersion)   

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

You can see a Readme Progress.docx on the repository. You can download it to see the project's development since day 1. This is what it looks like.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6sqx9lj8jfe5fj8n7t26.png)

So yeah, it's like a diary but for project development. I am so happy each time I read it, because I can see how much my projects improved since day 1. It feels like watching your plant growing from a small seed to full grown beautiful flower.

What do you guys think?
Usando --amend
Tags: javascript, git, programming, tutorial
Published: 2022-09-27 15:38:25

Cuando empecé en el mundo de la programación era normal ir a mi github, filtrar por los Pr's y ver cosas como:

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

Y ufffff 47 commits 🙈 pues no es que se vea muy bonito ¿verdad? gracias a que he tenido buenos compañeros mas seniors que uno me enseñaron a usar **_--amend_** y hoy quiero enseñarte a usarlo y decirte porqué es bueno usarlo y como me ha ayudado 🔥.

## ¿Porque usarlo?

Bueno la respuesta es simple, porque nos ayuda a tener un mejor control ✌🏽, dicen que buenas practicas es tener commits funcionales y que no supere cierto numero de commits, ¿Porqué? porque si queremos hacer por ejemplo un botón:


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


¿Te imaginas tener _n_ commits con: text, rounded, icon, background, color o quizás enviaste un commit con algo dañado nos tocaría hacer otro commit que diga algo como **_update o adjustment_** ? 🤔

Noooo!!! no es optimo la idea es que tengamos commits funcionales y por bloques y es ahi done **_--amend_** nos ayuda un montón.

## ¿Como usarlo?

Es muy fácil si por ejemplo enviamos nuestro primer commit normalmente como lo hacemos hoy en día.

`git commit -m"Component button disable"`

Pero luego te diste cuenta que aun no sirve el disable, tu harías algo como:

`git commit -m"Component button disable true"`

Pero con ammend podemos hacer lo siguiente:

`git commit --amend -m"Component button disable"`

y eso reemplaza el antiguo commit y solo tendríamos un commit y nadie se daría cuenta que la embarramos, ¿no te parece genial?


## Tener en cuenta al hacer push

Cuando hacemos push con ammend hay que hacerlo de la siguiente manera:

`git push -force`

## Conclusión

Pero ojo 👀 solo ammend funciona si no has realizado merge de alguna rama, si hiciste merge tienes que hacer commit de la forma tradicional pero si no dale candela al ammend 🔥.

A mí me ha ayudado mucho y siento que es más organizado mi trabajo y más limpio.

Bueno hasta aquí un pequeño relato de lo que he aprendido sobre Git estaré dando más consejos que me han ayudado 🚀 cuéntame si lo usas y si no, cuéntame que te parece ¿vas a usarlo?
Kenapa Project Android Setelah release atau build Gagal Fetch Api
Tags: android, reactnative, bahasaindonesia
Published: 2022-09-27 15:29:09

#Pendahuluan
hari ini saya mengalami error pada project android saya, setalah saya relase apk dan mau ditest ternyata muncul error gagal fatch api kebackend. setalah saya googling ternyata penyebab errornya karena domain server saya masi menggunakan http.

#Solusi
untuk fix error gagal fetch yang pertama bisa ubah url dari http menjadi https, yang kedua bisa tambahakan  `android:usesCleartextTraffic="true"` di file `AndroidManifest.xml`

#refrensi
https://github.com/nowsecure/secure-mobile-development/blob/master/en/android/set-usescleartexttraffic-to-false.md