teleren/devto huggingface dataset:
Gas Station
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 22:00:46

There are `n` gas stations along a circular route, where the amount of gas at the `ith` station is `gas[i]`.

You have a car with an unlimited gas tank and it costs `cost[i]` of gas to travel from the `ith` station to its next `(i + 1)th` station. You begin the journey with an empty tank at one of the gas stations.

Given two integer arrays `gas` and `cost`, return _the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return_ `-1`. If there exists a solution, it is **guaranteed** to be **unique**

**Example 1:**

**Input:** gas = \[1,2,3,4,5\], cost = \[3,4,5,1,2\]
**Output:** 3
**Explanation:**
Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 4. Your tank = 4 - 1 + 5 = 8
Travel to station 0. Your tank = 8 - 2 + 1 = 7
Travel to station 1. Your tank = 7 - 3 + 2 = 6
Travel to station 2. Your tank = 6 - 4 + 3 = 5
Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
Therefore, return 3 as the starting index.

**Example 2:**

**Input:** gas = \[2,3,4\], cost = \[3,4,3\]
**Output:** -1
**Explanation:**
You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
Travel to station 0. Your tank = 4 - 3 + 2 = 3
Travel to station 1. Your tank = 3 - 3 + 3 = 3
You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
Therefore, you can't travel around the circuit once no matter where you start.

**Constraints:**

*   `n == gas.length == cost.length`
*   `1 <= n <= 105`
*   `0 <= gas[i], cost[i] <= 104`

**SOLUTION:**

    class Solution:
        def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
            n = len(gas)
            total = 0
            abstotal = 0
            res = 0
            for i in range(n):
                diff = gas[i] - cost[i]
                total += diff
                abstotal += diff
                if total < 0:
                    total = 0
                    res = i + 1
            if abstotal < 0:
                return -1
            return res
Infrastructure as Code Tools
Tags: devops, terraform, aws, azure
Published: 2022-06-08 00:17:15

