teleren/devto huggingface dataset:
71. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 06:53:31

```
class Solution {
 public:
  string simplifyPath(string path) {
    string ans;
    istringstream iss(path);
    vector<string> stack;

    for (string dir; getline(iss, dir, '/');) {
      if (dir.empty() || dir == ".")
        continue;
      if (dir == "..") {
        if (!stack.empty())
          stack.pop_back();
      } else {
        stack.push_back(dir);
      }
    }

    for (const string& s : stack)
      ans += "/" + s;

    return ans.empty() ? "/" : ans;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/simplify-path/
60. Leetcode Solution in Python
Tags: python
Published: 2022-07-08 06:50:31

```
class Solution(object):
    def getPermutation(self, n, k):
        pe=[]
        list=[]
        for i in range(1,n+1):
            list.append(str(i))
        k1=k-1
        n1=n-1
        def fact(m):
            if m==0:
                return 1
            x=1
            for i in range(1,m+1):
                x=x*i
            return x
        while n1>=0:
            a=min(k1/fact(n1),n1)
            
            k1=k1-a*fact(n1)
            n1=n1-1
            pe.append(list[a])
            list.pop(a)
            
        return ''.join(pe)
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/permutation-sequence/
CSS Assistant
Tags: python, cssassistant, webdev, programming
Published: 2022-07-08 06:41:41

Hello friends,

CSS Assistant is a CSS kernel utility that can help you with user-side coding. This assistant receives commands by voice from the user and after the necessary processing, adds the command or attribute to the file and the changes in the file will be applied immediately.

> **v1.0 (Sunday, June 6, 2022)**:
- 35 Command CSS and 6 Command System = [ListCSSAssistant](https://github.com/Mhadi-1382/CSS-Assistant/blob/main/ListCSSAssistant.txt)

## Installation:
To launch the program, first install the required packages and then use the program safely. You can also install the required packages by running the setup.bat file.

## Core Dependencies:
- SpeechRecognition
- colorama
- platform
- pyttsx3
- random
- os

Project at GitHub: https://github.com/Mhadi-1382/CSS-Assistant
Using AWS Amplify UI for Creating Biodata Application
Published: 2022-07-08 06:30:43

**Introduction:**
​​AWS Amplify UI is an open-source UI library that brings the simplicity and extensibility of AWS Amplify to UI development. It consists of connected components that simplify complex workflows like authentication and dynamic data, primitive components that form the building blocks of a UI, and themes to make Amplify UI fit any brand. Extensibility and customization are at the forefront of Amplify UI allowing easy integration into any application regardless of the front-end tech stack.

**Steps in creating Biodata Application using React and AWS Amplify UI**
**Step-1:**Use command prompt and execute the following command
`npx create-react-app mybiodata && cd mybiodata`
**Step-2:**Now the basic react app required for creating the Biodata Application is created with the name “mybiodata”
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewygrdlszaeluh6y9oac.png)
**Step-3:**Now start the development server using the below command
npm start
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6xnhq0htidfvuoc0efqf.png)
**Step-4:**Now you can see your development server is running in the web browser
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zbczmn73oj9crsgd1kn.PNG)
**Step-5:**install the Amplify UI React package using the command given below
`npm i @aws-amplify/ui-react aws-amplify`
**Step-6:**Creating Biodata Reactapp Component using the code given below in app.js file

```
import { Button, Flex, Heading, Image, Text } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
function App() {
  return (
    <Flex
      direction={{ base: 'column', large: 'row' }}
      maxWidth="32rem"
      padding="1rem"
      width="100%"
    >
      <Image
        alt="My Biodata"
        height="21rem"
        src="mybio.png"
        width="100%"
      />
      <Flex justifyContent="space-between" direction="column">
        <Heading level={3}>Sample BioData</Heading>
        <Text>
          Name:Ramu<br></br>
          Date of Birth:03-05-1984<br></br>
          Qualification:B.Tech M.E<br></br>
          Address:Street1
                  Village1,
                  State 
                  Country<br></br>
          Hobbiles:Singing playing,listening music<br></br>
        </Text>
        <Button
          variation="primary"
          onClick={() => alert('View More!')}
        >
          View More...
        </Button>
      </Flex>
    </Flex>
  );
}
export default App;
```
**Step-7:**Run the app in the browser using the URL http://localhost:3000/. Now the Biodata React App will be displayed below
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnldrtc4xcvrcjyfgriq.PNG)
**Conclusion:**
 Thus we have created a Biodata Application using AWS AmplifyUI and React.
