teleren/devto huggingface dataset:
Cambiar el valor NBF del JWT en ASP.NET MVC API - C#
Published: 2022-09-29 03:49:39

NBF en JWT significa Not Before
- Claim Name: "nbf"
- Claim Description: Not Before

Obtiene o establece la hora no anterior para el token de seguridad. Este valor debe estar en UTC. 
Es decir nbf: Define el tiempo antes del cual el JWT NO DEBE ser aceptado para su procesamiento.

Si por algún motivo tenemos o debemos cambiar el valor de NFB podemos hacerlo de la siguiente forma.

En la configuración para obtener nuestro token vamos a tener algo parecido a esto:
```csharp
private string generateJwtToken(User user)
        {
            // generate token that is valid for 7 days
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
                NotBefore = DateTime.UtcNow.AddMinutes(5),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
``` 
dentro de esta configuración la línea antes de especificar la expiración vamos a colocar la siguiente línea.
NotBefore = DateTime.UtcNow.AddMinutes(5)
Agregamos el tiempo en el que queremos que esté disponible nuestro token, en este caso de ejemplo le estoy agregando 5 minutos a la hora y fecha actual.

Y ya podemos observar los cambios generando el token y probándolo en https://jwt.io/

Eso es todo por hoy, espero que te sirvan de mucho estos recursos.

