teleren/devto huggingface dataset:
Longest Common Subsequence
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 13:30:42

Given two strings `text1` and `text2`, return _the length of their longest **common subsequence**._ If there is no **common subsequence**, return `0`.

A **subsequence** of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.

*   For example, `"ace"` is a subsequence of `"abcde"`.

A **common subsequence** of two strings is a subsequence that is common to both strings.

**Example 1:**

**Input:** text1 = "abcde", text2 = "ace" 
**Output:** 3  
**Explanation:** The longest common subsequence is "ace" and its length is 3.

**Example 2:**

**Input:** text1 = "abc", text2 = "abc"
**Output:** 3
**Explanation:** The longest common subsequence is "abc" and its length is 3.

**Example 3:**

**Input:** text1 = "abc", text2 = "def"
**Output:** 0
**Explanation:** There is no such common subsequence, so the result is 0.

**Constraints:**

*   `1 <= text1.length, text2.length <= 1000`
*   `text1` and `text2` consist of only lowercase English characters.

**SOLUTION:**

    class Solution:
        def lcs(self, text1: str, text2: str, i, j) -> int:
            if (i, j) in self.cache:
                return self.cache[(i, j)]
            if i >= len(text1) or j >= len(text2):
                self.cache[(i, j)] = 0
                return 0
            if text1[i] == text2[j]:
                self.cache[(i, j)] = 1 + self.lcs(text1, text2, i + 1, j + 1)
                return self.cache[(i, j)]
            else:
                a = self.lcs(text1, text2, i + 1, j)
                b = self.lcs(text1, text2, i, j + 1)
                self.cache[(i, j)] = max(a, b)
                return self.cache[(i, j)]
            
        def longestCommonSubsequence(self, text1: str, text2: str, i = 0, j = 0) -> int:
            self.cache = {}
            return self.lcs(text1, text2, 0, 0)
Hitchweb! Browser Extension🧩, Talk to people on same website 🤩
Tags: javascript, webdev, react, programming
Published: 2022-06-06 13:21:35