[Infrastructure as Code Tools](https://www.bitslovers.com/infrastructure-as-code-tools/)


Infrastructure as Code (IaC) Tools is most useful for an DevOps Engineer.

Are you aware of the tools available in market? Read our article and find out the best IaC tools of 2022.

[Infrastructure as Code Tools](https://www.bitslovers.com/infrastructure-as-code-tools/)

Thanks
Number of Strings That Appear as Substrings in Word
Tags: leetcode, dsa, theabbie
Published: 2022-06-08 00:00:44

Given an array of strings `patterns` and a string `word`, return _the **number** of strings in_ `patterns` _that exist as a **substring** in_ `word`.

A **substring** is a contiguous sequence of characters within a string.

**Example 1:**

**Input:** patterns = \["a","abc","bc","d"\], word = "abc"
**Output:** 3
**Explanation:**
- "a" appears as a substring in "abc".
- "abc" appears as a substring in "abc".
- "bc" appears as a substring in "abc".
- "d" does not appear as a substring in "abc".
3 of the strings in patterns appear as a substring in word.

**Example 2:**

**Input:** patterns = \["a","b","c"\], word = "aaaaabbbbb"
**Output:** 2
**Explanation:**
- "a" appears as a substring in "aaaaabbbbb".
- "b" appears as a substring in "aaaaabbbbb".
- "c" does not appear as a substring in "aaaaabbbbb".
2 of the strings in patterns appear as a substring in word.

**Example 3:**

**Input:** patterns = \["a","a","a"\], word = "ab"
**Output:** 3
**Explanation:** Each of the patterns appears as a substring in word "ab".

**Constraints:**

*   `1 <= patterns.length <= 100`
*   `1 <= patterns[i].length <= 100`
*   `1 <= word.length <= 100`
*   `patterns[i]` and `word` consist of lowercase English letters.

**SOLUTION:**

    from collections import Counter
    
    class Solution:
        def numOfStrings(self, patterns: List[str], word: str) -> int:
            n = len(word)
            patterns = Counter(patterns)
            lens = set([len(p) for p in patterns])
            ctr = 0
            for l in lens:
                for i in range(0, n - l + 1):
                    curr = word[i:i+l]
                    if curr in patterns:
                        ctr += patterns[curr]
                        del patterns[curr]
            return ctr
Day 60: Two months. whew!
Published: 2022-06-07 23:37:16

Hi!

Two months now! unbelievable! I remember the day I started this public journaling/Writing and wanted to delete my `dev` account the following day because I could stay consistent at anything haha! and now Here we are... 60days of consistency (even on difficult times). These past Two months for sure are the most productive months for me as a developer, I learned a lot, I'm now more focused and motivated to learn and write code, and for once I was doing things and see a lot of progress that I'm actually growing and going somewhere.

One of the things that helped me more during this journey is writing tutorial articles, because writing forces you to do more research to understand concepts clearly and making them simpler for you and others to understand. I noticed that I have changed my approach to learning new concepts where as now I learn something with the intention that I may do an article about it after therefore I now try to understand concepts more deeply instead of just copy pasting snippets for the sake of finishing a task. now 60days are down but the target is hitting 500 days and more I don't see myself stopping this, in fact I will accelerate with more articles and more journaling. Even if sometimes things get hard, slowly by slowly we will Make it!

Today I continued working on the project but I was struggling with an error from Prisma which took me a lot of time to solve by realizing that I only needed to restart VS code but thankfully it led me to an amazing Series about Prisma posted here on `dev` [Here](https://dev.to/this-is-learning/its-prisma-time-create-relations-1ohb) and I started working on it together with the project so that would be the main plan for tomorrow
Generating nicely parsed schema files with pg_dump_schema_parser
Tags: postgres, sql, schemadump, schemafiles
Published: 2022-06-07 23:35:20

Ever had to go through thousands of lines of a schema file generated by `pg_dump`, it can be tedious and tasking. A little background [4-thousand-lines-of-code-in-a-single-file](https://www.quora.com/Is-it-a-good-idea-to-write-4-thousand-lines-of-code-in-a-single-controller-file)

A proper database design/development should be version controlled with a proper schema migration in place but some times we may want a schema dump for several reasons.

`pg_dump` is a tool supplied with PostgreSQL, used in taking bakckups and schema dumps of a single database.

I have had to look through 7000 lines of a schema file and it wasn't funny at all, I lost interest along the way. This prompted me to do some search for a tool I could use to split the schema dump into smaller pieces. I stumbled upon few stackoverflow questions around it, notably the following 
- https://stackoverflow.com/questions/18330358/postgresql-dump-each-table-into-a-different-file
- https://stackoverflow.com/questions/67890251/how-can-i-pg-dump-each-table-in-its-own-file-and-stay-consistent 
- https://stackoverflow.com/questions/7210320/pg-dump-individual-tables-possible-to-do-in-a-loop

While the above questions were limited to tables, I needed a tool that targets all object types.

After an exhaustive search and I couldn't find a tool to do the job properly, I decided to write one to do the job. This gave birth to [pg_schema_dump_parser](https://github.com/bolajiwahab/pg_schema_dump_parser).

`pg_schema_dump_parser` is a tool written in python which runs `pg_dump` in the background and parses the generated schema into the respective object name and according to the type of the object. Have a look at [how to use pg_schema_dump_parser](https://github.com/bolajiwahab/pg_schema_dump_parser#:~:text=Sample%20parsed%20schema-,Running%20the%20program,-Create%20pg_schema_dump_parser.config)

Having a schema dump which is nicely parsed into smaller pieces can greatly improve developer experience, imagine a developer having to go through a schema dump of 7000 thousands of lines just to find the definition for a particular table and another developer locating the specific file with the definition of a table of interest. The second developer would have a nice experience and find the table's definition in lesser time.
More entity framework core woes...
Published: 2022-06-07 23:07:29

Do one thing you have an error, fix one issue you have a warning, ignore the warning, the migrations stop working.

I've wasted many hours on entity framework over the many years that I have used it.

Why do I always have issues when EF is involved...

I really want to like it, I really tried, for years, but it keeps sending me down dark alleys and strange fixes.

If you want to judge for yourself, because you think EF is great, please be my guest and look at it for yourself.

- [https://github.com/kibblewhite/ef-issue-035](https://github.com/kibblewhite/ef-issue-035)

Everything about the issue is there...


p.s.
Also you can take a look at my previous issue too, if you feel so inclined:
- [https://github.com/kibblewhite/ef-issue-034](https://github.com/kibblewhite/ef-issue-034)

This 034 one is less of a thorn in my side.
How *ngIf teached me a lesson
Tags: angular, programming, firstpost, motivation
Published: 2022-06-07 23:06:35

Hi guys! This is my first post here on dev.to, and will be a short one. I just want to tell you a story about how *ngIf, an Angular's directive, teached me a lesson today.

##Context
I was trying to help my team to solve a problem were we had a modal and some nested components inside it, and some of these elements were formularys. I can't show the exact code, but here's a generic example:

```html
<modal [visible]="isVisible" [properties]="someProperties">
  <steps>
     <step>
        <formulary></formulary>
     </step>
     <step>
        <formulary></formulary>
     </step>
  </steps>
</modal>
```

Everything was working just as it should, we could fill formulary and navigate between steps without losing data. But, when we closed modal, we found out that, if we open modal again, the data was still there, even when modal was closed!

##The journey

We couldn't just pass an empty object to formulary's model when modal closes, it would be too complex to mantain, for other reasons. I began to search for alternatives, and I spent almost the whole afternoon trying to find a way to solve this problem. I tried a lot of things: use ViewChild decorator to watch modal and destroy its instance, use OnDestroy lifecycle to pass an empty object to every formulary when modal was closing... None of them worked.
I reached almost the end of my working journey without a solution, I was frustated and disappointed, thinking that this problem should be very simple to solve and that I wasn't capable to help my team.

##The lesson

Then, I had an idea: "what if I use ngIf on steps component, associating with modal's visibility?". It will not work, my pessimist mind thought. I tried a whole lot of complex implementations and no one work, why would a ngIf go?
It's very easy to find out what happened, right? It worked just as I needed.
It's probably very situational, and wouldn't work for others as it worked for me, but it teached me a lesson that I'll probably carry for a time. **Never subestimate the power of a simple solution.** The basis can take you really far, even if your solutions aren't the prettiest or most performatic ones.
Ones and Zeroes
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 23:00:46

You are given an array of binary strings `strs` and two integers `m` and `n`.

Return _the size of the largest subset of `strs` such that there are **at most**_ `m` `0`_'s and_ `n` `1`_'s in the subset_.

A set `x` is a **subset** of a set `y` if all elements of `x` are also elements of `y`.

**Example 1:**

**Input:** strs = \["10","0001","111001","1","0"\], m = 5, n = 3
**Output:** 4
**Explanation:** The largest subset with at most 5 0's and 3 1's is {"10", "0001", "1", "0"}, so the answer is 4.
Other valid but smaller subsets include {"0001", "1"} and {"10", "1", "0"}.
{"111001"} is an invalid subset because it contains 4 1's, greater than the maximum of 3.

**Example 2:**

**Input:** strs = \["10","0","1"\], m = 1, n = 1
**Output:** 2
**Explanation:** The largest subset is {"0", "1"}, so the answer is 2.

**Constraints:**

*   `1 <= strs.length <= 600`
*   `1 <= strs[i].length <= 100`
*   `strs[i]` consists only of digits `'0'` and `'1'`.
*   `1 <= m, n <= 100`

**SOLUTION:**

    class Solution:
        def longest(self, strs, i, m, n, slen):
            if m < 0 or n < 0:
                return -1
            if i >= slen:
                return 0
            key = (i, m, n)
            if key in self.cache:
                return self.cache[key]
            x, y = strs[i]
            a = 1 + self.longest(strs, i + 1, m - x, n - y, slen)
            b = self.longest(strs, i + 1, m, n, slen)
            mlen = max(a, b)
            self.cache[key] = mlen
            return mlen
        
        def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
            slen = len(strs)
            strs = [(s.count("0"), s.count("1")) for s in strs]
            self.cache = {}
            return self.longest(strs, 0, m, n, slen)
3Sum Closest
Tags: leetcode, dsa, theabbie
Published: 2022-06-07 22:30:40

Given an integer array `nums` of length `n` and an integer `target`, find three integers in `nums` such that the sum is closest to `target`.

Return _the sum of the three integers_.

You may assume that each input would have exactly one solution.

**Example 1:**

**Input:** nums = \[-1,2,1,-4\], target = 1
**Output:** 2
**Explanation:** The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).

**Example 2:**

**Input:** nums = \[0,0,0\], target = 1
**Output:** 0

**Constraints:**

*   `3 <= nums.length <= 1000`
*   `-1000 <= nums[i] <= 1000`
*   `-104 <= target <= 104`

**SOLUTION:**

    class Solution:
        def threeSumClosest(self, nums: List[int], target: int) -> int:
            n = len(nums)
            if n < 3:
                return []
            nums = [3 * num - target for num in nums]
            nums.sort()
            closest = float('inf')
            for i in range(n - 2):
                a = nums[i]
                start = i + 1
                end = n - 1
                while start < end:
                    b = nums[start]
                    c = nums[end]
                    total = a + b + c
                    if abs(total) < abs(closest):
                        closest = total
                    if total > 0:
                        end -= 1
                    else:
                        start += 1
            return target + closest // 3
Day 568 : Gold
Tags: hiphop, code, coding, lifelongdev
Published: 2022-06-07 22:29:07

_liner notes_:
- Professional : Pretty productive day for the first day back from travelling. I don't really count yesterday because I was recovering and filling out forms for my travels. Updated and refactored some code. Reached out to some folks. Reviewed some pull requests. Not bad.

- Personal : Last night, I watched an episode of the new season of "The Boys" and wow! Pure Gold! haha It looks like they will outdo themselves with the goriness! Again, wow.

![A series of waterfalls flowing into a lake in a lush jungle in Vibhooti Falls, India with lots of green vegetation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p69nuti82qrujmelu01n.jpg)

Found an error where some pictures where double posted in my travel blog site https://doingstuff.in . I think I know how the error occurred. I didn't refresh a page when I uploaded the photos and I remember thinking, "I wonder if this will work?" haha. I'll just have to go in the backend and delete the files. Then I want to look into a cool new library I came across on Twitter and maybe do a quick proof of concept. Will definitely end the night watching an episode of "The Boys".

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube 7IQE62Vn4_U %}
[Desafio] - Estimar Recursos Computacionais num Ambiente Elástico
Published: 2022-06-07 22:27:00

> Conteúdo original [nessa thread do Twitter](https://twitter.com/zanfranceschi/status/1534299607659819009)

---

Ei dev,

Aceita um desafio para estimar a capacidade computacional das máquinas que irão servir uma API num ambiente elástico com auto scaling? Então cola aí pra eu dar os detalhes :)

cc @sseraphini
 
↓

![img](https://pbs.twimg.com/media/FUrtXERVIAA4_xB?format=png&name=small)

---

Você precisa estimar a configuração das máquinas que irão servir uma API de modo que haja o menor desperdício possível.
O ambiente é auto escalável e o gatilho é o número de requisições, pois você sabe que 300 requisições/segundo são adequadamente atendidas por 1GB RAM/1 CPU.

---

Algumas premissas:
- Não pode haver menos de 2 nós rodando a qualquer horário.
- Para facilitar, assuma que o auto scaling ocorre quase que imediatamente quando o threshold for ultrapassado.
- As configurações válidas das máquinas são as combinações do desenho.

![img](https://pbs.twimg.com/media/FUrtXm1VIAAeGZr?format=png&name=360x360)

---

Esse é o gráfico que vc deve se basear para estimar a melhor configuração para as máquinas do cluster da API. Os horários não mostrados (entre 00:00 e 08:00), têm a média de menos de 100 requisições por segundo.

![img](https://pbs.twimg.com/media/FUrtX7nUUAEorUC?format=png&name=small)

---

É esse o máximo de informações que você tem para escolher uma das configurações válidas com a premissa de nunca haver menos de duas máquinas em execução por vez. O seu gestor está atacado e ansioso porque deveria ter lhe pedido isso antes e agora estão cobrando ele.

---

O termo para isso é dimensionamento de recursos. Em inglês, a galera chama de "sizing". É muito importante fazer o "right sizing" (dimensionamento correto) dos recursos para não haver desperdício financeiro. E esse advento de right sizing veio forte com os provedores cloud. 💵

---

Dá um abraço aqui se você aceitou o desafio ou pelo menos leu até aqui. 🫂

E obrigado demais pela moral como sempre! ❤️
How to Reconnect to Process logs on Ubuntu
Tags: devops, ubuntu, blockchain
Published: 2022-06-07 22:05:09

Running continuous processes or functions on a virtual machine is essential for any large development process.

Here's how to continuously run a process on Ubuntu, disconnect and then reconnect to access a process' logs.

## Step 1) Start `screen`

This might be already installed, check with: `screen --version`

If not, install with one of these commands (OS specific)

yum install screen
apt install screen

Open a screen session: 

`screen`

[Screen User Manual](https://www.gnu.org/software/screen/manual/screen.html)

## Step 2) Run your program with `&`

I'm running a validator in a GCP ubuntu virtual machine so my start command looks like:
`sudo mortar server --data-dir ./data-dir --chain genesis.json --libp2p 0.0.0.0:1478 --nat IP-ADDRESS --seal --price-limit 1 &`

Just make sure to add `&` to the end of whatever command you use. This is let the program to keep running even after you quit the shell session.

## Step 3) Disconnect your SSH session

You can do this by closing the shell window

## Step 4) Reconnect

Resume screen session: `screen -r`

You should now see the output of the process logs in real time
What are the issues you have with building or maintaining your website/startup search?
Tags: elasticsearch, discuss, startup, performance
Published: 2022-06-07 22:01:25

Currently, at [Spotlyt](https://spotlyt.cloud) we are building a tool and API that enables developers build good search infrastructure for their platform be it a website, app or documentation. We are basically not focusing on owning and defining consumer experience, but focusing on the simplicity of search from development perspective  just so developers can do more with less amount of code. 

We need sort of guidance and opinion from the community and we'd love you to share ideas with us, mainly around the problems you face building or implementing search.

You can also recommend features too!
SOON: Ace’s launching E-book on career progression on Product Hunt
Published: 2022-06-07 21:50:34

This Friday, June 11, Ace’s preparing for a big launch on [Product Hunt](https://www.producthunt.com/) with a big E-book on career progression to help managers plan the careers of their tech teams. And it’s awesome!

## Why have we made this guide?

**Reason #1.** Plenty of small and medium companies don’t feel the need to build a career ladder. Decisions on promotion are unplanned and professional development happens as the company grows. In this case, employees may lose motivation over time and leave their company for a place where they will be offered career growth opportunities. 

**Reason #2.** Implementing a career progression framework gives lots of benefits both to the company and employees. Among them are significant motivation increase, possibility to take transparent and fair promotion decisions, faster professional development of a team, and improving company brand image.  

**Reason #3.** To build an effective career progression, a manager needs to take into consideration the company’s goals and the existing practices that have been implemented by the top tech companies. 

With the help of Ace’s new E-book, managers will explore these practices and get all they need to implement career paths in their companies. 

## The GUIDE INCLUDES:

- ✅ Step-by-step guide on building a career ladder 
- ✅ Basic toolkit for a manager
- ✅ Experts’ advice and their experience in implementing career progression frameworks
- ✅ Examples of successful tech companies who have developed their own career ladders 
- ✅ FREE career path templates for 50+roles 

## BOUNS FOR OUR READERS:

You can download your free copy before the official launch via this link: [https://www.Ace.team/ebooks/career-path-guide](https://www.getace.io/ebooks/career-path-guide)

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