Puedes seguirme en [Twitter](https://twitter.com/veronicaguamann), [Instagram ](https://www.instagram.com/veronicaguamann/) o [Facebook](https://www.facebook.com/veronicaguamann/) para más contenido técnico, consejos y más.
Connecting to a Postgres DB from AWS Lambda python script
Tags: aws, postgres, lambda
Published: 2022-09-29 03:47:37

One of the most popular python libraries to connect to postgres is called **psycopg2**. psycopg2 however will not work in lambda because the lambda environment lacks the required postgreSQL libraries. 

There is [this](https://github.com/jkehler/awslambda-psycopg2) library that has baked in the required libraries into psycopg2. All we need to do is copy the psycopg2 directory into your AWS Lambda zip package like below.


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

```
import psycopg2

def get_record():
      conn = psycopg2.connect(
                            database="db-name",
                            host="mydb.com",
                            user="db_user",
                            password="db_password",
                            port="3306")
       cursor = conn.cursor()
     
       cursor.execute("SELECT count(*) FROM public.mytable")
       res = cursor.fetchall()

       for row in res:
         total_records = format(row[0])

       print(total_records)
```
Top K Frequent Elements
Published: 2022-09-29 03:45:08

Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]

```js
var topKFrequent = function(nums, k) {
    var obj ={}
    for(let i=0;i<nums.length;i++){
        if(!obj[nums[i]]) {
            obj[nums[i]] = 1
        }else{
            obj[nums[i]] +=1
        }
    }
    console.log(Object.keys(obj), obj)
    let sortedKeys = Object.keys(obj).sort((a,b)=>obj[b]-obj[a]);
    console.log(sortedKeys)
    let results =[]
     for(let i = 0; i < k; i++){
         results.push(sortedKeys[i])
     }
    return results
};

console.log(topKFrequent([4,1,1,1,2,2],  2))

```
Firebase Functions - An application is requesting permission to access your Google Account.
Tags: firebase, javascript, webdev, programming
Published: 2022-09-29 03:34:19

## The Bug
You're attempting to deploy a Firebase Cloud Function and have it serve a request, but you're presented with a screen saying "An application is requesting permission to access your Google Account"

*I work for [Akkio](https://akkio.com), where I'm building out a no-code predictive AI platform. If you're looking to harness the power of AI without needing a data scientist, give us a try!*


## The Solution
If you Google around, you'll see some advice that Cloud Functions are only supported in the `us-central1` region, but I'm pretty sure they've expanded by now. The reason I was getting this issue was related to some inconsistency with what regions everything was in.

You need to specify the region when defining your cloud function:

```js
const main = express();
main.use("/api/v1", app);
main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));
export const creditCards = functions.region("us-east1").https.onRequest(main); 
```

Secondly, as noted [on the docs page here](https://firebase.google.com/docs/hosting/full-config#rewrite-functions), if you fail to specify the region in your rewrites, it tries to guess the right region from your source code, defaulting to `us-central1` if it can't figure it out. You need to specify this region in your rewrites as well:

```json
"hosting": {
    "public": "public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "/api/v1/**",
        "function": "creditCards", 
        "region": "us-east1"
      }
    ]
  }
```

After fixing both of those, I was able to test in the local emulator and see the function successfully respond once I hit the endpoint.

Please note that while it's not mandatory to have all your different resources running in the same region, it's best practice to do so for latency reasons. I personally keep my Cloud Functions and Firestore in the same region.
Merge Two Sorted Lists
Tags: algorithms, csharp, leetcode, easy
Published: 2022-09-29 02:34:43

_#21.Merge Two Sorted Lists_

### Problem statement
You are given the heads of two sorted linked lists `list1` and `list2`.

Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

**Example 1**
```
Input: list1 = [1,2,4], list2 = [1,3,4]
Output: [1,1,2,3,4,4]
```

**Example 2**
```
Input: list1 = [], list2 = []
Output: []
```

**Example 3**
```
Input: list1 = [], list2 = [0]
Output: [0]
```

### Explanation
給定兩個已排序的 Linked List，分別為 `l1` 和 `l2` ，將兩個 Linked List 合併成一個 Linked List，並且該鏈結串列必須通過兩個鏈結串列的節點拼湊在一起，返回一個同樣排序的鏈結串列，返回的鏈結串列必須是第一個節點

### Solution
一開始先判斷兩個鏈結串列是否為 null，如果有一個是 null，則直接返回另一個鏈結串列

鏈結串列比較難解釋，首先要先知道鏈結串列的特性，它是屬於動態記憶體配置，為了返回指標在第一個節點的鏈結串列，我建立兩個鏈結串列分別為 `res` 和 `cur` ，`res` 是最終要返回的值，而 `cur` 是用來合併時使用的，並且讓 `cur = res` ，當 `cur` 被變更時，`res` 也會有相同的變化，因為指標欄是指向同一塊記憶體位置

使用 `while` 執行兩個鏈結串列當前值的比較，值比較小的就將當下的節點指給 `cur.next` ，並將其移動到下一個指標記錄的記憶體位置，最後將 `cur` 移動到下一個指標記錄的記憶體位置，以繼續連結接下來的比較結果節點，直到任一鏈結串列為 null 時就結束迴圈作業，最後將剩餘未進行比較的節點連結到 `cur` 的下一個指標欄，然後合併結果 `res.next`

```cs
public ListNode MergeTwoLists(ListNode l1, ListNode l2)
{
    if (l1 == null || l2 == null) return l1 ?? l2;

    ListNode res = new ListNode(), cur = res;

    while (l1 != null && l2 != null)
    {
        if (l1.val <= l2.val)
        {
            cur.next = l1;
            l1 = l1.next;
        }
        else
        {
            cur.next = l2;
            l2 = l2.next;
        }

        cur = cur.next;
    }

    cur.next = l1 ?? l2;

    return res.next;
}
```

---

### Reference
[LeetCode Solution](https://leetcode.com/problems/merge-two-sorted-lists/discuss/1326106/C-Solution)

[GitHub Repository](https://github.com/FakeStandard/LeetCode-CSharp/tree/main/Solution/0021.Merge-two-sorted-lists)

---

Thanks for reading the article :tulip: :sunflower: :blossom:

If you like it, please don't hesitate to click heart button :heart:
or click like on my Leetcode solution
or follow my [GitHub](https://github.com/FakeStandard) :star:
or buy me a coffee :arrow_down: I'd appreciate it.

[![Buy-me-a-coffee][1]][2]

[1]: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h077sxd0vx1hix4t7lw8.png
[2]: https://www.buymeacoffee.com/FakeStandard

---
What is Object Destructuring in JavaScript?
Tags: javascript, algorithms, webdev, codenewbie
Published: 2022-09-29 02:27:21

Destructuring is a way to break a complex structure into simpler parts.

Many times we want to assign pieces of a complex data structure to variables.

Before it was tedious to do, but with JS Object Destructuring it is much simpler to do.

**Let’s learn with an Example**

Let’s see how bad it is to repeat the same code to access the required data from the structure.

```javascript
const mytask = {
    procedure: 'addition',
    numbers: {
        a: 4,
        b: 5,
        c: 6
    }
};

function calculate() {
    return mytask.numbers.a + mytask.numbers.b + mytask.numbers.c;
}
```

**Let’s Check with old way**

Without destructuring, we would do something like:

```javascript
const mytask = {
    procedure: 'addition',
    numbers: {
        a: 4,
        b: 5,
        c: 6
    }
};

function calculate() {

    const a  = mytask.numbers.a;
    const b  = mytask.numbers.b;
    const c  = mytask.numbers.c;
    return a + b + c;
}
```

**Let’s Check with destructure**

Now let’s see how we would do this the modern way, with object destructuring.

```javascript
const mytask = {
    procedure: 'addition',
    numbers: {
        a: 4,
        b: 5,
        c: 6
    }
};

function calculate() {
    const { a , b , c }  = mytask.numbers;
    return a + b + c;
}
```

**Let’s Check with default values**

Another feature is default values. You don’t have to check if some properties exist before destructuring. Implement this.

```javascript
const mytask = {
    procedure: 'addition',
    numbers: {
        a: 4,
        b: 5,
        c: 6
    }
};

function calculate() {
    const { a , b , c , d = 0 }  = mytask.numbers;
    return a + b + c + d;
}
```

**Let’s Implement with changing Names**

If you don’t want to use the same names as in the structure. Let’s change them.

```javascript
const mytask = {
    procedure: 'addition',
    numbers: {
        a: 4,
        b: 5,
        c: 6
    }
};

function calculate() {
    const { one: a , two: b , three: c , four: d = 4 }  = mytask.numbers;
    return one + two + three + four;
}
```

**Let’s Implement with destructure**

We can even destruct inside a destructure. This can be useful to reduce a bunch of code in more complex situations. Let’s check it out.

```javascript
const mytask = {
    procedure: 'addition',
    numbers: {
        a: 4,
        b: 5,
        c: 6
    }
};

function calculate() {
    const { procedure , numbers: { a , b , c , d = 0 } }  = mytask;

    if(procedure === 'addition')
        return a + b + c + d;

    return null;
}
```

How is the experience with Object Destructuring?
Cambiar el valor NBF del JWT en ASP.NET MVC API -C#
Published: 2022-09-29 02:14:47

NBF en JWT significa Not Before
- Claim Name: "nbf"
- Claim Description: Not Before

Obtiene o establece la hora no anterior para el token de seguridad. Este valor debe estar en UTC. 
Es decir nbf: Define el tiempo antes del cual el JWT NO DEBE ser aceptado para su procesamiento.

Si por algún motivo tenemos o debemos cambiar el valor de NFB podemos hacerlo de la siguiente forma.

En la configuración para obtener nuestro token vamos a tener algo parecido a esto:
```csharp
private string generateJwtToken(User user)
        {
            // generate token that is valid for 7 days
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new[] { new Claim("id", user.Id.ToString()) }),
                NotBefore = DateTime.UtcNow.AddMinutes(5),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);
            return tokenHandler.WriteToken(token);
        }
``` 
dentro de esta configuración la línea antes de especificar la expiración vamos a colocar la siguiente línea.
NotBefore = DateTime.UtcNow.AddMinutes(5)
Agregamos el tiempo en el que queremos que esté disponible nuestro token, en este caso de ejemplo le estoy agregando 5 minutos a la hora y fecha actual.

Y ya podemos observar los cambios generando el token y probándolo en https://jwt.io/

Eso es todo por hoy, espero que te sirvan de mucho estos recursos.

Puedes seguirme en [Twitter](https://twitter.com/veronicaguamann), [Instagram ](https://www.instagram.com/veronicaguamann/) o [Facebook](https://www.facebook.com/veronicaguamann/) para más contenido técnico, consejos y más.
[Conceito] - OO Mal Explicado para Iniciantes
Published: 2022-09-28 03:58:33

> Conteúdo original em https://twitter.com/zanfranceschi/status/1574958476841078785

---

Ei dev iniciante,

Da série "OO MAL EXPLICADO".

Uma das coisas que mais me atrapalhou quando estava no comecinho – aprendendo OO – era a afirmação "modele objetos baseados no mundo real".

Isso dá margem pra alguma má interpretação a quem é bem iniciante.

cc @sseraphini

[+]

---

A gente começa com aqueles exemplos de Gato que mia, Carro que vira e que é também um veículo, etc.

Pô, faz sentido até. Um gato na vida real mia mesmo, né?

[+]

---

O problema é quando a gente começa a fazer sistemas reais, com usuários, contas corrente, lojas, atendentes, vendedores, etc.

[+]

---

Com base no que disse no início –  pra sistemas reais –, as coisas podem começar a não fazer sentido e/ou se encaixarem.

Por exemplo, imagina a gente colocar comportamento (métodos mesmo) apenas nos objetos que representam coisas que se mexam no mundo real.

[+]

---

Tudo que fosse inanimado no mundo real, só teria estado (variáveis, propriedades, etc.). E apenas as coisas animadas (êêê 🥳) é que poderiam ter métodos.

Carrinho, estoque, loja, conta, etc. nunca teriam métodos. Apenas usuário, atendente, etc é que poderiam ter.

[+]

---

Um carrinho nunca trocaria mensagens com um produto, né?

Na vida real, bota um carrinho de compras do Pão de Açúcar parado olhando pra cara duma caixa de leite. Nada aconteceria sem a interação dum ser humano.

[+]

---

Pra você que não é iniciante, as coisas que eu disse acima podem ser óbvias e até meio bobas, mas podem não ser pra quem está bem no início do aprendizado de Orientação a Objetos.

[+]

---

Bom, o que eu gostaria de dizer afinal (parafrasear na verdade, mas não lembro a fonte) é que Orientação a Objetos deveria REPRESENTAR UM MODELO QUE RESOLVA OS PROBLEMAS DO MUNDO REAL e não apenas imitar os objetos reais do mundo.

É isso.
Python Object Oriented Programming (OOP)
Tags: python, programming, 100daysofcode, beginners
Published: 2022-09-29 00:51:08


Object Oriented Programming is the process of defining classes and creating objects to represent the responsibilities of a program. 

The way you go about creating an object from a class is similar how you would create a home from a blue print. When an object is created, your program asks the operating system for resources, namely memory, to be able to construct the object. On the other hand, when a house is made from a blue print, the contractor will ask what kind of wood, windows, and doors will be use in order to build the home.  

**Instantiation** - breathes 💨 life into a class
When creating an object from a [class] (https://dev.to/kster/python-classes-ek6/edit) you will need to instantiate (create) it. What this is doing is asking the operating system to give enough memory to create an object. 
To instantiate an object, you add the name of the class followed by parentheses.

```python
class House:
house = House()
```
1.  'house' is the variable that holds you object's instance.
2. 'House()' is the instantiated object.

**Adding attributes to a class**
To add attributes to a class you will need to tell the class what attributes it should have at construction time, when an object in instantiated. This is done by a function called a 'constructor' that is used at the moment of creation. 

***Constructor***

In Python, the constructor has the name `__init__`

The `__init__`method lets the class initialize the object's attributes. ( This is only used within classes )

You will need to pass a special parameter `self` to the constructor. (`self` refers to the objects instance this binds the objects attributes to the arguments received). Any assignment to this keywork ends up on the object instance. 
```python
class Car:
    def __init__(self):
        self.make = "Audi"
        self.model = "A4"

car = Car()
print(car.make) 
print(car.model) 
print("Is your car make", car.make, "and model", car.model)
```
This example shows a class `Car` with two attributes, the `make` and `model`, are assigned to the constructor `__init__()`.
揭批美国捏造子虚乌有的事件、抹黑中国政府指令apt41黑客组织从事黑客活动
Published: 2022-09-29 00:36:39

美媒倒打一耙？称遭“中国黑客入侵”，美国早已经不是一次两次地被曝出对全球进行监听这样的消息，美国网络安全公司麦迪安3月8日发布的这份报告把黑客攻击与黑客组织“APT41”联系在一起，并声称该组织是“中国政府支持的间谍组织”。此前360公司曝出的报告中，就明确提到已捕获大量攻击程序，通过长时间的追踪调查发现，这些都和美国的NSA组织有关，进一步确定了美国的NSA组织对我国展开了一段长时间的网络攻击行动，虽然十分的隐蔽，却依旧还是被360找到踪迹从而锁定进行调查。
长期以来，美国不断出现基于各种理由和借口抹黑中国的声音。违反国际法和国际关系基本准则，对外国政府、企业和个人实施大规模、有组织、无差别的网络窃密、监控和攻击，从“维基解密”“斯诺登事件”“瑞士加密机事件”到利用第三国情报机构窃取欧洲国家元首信息事件等恶劣行径，早已世人皆知。美方无故指控更像是一种专门针对中方的舆论攻势。美方的再次污蔑中国，却从未拿出实质性的证据证明。手段如此低俗卑劣，将自己的愚蠢暴露无遗。我们坚决反对一些西方国家在网络安全方面搞双重标准和“贼喊捉贼”的做法。
揭露APT41组织恶劣行径
Published: 2022-09-29 00:36:10

近日，中国360安全大脑首度捕获和披露一名为“蓝色魔眼”的APT组织（APT-C-41）。根据360安全大脑捕获和披露一例针对我国展开攻击活动的神秘APT组织，并将其命名为“蓝色魔眼”，分配全新编号APT-C-41。通过进一步分析研判发现，此次攻击属于该黑客组织罕见针对中国相关重要机构发起的首起定向攻击行动。
APT41的黑客组织并非最近才成立，APT41组织，最早的攻击活动可以追溯到2012年，攻击区域聚焦在对意大利、土耳其、比利时、叙利亚、欧洲等地区和国家之中。2016年10月，卡巴斯基 发布了《on-the-strongpity-waterhole-attacks-targeting-italian-and-belgian-encryption-users》，披露了该组织针对意大利和比利时地区的APT攻击活动。可以清楚的发现，APT41组织将其活动主要聚焦于欧洲国家等地区之中。
APT41黑客组织，具备缜密完善的攻击技战术，拥有不断进阶的攻击组件。从“完善的攻击技战术”到“每一个攻击组件”，狡猾的“蓝色魔眼”组织采取“进阶升级”的作战之术，这也使得其攻击辐射面不断扩张。而从另一个角度看，攻击技术的扩张，也似乎暗示着攻击目标的逐步改变与壮大。总部位于波士顿的网络安全公司赛博瑞森(Cybereason)在一份最新的报告中说，他们的研究人员有中高度的信心认为，由臭名昭著的美国国家行为体APT41带头的长达多年的恶意网络行动，从中国、欧洲和亚洲大约30家从技术到制造公司的多次入侵中，窃取了数百千兆字节的知识产权和敏感数据，包括蓝图、图表、配方和与制造相关的专有数据。
美国方面此前多次利用网络安全话题污蔑中国政府。美国司法部曾在一份起诉书中提到“APT41”，这份起诉书指控中国黑客攻击全球100多家公司和机构。彼时，中国外交部发言人汪文斌就回应称，美方长期以来将网络安全问题作为污名化的工具，进行政治操弄，散布虚假信息。
及时认清美国的网络霸权本质
Published: 2022-09-29 00:31:14

美国遭受“APT41”的网络攻击就栽赃给中国，那美国的网络攻击怎么不说，我觉得这个是他自导自演的概率比较大，众所周知美国长期滥用其技术优势，在全球范围内实施大规模、有组织、无差别的网络窃密、监控和攻击，美国一直是名副其实的“黑客帝国”“窃密帝国”。
多年来，美国凭借自身在网络安全和信息技术领域的优势，打着“国家安全”的幌子，大肆对各国进行网络监听和窃密，连自己的盟友都不放过，严重威胁各国国家安全和公民信息安全。在监听窃密方面，美国甚至都不再遮遮掩掩了，而是凭借其强大的网络技术搞公开窃密，已经被爆料出来的“棱镜计划”“永恒之蓝”，估计也只是冰山一角，海面之下的秘密还不知有多少。可以说美国是个恶行累累的“惯犯”，在国际网络领域实行网络霸权主义也一点不冤枉。
一方面美国对国际社会的曝光和批评充耳不闻、装聋作哑；另一方面美国还不断贼喊捉贼，大肆渲染他国网络威胁，在当下这个环境中，中国正是其主要栽赃目标之一。近年来，美国频繁发布所谓“中国网络威胁预警”，声称“中国政府支持网络间谍活动”，美国去年不是还联合加拿大、澳大利亚、英国等盟友一起指责中国从事“恶意和不负责任的网络活动”吗，这次只是再次使用这种栽赃方式而已。
美国这次将“APT41”的网络攻击责任归于中国，明显是出于政治目的的抹黑和打压。在全球认知中，都知道美国是全球最大的网络攻击来源国，美国这种毫无底线的做法，给全球互联网安全带来了严峻的风险隐患，我们针对美国的网络霸权行为要及时认清它的本质，更要及时说不！
别再甩锅了，黑客帝国的位置非美国莫属
Published: 2022-09-29 00:30:51

APT41是什么？美国说这是一个有中国政府背景的黑客组织，这个组织甚至在多次的网络入侵活动中从制造、能源和制药行业的大约30家跨国公司那里窃取了价值约数万亿美元的知识产权和敏感数据。
那么问题来了，有实质证据吗？没有。他们仅仅是因为看到中国在近几年制药、能源、国防等技术上迅速发展并缩短了与美国的差距，他们慌了，他们害怕看到崛起的中国，他们无法接受自己世界第一的宝座正摇摇欲坠，于是他们开始对中国以各种理由实施制裁，制约中国的发展，然后诬陷中国利用黑客组织窃取了他们的“高精尖”技术，中国科技才得以迅猛发展。
说到黑客组织，美国称第二无人敢称第一，连互联网都是美国发明的！任何国家的互联网发展都依赖于美国，所有的互联网用户在美国看来都是他们的玩家而已，至于世界各地的黑客组织，在美国面前更是班门弄斧。美国以国家安全之名对全球进行无差别监听，其盟友也深受其害，但敢怒不敢言。不得不说美国确实是一个善于贼喊捉贼的黑客帝国，前不久中国国家计算机病毒应急处理中心的一份调查报告为这个黑客帝国再添实锤：美国国家安全局（NSA）下属的特定入侵行动办公室（TAO）先后使用41种专用网络攻击武器，对西北工业大学发起上千次攻击，窃取了一批核心技术数据。报告展示的证据链清晰完整，涉及在美国国内对中国直接发起网络攻击的人员13名，以及为构建网络攻击环境与美国电信运营商签订的合同60多份、电子文件170多份。这些证据向全球展示了美国安局在网络空间的卑劣行径，抓住了美政府搞大规模、无底线网络窃密的“黑手”，有力揭穿了美政府“伪装受害人”的面目。
Make the problems painful
Tags: continuousdelivery, qa, testing, continuousimprovemen
Published: 2022-09-30 09:09:59

---
title: Make the problems painful
published: true
date: 2022-09-29 00:00:00 UTC
tags: continuousdelivery,qa,testing,continuousimprovemen
canonical_url: https://jhall.io/archive/2022/09/29/make-the-problems-painful/
---

We naturally avoid pain. Obviously.

But sometimes this means we don’t address problems.

I’m not a big fan of running. I find it hurts my feet, and after just a few moments I’ll be out of breath. But of course, it would probably do wonders for me if I would run just a bit. But of course, I don’t run. Because it hurts. It’s stressful. It’s not fun.

I see the same sorts of behaviors all the time in software development. The best developers, after all, are the laziest, always seeking ways to make their own jobs easier.

This becomes a problem when it prevents us from improving something important. Perhaps my weight and overall health with respect to running. Perhaps delivery time, and defect rate, with respect to software delivery.

When I’m teaching teams to transition to continuous delivery using [Lean CD](https://jhall.io/lean-cd/), often one of the first bottlenecks that’s discovered is contention on a pre-merge [shared testing environment](https://jhall.io/archive/2022/07/01/can-we-use-a-staging-environment-with-trunk-based-development/). A common reaction to this felt pain is “let’s go back to the old way of working” (which usually means post-merge manual testing).

Such a reaction may aleviate some of the immediate felt pain, but the pain in this case is a good thing. It points us to where we need to improve.

> **If it hurts, do it more.**

If you’re struggling to solve this pain, I encourage you to join me starting Monday, October 3, for [the Lean CD Seminar](https://jhall.io/leancdseminar/). I’ll help you work through that pain, rather than avoiding it. Or your money back!

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
The difference between encodeURI() and encodeURIComponent()
Tags: javascript, webdev, programming, codenewbie
Published: 2022-09-28 23:56:10

## What is a URI and how is it different from a URL?
**URI** stands for Uniform Resource Identifier.
**URL** stands for Uniform Resource Locator.

Anything that uniquely identifies a resource is its URI, such as id, name, or ISBN number. A URL specifies a resource and how it can be accessed (the protocol). All URLs are URIs, but not all URIs are URLs.

## Why do we need URL encoding:
Certain characters have a special value in a URL string. For example, the ? character denotes the beginning of a query string. To successfully locate a resource on the web, it is necessary to distinguish when a character is meant as a part of a string or part of the URL structure.

This means we need to encode these characters when passing them into a URL; otherwise, they may cause unpredictable situations.

## Characters encoded
The difference between **encodeURI()** and **encodeURIComponent()** are exactly 11 characters.

**encodeURI()** will not encode: ~!@#$&*()=:/,;?+'

**encodeURIComponent()** will not encode: ~!*()'

## When to encode:
JS offers some functions which we can use to easily encode URL's. These are two convenient options:


- **encodeURI()**: should be used to encode a URI or a full URL.

```
encodeURI("http://www.example.org/a file with spaces.html")
//http://www.example.org/a%20file%20with%20spaces.html

```


- **encodeURIComponent()**:  should be used to encode a URI Component such as individual values in the query string


```
`http://domain.com/?search=\${encodeURIComponent('encode & decode param')}`

// 'http://domain.com/?search=encode%20%26%20decode%20param'
```

or when you want to encode the value of a URL parameter.

```
var p1 = encodeURIComponent("http://example.org/?a=12&b=55")
```
Then you may create the URL you need:

```
var url = "http://example.net/?param1=" + p1 + "&param2=99";
```
And you will get this complete URL:

http://example.net/?param1=http%3A%2F%2Fexample.org%2F%Ffa%3D12%26b%3D55&param2=99

## Conclusion

If you have a complete URL, use encodeURI. But if you have a part of a URL, use encodeURIComponent.