Recently, I wrote a post [Talk to people who are on the same site 🌎 | Chrome Extension](https://dev.to/rajeshj3/talk-to-people-who-are-on-the-same-site-chrome-extension-5hh7). Where I talked about an **extension for chromium based browsers.**

---

## ✨ Finally ✨

The extension is now 🔴 Live on **Chrome Web Store** to be downloaded for chromium based browsers.

👉 [Install **HitchWeb** from here](https://chrome.google.com/webstore/detail/hitchweb/bbpnmmlldlnbkoelibmceelheacmbhme) 👈

## Let's Talk 💬💬

Let's Join in the [**dev.to**](https://dev.to/) **room** itself.

---

## Feedbacks ✨

Feedbacks are welcomed, as this is an early release, it is going to crash a lot, you may find a lot of bugs here.

## Support 😇

This is a small project as of now, that I build all alone by myself. Your support is appreciated 😊

---

## Contact me 💬

If you have any feedback, bug report or any concern drop **an email** to me at `info.rajeshj3@gmail.com`

---

## Spamming? 👺

This is our dev community, let's not do the bad stuff here, I request every one not to create any mess.

And, if you are facing any trouble, please report to me.

As this is an early release, it doesn't contains any spam detection, or ban system.

---

## Thank you 😍

I thank all our dev community members 🦄 on reading this post and trying [Hitchweb](https://chrome.google.com/webstore/detail/hitchweb/bbpnmmlldlnbkoelibmceelheacmbhme). ✨

Thank you
Happy Coding 🤓
Day 9 - Decision Making
Tags: 100daysofcode, solidity, web3, blockchain
Published: 2022-06-06 13:17:00

{% embed https://github.com/Envoy-VC/30-Days-of-Solidity noreadme %}

This is Day `9` of `30` in Solidity Series
Today I Learned About Decision Making in Solidity.

## If Statement

This is the most basic conditional statement. It is used to make a decision whether the statement or block of code will be executed or not. If the condition is true the statements will be executed, else no statement will execute.

**Syntax** -

```solidity
if (expression) {
    Statement(s) to be executed if expression is true
}
```
Example -

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    uint i = 4;
    function ifStatement() public returns(bool) {
        if(i>5) {
            return true;
        }
    }
}
```

Output -

```solidity
"0": "bool: false"
```

---

## If - Else Statements

This statement is the next form of conditional statement which allows the program to execute in a more controlled way. Here if the condition is true then the, if block is executed while if the condition is false then else block, is executed.

![If - Else Statements](../assets/if-else.jpg)

**Syntax** -

```solidity
if (expression) {
    Statement(s) to be executed if expression is true
} else {
    Statement(s) to be executed if expression is false
}
```

Example -

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    uint i = 4;

    function ifElseStatement() public returns (string memory) {
        if (i > 5) {
            return "i is greater than 5";
        } else {
            return "i is less than 5";
        }
    }
}
```

Output -
```solidity
"0": "string: i is less than 5"
```

---

## If-Else If-Else Statement

This is a modified form of if…else conditional statement which is used to make a decision among several options. The statements start execution from if statement and as the condition of any if block is true the block of code associated with it is executed and rest if are skipped, and if none of the condition is true then else block executes.

**Syntax** -

```solidity
if (expression 1) {
    Statement(s) to be executed if expression 1 is true
} else if (expression 2) {
    Statement(s) to be executed if expression 2 is true
} else if (expression 3) {
    Statement(s) to be executed if expression 3 is true
} else {
    Statement(s) to be executed if no expression is true
}
```

Example -

```solidity
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.7;

contract MyContract {
    uint i = 4;

    function ifElseIfElseStatement() public returns (string memory) {
        if (i < 2) {
            return "i is less than 2";
        } else if (i >= 2 && i < 8) {
            return "i is between 2 and 8";
        } else {
            return "i is greater than 8";
        }
    }
}

```

Output -

```solidity
"0": "string: i is between 2 and 8"
```

---
[Conceito] - Backoff e Jitter
Published: 2022-06-06 12:55:10

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

---

Ei dev,

Quer aprender dois conceitos sensuais pra você ter uma noite bem gostosa e duradoura com seu crush? Já ouviu falar de BACKOFF e JITTER?

Dá até pra aplicar esses conceitos se o negócio estiver indo muito rápido e alguém não estiver dando conta. 😁

cc @sseraphini

↓

![uma linda mulher cavalgando](https://pbs.twimg.com/media/FUkg9qRUUAE5a4Y?format=png&name=small)

---

Quando fazemos requisições, alguma coisa pode dar errada. O servidor pode estar muito ocupado, a rede lenta ou até uma pessoa muito ansiosa. :)

Backoff, nesse contexto, significa tentar posteriormente essa mesma requisição.

---

Já falei um pouco sobre retry (retentativa) na thread abaixo.

(Backoff pode estar relacionado com processamento de mensagens vindas de filas e outras coisas também como chamadas HTTP, por exemplo.)

https://twitter.com/zanfranceschi/status/1522554964534435840

---

Uma coisa importante sobre backoff é que existem estratégias para definir o intervalo entre as retentativas. O intervalo pode ser linear, mínimo, polinomial, exponencial, aleatório, etc.

Bom, backoff é isso.

---

Agora, vamos falar sobre jitter. Acabei de mencionar que o intervalo do backoff pode ser aleatório. Pois então, jitter significa aleatório. Bom, na verdade significa irregular, mas pra obtermos irregularidade, usamos aleatoriedade :)

---

Vamos juntas as peças agora com um exemplo. Imagina se o poupa tempo da Índia (existe isso lá?), falhasse e as milhares de pessoas naquele dia voltassem todas na mesma hora do dia seguinte. Iria entupir os guichês de atendimento no dia seguinte.

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

---

Aí é que o conceito de jitter poderia ajudar: algumas pessoas deveriam voltar de manhã, outras mais tarde, outras talvez outro dia, etc. O ideal é que a retentativa tenha um intervalo irregular entre as várias requisições que foram contidas.

---

Claro, estamos falando de sistemas e é mais trivial que as retentativas não tenham um intervalo tão grande assim que chegue a dias. Mas deu pra entender a analogia, né?

---

Outra parte importante e uma prática comum é que o backoff, além de sua estratégia de intervalo (exponencial, por exemplo), adicione jitter pra evitar aquele "entupimento" que comentei. Claro, o jitter por si só poderia ser uma estratégia de intervalo desde que seja maior que 0.

---

Vale ressaltar que quem define a estratégia de backoff é quem faz a requisição na maioria dos casos, ok?

---

Agora você já sabe, se estiver difícil manter as noites duradouras com o crush, você pode solicitar que a outra parte use backoff e jitter para que haja um afastamento temporário e uma nova tentativa. 😁

---

Preciso nem dizer, né? Dá um abraço aqui por ter lido e dado essa moral (mas vem com calma). 💕
Codespaces - first reactions
Tags: github, virtualisation
Published: 2022-06-06 12:53:34

---
title: Codespaces - first reactions
published: true
description: A few initial thoughts on using Github's new Codespaces
tags: github, virtualisation
---

I've had beta access to [Codespaces](https://docs.github.com/en/codespaces) now for two weeks or so and I have to say that it's an impressive integration. I was aware that the VS Editor was enabled to improve editing repositories online but the addition of a functioning shell and easy pretty forwarding to local web apps is both easy to use and seamless. There have been many promises of virtual development environments but this is the first time I've felt it could be true.

The integration with the Github repos is great too, meaning you don't have to learn any new commands or patterns of work you can just translate your preferred Git flows.

I haven't got any Github deployment actions so I haven't been see a continuous deployment flow without a local client involved. I'm still a little wary of completely automated deployment for my hobby projects as I don't have great monitoring or release testing for things that are mostly for fun or my own use.
How to build a generic Shopify API integration
Tags: api, programming, integration, shopify
Published: 2022-06-22 11:12:09

---
title: How to build a generic Shopify API integration
published: true
date: 2022-06-06 12:52:33 UTC
tags: API,Programming,Integration,Shopify
canonical_url: https://linx.software/shopify-integration/
---

You can use webhook subscriptions to receive notifications in a Linx Application about particular events in a Shopify store. After you’ve subscribed to a webhook, you can let your app execute code immediately after specific events occur in shops that have your app installed, instead of having to make API calls periodically to check their status. For example, you can rely on webhooks to trigger an action in your app when a customer creates a cart, or when a merchant creates a new product in their Shopify admin. By using webhooks subscriptions you can make fewer API calls overall, which makes sure that your apps are more efficient and update quickly.

Full solution https://linx.software/shopify-integration/
Sample https://github.com/linx-software/shopify-api-integration
AWS Cognito and Federated Identities
Tags: aws, cognito, saml, oauth
Published: 2022-06-06 12:44:22

I have two application environments in the cloud. 1) a Wordpress site providing protected courses through an LMS. 2) a custom-built mobile app. Users of both are currently authenticating against a single Cognito user pool - authentication is working perfectly. I have a new customer that wants their users to have access to both these environments. The catch is they do not want their users to maintain credentials in my Cognito environment. Surely there is a solution in federated identities and/or SAML and/or OAuth - but I need some help to understand the large component parts, and maybe some of the implementation. Thanks!
Update env variables in Windows 10 without Restarting/Logout
Published: 2022-06-06 12:38:37