100 Days of Learning From My Mistakes – Day 1
Tags: heroku, webdev, node, react
Published: 2022-07-08 06:19:42

PSA: For a maximally enjoyable read, play my [song of the day](https://www.youtube.com/watch?v=KMOoNlD_bNg) while reading.

After what essentially amounted to a day's worth of wasted time trying to figure this out, Heroku support came through for the win. 

My personal website had been running flawlessly up until yesterday, where out of the great beyond my entire App crashed on Heroku. I was getting the dreaded H10 error. Interestingly it was happening only after adding a couple of icons with react-icons. I would push, then after a second or two of functionality it would crash. 

But when I checked out to the head position before my adding of the icons, and pushed again it worked!

Surly this massive crash couldn't have been from adding a couple of tiny react-icons. 

Well... kind of. 

After sorting through a long list of accumulating errors, this one stuck out to the Heroku rep:

`2022-07-07T17:47:12.103981+00:00 app[web.1]: FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory`

Meaning...at some process in my application, WAY too much memory was being used in the memory heap. 

For now, the short-term solution was changing the node settings on Heroku's end with 

`$ heroku config:set NODE_OPTIONS="--max_old_space_size=2560" -a <app_name>"`

and 

`export NODE_OPTIONS="--max-old-space-size=8192"`

to increase the allowed memory of node. 

While that did fix the fatal error, I suspect I have a memory leak somewhere. 

But that's for another Day of Learning from My Mistakes. 

Until next time 👋 
-Dan
www.dndl.me
Top 10 freelancing website in 2022
Tags: earning, freelancing, devearning, technology
Published: 2022-07-08 06:16:50

A freelancer works independently, not as an employee for a company. Since freelancers are self-employed, they generally make direct contact with clients to discuss hiring terms and service rates. Companies often hire freelancers as independent contractors for a short period or a specific project.

Step by Step Full Article: https://itznur07.medium.com/top-10-freelancing-marketplace-in-2022-75db2325fe0e 💸💸💸
A simple hta program to document oracle tables
Tags: oracle, javascript, html, hta
Published: 2022-07-08 06:13:11

Just code a hta (html application) program to document table/view for oracle. It use Microsoft OLE DB (MSDAORA) to connect to oracle. no more dependence.

[https://github.com/casualwriter/hta-db-schema]()

![screen layout of db-schema-oracle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aslfokzos62rzprnpwgp.jpg)

1. single file without dependence.
1. document oracle using built-in "comments" feature.
1. classify tables/views into "folder"
1. doubleclick to add/modify table description
1. doubleclick to add/modify column description
1. show and print table definition
1. search keyword in name or description

no installation is needed. Just download file db-schema-oracle.hta to local, and click to run.

ps: the code is simple (in 270 line). you may check it out [here](https://github.com/casualwriter/hta-db-schema/blob/main/source/db-schema-oracle.hta) before run

![first screen, input parameter for DB connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2e4ccnh09ehxio7b4m8b.jpg)


enjoy,
C#: How to unit test ILogger?
Published: 2022-07-08 05:52:08

As ``logger.LogError()`` or ``logger.LogInformation()`` are extended method, we cannot directly mock these methods.

According to [this stackoverflow](https://stackoverflow.com/questions/58294825/how-to-check-that-an-error-is-logged-in-a-unit-test-for-asp-net-core-3-0), we can mock it by using underline method with little trick.

# Unit Test logger.LogError

This is how I write unit test for ``logger.LogError`` to be called only once.

The Log method takes ``FormattedLogValues`` class instance in third argument, which is internal class, thus I couldn't instantiate it. Therefore I use ``It.IsAny<It.IsAnyType>()``.

```csharp
Mock<MyService> mockedMyService = new();
mockedILogger.Verify(x => x.Log(
  LogLevel.Error,
  It.IsAny<EventId>(),
  It.IsAny<It.IsAnyType>(),
  It.IsAny<Exception>(),
  It.IsAny<Func<It.IsAnyType, Exception?, string>>()),
  Times.Once);
```

Other extension methods such as ``LogWarning``, ``LogInformation`` shall work in the same manner.
692. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 05:39:46

```
class Solution {
 public:
  vector<string> topKFrequent(vector<string>& words, int k) {
    const int n = words.size();
    vector<string> ans;
    vector<vector<string>> bucket(n + 1);
    unordered_map<string, int> count;

    for (const string& word : words)
      ++count[word];

    for (const auto& [word, freq] : count)
      bucket[freq].push_back(word);

    for (int freq = n; freq > 0; --freq) {
      sort(begin(bucket[freq]), end(bucket[freq]));
      for (const string& word : bucket[freq]) {
        ans.push_back(word);
        if (ans.size() == k)
          return ans;
      }
    }

    throw;
  }
};

```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/top-k-frequent-words/
1046. Leetcode Solution in Java
Tags: java
Published: 2022-07-08 05:37:59

```
class Solution {
    public int lastStoneWeight(int[] stones) {
        PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.reverseOrder());
        for (int stone : stones) {
            heap.add(stone);
        }
        
        while (heap.size() > 1) {
            int stone1 = heap.remove();
            int stone2 = heap.remove();
            
            if (stone1 - stone2 != 0) {
                heap.add(stone1 - stone2);
            }
            
        }
        return heap.isEmpty() ? 0 : heap.remove();
    }
}
```

#leetcode
#challenge
here is the link for the problem:
https://leetcode.com/problems/last-stone-weight/
Cómo crear una base de datos postgres y luego asignarle a un usuario.
Published: 2022-07-08 05:26:45

Despues de [crear el usuario company](https://medium.com/crehana/creaci%C3%B3n-de-usuario-en-postgresql-10-4-y-ubuntu-18-04-9e80fe077f7e), vamos a continuar con la creación de la base de datos.

- role/usuario -> company

- database -> company_db


## Creamos la base de datos llamado **company_db**

Abrimos el terminal con **Ctrl + Alt + T** y nos conectamos con el usuario postgres, si desean  pueden ingresar con el  usuario company. Yo lo hago con la intención de mostrarles cómo cambiar de propietario a una base de datos. 

```
sudo -i -u postgres
```
Luego ejecutamos **psql** para ingresar a la consola de postgres y digitamos **\l** para ver las bases de datos que tenemos.
```
psql
postgres=# \l

```

Seguidamente creamos nuestra base de datos **company_db** con el siguiente comando.

```
CREATE DATABASE company_db;
```
![databases](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lh723ngawdhcmvsm6fn6.png)

Como podemos ver ya tenemos la nueva base de datos, propietario  del usuario postgres y sin ningún privilegio.

Ahora cambiaremos de propietario y le otorgaremos todos los privilegios de la base de datos **company_db** al usuario **company**.

```
 ALTER DATABASE company_db OWNER TO company;
 GRANT ALL PRIVILEGES ON DATABASE company_db TO company;

```
![database with owner](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5i1p7plx45o6ghci42wh.png)
 
 
Para finalizar salimos de la consola postgres con el comando `exit` e ingresamos a la base de datos `company_db` con el usuario `company`.

```
psql company_db company;

```

```
SELECT current_database();
```
 

```
SELECT current_user;
```

![Resultado de base de datos](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60r4qxesnkqhx6vij7ik.png)
 

Listo! :rocket:
1473. Leetcode Solution in CPP
Tags: cpp
Published: 2022-07-08 05:22:41

```
class Solution {
 public:
  int minCost(vector<int>& houses, vector<vector<int>>& cost, int m, int n,
              int target) {
    // dp[k][i][prevColor] := min cost to paint houses[i..m) to k neighborhoods
    // w/ houses[i - 1]'s color = prevColor
    dp.resize(target + 1, vector<vector<int>>(m, vector<int>(n + 1)));

    // init: prevColor = 0 (virtual neighbor)
    const int c = minCost(houses, cost, m, n, target, 0, 0);
    return c == kMax ? -1 : c;
  }

 private:
  constexpr static int kMax = 1e6 + 1;
  vector<vector<vector<int>>> dp;

  int minCost(const vector<int>& houses, const vector<vector<int>>& cost,
              const int& m, const int& n, int k, int i, int prevColor) {
    if (i == m || k < 0)
      return k == 0 ? 0 : kMax;
    if (dp[k][i][prevColor] > 0)
      return dp[k][i][prevColor];
    if (houses[i] > 0)  // painted last year
      return minCost(houses, cost, m, n, k - (prevColor != houses[i]), i + 1,
                     houses[i]);

    int ans = kMax;

    // try to paint houses[i] with each color in 1..n
    for (int color = 1; color <= n; ++color)
      ans = min(ans, cost[i][color - 1] + minCost(houses, cost, m, n,
                                                  k - (prevColor != color),
                                                  i + 1, color));

    return dp[k][i][prevColor] = ans;
  }
};

```



https://leetcode.com/problems/paint-house-iii/
Go Course: Hello world
Tags: go, tutorial, beginners
Published: 2022-07-08 05:12:08


Let's write our first hello world program, we can start by initializing a module. For that, we can use the `go mod` command.

```bash
$ go mod init example
```

But wait...what's a `module`? Don't worry we will discuss that soon! But for now, assume that the module is basically a collection of Go packages.

Moving ahead, let's now create a `main.go` file and write a program that simply prints hello world.

```go
package main

import "fmt"

func main() {
	fmt.Println("Hello World!")
}
```

_If you're wondering, `fmt` is part of the Go standard library which is a set of core packages provided by the language._

## Structure of a Go program

Now, let's quickly breakdown what we did here, or rather the structure of a Go program.

First, we defined a package such as `main`.

```go
package main
```

Then, we have some imports.

```go
import "fmt"
```

Last but not least, is our `main` function which acts as an entry point for our application, just like in other languages like C, Java, or C#.

```go
func main() {
	...
}
```

Remember, the goal here is to keep a mental note, and later in the course, we'll learn about `functions`, `imports`, and other things in detail!

Finally, to run our code, we can simply use `go run` command.

```bash
$ go run main.go
Hello World!
```

Congratulations, you just wrote your first Go program!

---

_This article is part of my open source [Go Course](https://www.karanpratapsingh.com/courses/go) available on Github._

{% github karanpratapsingh/go-course %}
The experience of writing a ray tracer in Go
Tags: go, raytracer, computergraphics, learning
Published: 2022-07-08 05:11:42

## Motivation

There was a lazy day on an extended weekend when I was watching [The Cherno's Code Reviews](https://www.youtube.com/watch?v=sb1FtMYAcYQ) series and came to meet (again) the [Ray Tracing in a Weekend](https://raytracing.github.io/) book series. As the code was already in C++, I thought it wouldn't be much of a challenge to write it again in the same language. It would rather be best to identify and improve bottlenecks, or to use Modern C++ techniques.

Alas, I had already written a ray tracer in C back in college as a classroom assignment and had worked on some improvements in a Computer Graphics class in my post-grad.

But as I'm learning Go (and loving it) and I was searching for projects that would be nice to have a taste of what Go has to offer, it occurred to me that writing the ray tracer[<sup>1</sup>](#note1) in Go would be fun and easy.

And it was.

## Go makes it a breeze

Go already has image manipulation, profiling, and flag-parsing off the shelf. So, instead of following the book's suggestion of writing the result to a text file, I could output it directly to a png file.

Go's syntax[<sup>2</sup>](#note2) makes you write clean and easy-to-understand code. This project made me work with interfaces, whereas in C++ I'd probably resort to templates or inheritance.

The only external library I had to resort to was a Go implementation of [glm](https://github.com/engoengine/glm).

## What's next?

Once I finished the first book, I knew some improvements could be made to run faster and better. For example, as ray tracing is extremely parallel, I could use goroutines to use more cores.

Also, there are other two books in the series: "The next week", and "The rest of your life".

## The path of others

Surely, I wasn't the only one who thought about doing this project. If you're interested in how other developers handled implementing the ray tracer in Go, I'd recommend taking a look at these:

- [Erik Lupander - Optimizing a simple ray-tracer written in Go, part 1](https://callistaenterprise.se/blogg/teknik/2020/07/04/a-go-ray-tracer/)
- [Mark Phelps - Writing a Ray Tracer in Go](https://github.com/markphelps/go-trace)
- [Yan Pujante - Ray-Tracing](https://github.com/ypujante/ray-tracing)

## What do we take from it?

Adapting "Ray Tracing in a Weekend - Part 1"'s code to Go was an entertaining experience. I certainly would recommend using it to get a hold of the basics of a new language you're learning. I'm just waiting for the opportunity to tackle the second and third books in the series, and going back to the start with [The Ray Tracer Challenge](https://pragprog.com/titles/jbtracer/the-ray-tracer-challenge/).

{% embed https://github.com/killerasus/GoRTIW %}

<a name="note1">1</a>: Actually more of a path tracer than a ray tracer.
<a name="note2">2</a>: Sometimes I get myself thinking that Go is C and Python's child.
4 Most Common Git Mistakes 😍 🔥
Tags: git, productivity, programming, webdev
Published: 2022-07-08 04:57:28

## 1. Discard changes to local files in git
As a programmer, it happens every day that unexpected errors occur. To solve the errors quickly, we fumble wildly with the code. Unfortunately, these code changes are not always optimal. It is, therefore, helpful to quickly undo the changes you have made. this is the common mistake in git 
. if you don't want to do it you can do git commit with a comment.
With the command “git checkout” you can reset the files to their original state:

 - Reset directory "myCode"
git checkout - myCode

## 2. Undo local commits. git commit revert

You have already created four new commits and only now realize that one of these commits contains a major error. Oops!

No panic. If you want to undo one or more commits, you can use the “git reset” command. The command knows three different modes (soft, hard, mixed):

 - Undo the last four commits, keep changes
git reset HEAD ~ 4

- Undo the last four commits, discard changes
git reset --hard HEAD ~ 4

## 3. Remove the file from Git without deleting it completely in git commit

You often add a file to the staging area ( git add ) that doesn’t belong there. You can use the command “ git rm “ here. However, this also removes the file from your file system.

However, if you want to keep the file in the filesystem, you can better remove it from the staging area with “git reset <filename>”. Then add the file to the .gitignore so that you do not mistakenly pack it back into the staging index in the future. That’s how it’s done:

git reset Dateiname
echo Dateiname >> .gitignore

## 4. Git commit message change
git commit message changes Every programmer makes a typo on a commit. Fortunately, commit messages are very easy to correct using the “git commit — amend” command. you can commit your code with your own git commit with a message. That’s how it’s done:

- Start the standard text editor to edit the commit message
git commit --amend

- Sets the new message directly
git commit --amend -m "My new commit message
HTML Cheatcode
Tags: beginners, webdev
Published: 2022-07-08 04:13:57

Just starting prep-work for a 24-week coding bootcamp. After some intro reading, I was giving the task of reading a blog post topic and writing about what I learned. HTML cheatcode is what I read up on and I learn that HTML is basically the skeleton of a web page. HTML is what you use to layout your webpage without graphics or flare.
Redirect user to homepage after login/logout in WordPress
Tags: wordpress, woocommerce
Published: 2022-07-08 04:03:26

Let’s assume you have a WooCommerce shop in multisite WordPress installation. When user will logout then is redirected to main website from your multisite. User should be redirected to homepage of your store. If you want to redirect user to homepage after login or logout in WordPress put this code in functins.php file:

{% gist https://gist.github.com/texe/dac667b13b996d2708230a43cd2dec78 %}

After saving the file user after logout will be redirected to homepage.