Hi,
a quick post, I just installed [WAMP](https://www.wampserver.com/en/) and I needed to work with MySQL from the shell (Powershell or cmd or whatever :P ), I added the `bin` folder to the [Environment Variables](https://superuser.com/questions/949560/how-do-i-set-system-environment-variables-in-windows-10) but without restarting, here is how to do it quickly :

1 - Install [Chocolatey](https://docs.chocolatey.org/en-us/choco/setup) as an Admin using this command from [PowerShell](https://github.com/PowerShell/PowerShell) :
 `Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))`

2 - Run this simple command : `RefreshEnv.cmd` (you can use Refre and type Tab like you do in Linux...right ? ^^ )

3 - Done
Bootstrap + JQuery - How to create a checkbox button
Tags: jquery, webdev, javascript, bootstrap
Published: 2022-06-06 12:31:40


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f1ejrooha3txqqdgmkpc.png)
HTML:
```
<div class="container p-4">
    <span class="button-checkbox">
        <button type="button" class="btn btn-sm btn-outline-primary" data-color="primary">Example</button>
          <input type="checkbox" class="d-none"/>
    </span>
</div>
```

Script:
```
$('.button-checkbox').each(function () {
    var $button = $(this).find('button'),
        $checkbox = $(this).find('input:checkbox'),
        color = $button.data('color');

    $button.on('click', function () {
        $checkbox.prop('checked', !$checkbox.is(':checked')).triggerHandler('change');
        initialize();
    });

    $checkbox.on('click', function () {
        initialize();
    });

    function initialize() {
        var tab = $button.parents('.tab-pane').attr('id'),
            parentButton = $('#' + tab + '-tab'),
            checkBoxCount = $button.parents('.content').find('input[type="checkbox"]').filter(':checked').length,
            isChecked = $checkbox.is(':checked');

        $button.data('state', isChecked ? 'on' : 'off');
        parentButton.children('span').remove();

        if (checkBoxCount) {
            parentButton.append('<span class="badge badge-primary ml-auto float-right d-flex align-items-center shadow-sm">' + checkBoxCount + '</span>');
        }

        if (isChecked) {
            $button.append('<i class="fas fa-check ml-1"></i>');
            return $button.removeClass('btn-outline-primary').addClass('bg-' + color + ' shadow-sm text-white');
        }

        $button.children('i').remove();
        return $button.removeClass('bg-' + color + ' active text-white').addClass('btn-outline-primary');
    }
});

```
Contains Duplicate
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 12:30:39

Given an integer array `nums`, return `true` if any value appears **at least twice** in the array, and return `false` if every element is distinct.

**Example 1:**

**Input:** nums = \[1,2,3,1\]
**Output:** true

**Example 2:**

**Input:** nums = \[1,2,3,4\]
**Output:** false

**Example 3:**

**Input:** nums = \[1,1,1,3,3,4,3,2,4,2\]
**Output:** true

**Constraints:**

*   `1 <= nums.length <= 105`
*   `-109 <= nums[i] <= 109`

**SOLUTION:**

    import heapq
    
    class Solution:
        def containsDuplicate(self, nums: List[int]) -> bool:
            n = len(nums)
            heapq.heapify(nums)
            curr = heapq.heappop(nums)
            for _ in range(n - 1):
                currnew = heapq.heappop(nums)
                if curr == currnew:
                    return True
                curr = currnew
            return False
Use the shared component reference
Published: 2022-06-06 12:05:35

Hi Team,
I have a requirement where I have to render Component A twice in the Container, one at the top and one at the bottom.
Both the components should be in sync , changes made at one place should be reflected at other place.
Is there any approach to do it, without lifting the state up?

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4tvr6b5oakxhe8hpupma.png)
Typescript & Terraform for beginners - Infrastructure as code (IaC)
Tags: devops, typescript, node, terraform
Published: 2022-06-06 11:19:53

Today I'm going to demonstrate how to spin up AWS Infrastructure using Typescript and Terraform. To spin up infrastructure using Terraform, usually we'll have to write HCL (Hashicorp Configuration Language) manifests but with Terraform CDK we can spin up our own infrastructure with various Cloud providers (AWS, Google, Azure, etc) while using our favorite programming languages.

{% embed https://www.youtube.com/watch?v=IBb7ncNYiqg %}
Palindromic Substrings
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 12:00:47

Given a string `s`, return _the number of **palindromic substrings** in it_.

A string is a **palindrome** when it reads the same backward as forward.

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

**Example 1:**

**Input:** s = "abc"
**Output:** 3
**Explanation:** Three palindromic strings: "a", "b", "c".

**Example 2:**

**Input:** s = "aaa"
**Output:** 6
**Explanation:** Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

**Constraints:**

*   `1 <= s.length <= 1000`
*   `s` consists of lowercase English letters.

**SOLUTION:**

    class Solution:
        def countSubstrings(self, s: str, i = 0) -> int:
            n = len(s)
            if i == n - 1:
                return 1
            k = self.countSubstrings(s, i + 1)
            ctr = 0
            for j in range(i + 1, n + 1):
                if s[i:j] == s[i:j][::-1]:
                    ctr += 1
            return ctr + k
Docker series (Part 4): How to look what is going on in a container?
Tags: docker
Published: 2022-06-06 11:39:22

These are the commands we are going to use for checking the containers

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

Let's first create containers


L![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/10tpqzuoin0mq3xfafhf.png)
Let's create the 2nd one

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

Now lets see the containers

```
docker container ls
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bpxlofy04i6r8rdmf089.png)
Now , lets see some information for the container_1 
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k2kt46ogh657u129nboa.png)
Same for the container_2


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/omqp4yauw6sokw636bxy.png)
Let's investigate more
Now, we will use 

```
docker container inspect <container name>
```
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3c02womxtl5bkvnwv0ga.png)
Also for the 2nd one

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n613ktfc2g0ryo9jiyf4.png)
This basically shows all the metadata for the container

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

We also can use the `stats` command to know more details like which is active or not

Now, if we type 

```
docker container stats
```
we can see a streaming view of our containers activity

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7k00bd3ngdwvh1vvxmc0.png)
SO, this is how we can track our containers and their activities

Bye then!
<img src="https://c.tenor.com/Tvd3VKwtse0AAAAC/cat-cute.gif">
Check if Binary String Has at Most One Segment of Ones
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 11:30:50

Given a binary string `s` **​​​​​without leading zeros**, return `true`​​​ _if_ `s` _contains **at most one contiguous segment of ones**_. Otherwise, return `false`.

**Example 1:**

**Input:** s = "1001"
**Output:** false
**Explanation:** The ones do not form a contiguous segment.

**Example 2:**

**Input:** s = "110"
**Output:** true

**Constraints:**

*   `1 <= s.length <= 100`
*   `s[i]`​​​​ is either `'0'` or `'1'`.
*   `s[0]` is `'1'`.

**SOLUTION:**

    class Solution:
        def checkOnesSegment(self, s: str) -> bool:
            s += "0"
            segments = []
            chunk = ""
            for c in s:
                if c == '0' and len(chunk) > 0:
                    segments.append(chunk)
                    chunk = ""
                elif c == '1':
                    chunk += '1'
            return len(segments) <= 1
JavaScript project
Tags: beginners, javascript, programming
Published: 2022-06-06 11:30:04

Can anyone help me with this course on JavaScript from Udemy? I've been struggling a lot with the course, and now I'm doing a project to create a game, but my basics are a little unclear, I recently covered it, but still I've made so many mistakes, should I revisit basic, or should I do some more projects to help me better understand it?
Sort the Jumbled Numbers
Tags: leetcode, dsa, theabbie
Published: 2022-06-06 11:00:44

You are given a **0-indexed** integer array `mapping` which represents the mapping rule of a shuffled decimal system. `mapping[i] = j` means digit `i` should be mapped to digit `j` in this system.

The **mapped value** of an integer is the new integer obtained by replacing each occurrence of digit `i` in the integer with `mapping[i]` for all `0 <= i <= 9`.

You are also given another integer array `nums`. Return _the array_ `nums` _sorted in **non-decreasing** order based on the **mapped values** of its elements._

**Notes:**

*   Elements with the same mapped values should appear in the **same relative order** as in the input.
*   The elements of `nums` should only be sorted based on their mapped values and **not be replaced** by them.

**Example 1:**

**Input:** mapping = \[8,9,4,0,2,1,3,5,7,6\], nums = \[991,338,38\]
**Output:** \[338,38,991\]
**Explanation:** 
Map the number 991 as follows:
1. mapping\[9\] = 6, so all occurrences of the digit 9 will become 6.
2. mapping\[1\] = 9, so all occurrences of the digit 1 will become 9.
Therefore, the mapped value of 991 is 669.
338 maps to 007, or 7 after removing the leading zeros.
38 maps to 07, which is also 7 after removing leading zeros.
Since 338 and 38 share the same mapped value, they should remain in the same relative order, so 338 comes before 38.
Thus, the sorted array is \[338,38,991\].

**Example 2:**

**Input:** mapping = \[0,1,2,3,4,5,6,7,8,9\], nums = \[789,456,123\]
**Output:** \[123,456,789\]
**Explanation:** 789 maps to 789, 456 maps to 456, and 123 maps to 123. Thus, the sorted array is \[123,456,789\].

**Constraints:**

*   `mapping.length == 10`
*   `0 <= mapping[i] <= 9`
*   All the values of `mapping[i]` are **unique**.
*   `1 <= nums.length <= 3 * 104`
*   `0 <= nums[i] < 109`

**SOLUTION:**

    class Solution:
        def mapNum(self, num, mapping):
            op = 0
            for c in str(num):
                op = 10 * op + mapping[int(c)]
            return op
        
        def sortJumbled(self, mapping: List[int], nums: List[int]) -> List[int]:
            return sorted(nums, key = lambda num: self.mapNum(num, mapping))