teleren/devto huggingface dataset:
BCFtools
Tags: genomics, vcf, software, bioinformatics
Published: 2022-11-03 16:40:29

Since I have started to work in bioinformatics, I faced a lot of issues with computational **_performances_** and **_memory usage_** for the execution of some tasks. In bioinformatics, generally, people work with large amount of data and **optimisation** is often required.

In case of genomics data one of the most used format is the [Variant Call Format (VCF)](https://samtools.github.io/hts-specs/VCFv4.2.pdf) 

After year of working, with this type of file, one of the best software for manipulating and modification of this format is [bcftools](https://github.com/samtools/bcftools). You can do basically everything with this CLI software on a VCF file.
 
The main tips I recommend are:
- Always convert your file from VCF to **BCF** format, this will increase at least x4 the execution time speed on all tasks. 
- The flag `—-threads` will not speed up the process, The multiprocessing is only applied for **compression** and **decompression**.
- When you have to execute multiple commands on your VCF file, such as: _Extraction_, _Annotation_ and _Normalisation_, ensure that you are using bcftools with `|` (pipe) and `-Ou` in order to avoid to overwrite intermediate files that will slow down your process. 

An example: 
`bcftools view -t chr2 input.vcf.gz -Ou |` 
`bcftools annotate —-rename-chrs alias.txt -Ou | `
`bcftools norm -m - -Oz -o output.vcf.gz —-threads 8`

 This command: 
1. _extract_ only chromosome 2 variants `-t chr2`
2. Change chromosome _prefix_ `—rename-chrs`
3. _Split_ multi-allelic sites into bi-allelic records and save the _output_ in VCF compressed format `-m - and -Oz`.
Letter of Recommendation Templates For University Applicants - SummerOkibe
Tags: career, education, productivity
Published: 2022-11-03 16:40:11

####   Original Tweet From  [@SummerOkibe](https://twitter.com/SummerOkibe)
{% embed https://twitter.com/SummerOkibe/status/1577605851489374209 %}
Letter of Recommendation Templates

⚠️ DO NOT PLAGIARIZE!!! It’s a crime.

📍University of California, Berkeley:
[https://gsi.berkeley.edu/media/sample-recommendation-letter.pdf](https://gsi.berkeley.edu/media/sample-recommendation-letter.pdf)

📍University of Michigan:
[http://www.press.umich.edu/pdf/9780472031887-appendixg.pdf](http://www.press.umich.edu/pdf/9780472031887-appendixg.pdf)

📍Pennsylvania State University:
[http://www.e-education.psu.edu/writingrecommendationlettersonline/sites/www.e-education.psu.edu.writingrecommendationlettersonline/files/Ch5pdf3.pdf](http://www.e-education.psu.edu/writingrecommendationlettersonline/sites/www.e-education.psu.edu.writingrecommendationlettersonline/files/Ch5pdf3.pdf)
 
AdSpace Here!!

📍Tips from the University of Calgary:
[http://www.ucalgary.ca/live-uc-ucalgary-site/sites/default/files/teams/9/final-reference-guide.pdf](http://www.ucalgary.ca/live-uc-ucalgary-site/sites/default/files/teams/9/final-reference-guide.pdf)

📍Tips from University of Western Ontario:
 [https://ssc.uwo.ca/PDF_folder/graduate/Writing%20Strong%20Reference%20Letters%20FSS_UWO.pdf](https://ssc.uwo.ca/PDF_folder/graduate/Writing%20Strong%20Reference%20Letters%20FSS_UWO.pdf)

📍Dickson College:
[http://www.dickinson.edu/download/downloads/id/3576/facultylettersofrecguide](http://www.dickinson.edu/download/downloads/id/3576/facultylettersofrecguide)

AdSpace Here!!

✘ 𝑇ℎ𝑒 𝐸𝑛𝑑． 

 Click [Here](https://www.knowledge-twitter.com/?utm_source=dev.to)  For More Posts Like This [https://www.knowledge-twitter.com](https://www.knowledge-twitter.com/?utm_source=dev.to)
Minimum Cost of Buying Candies With Discount
Tags: javascript, leetcode
Published: 2022-11-03 16:40:00

A shop is selling candies at a discount. For every two candies sold, the shop gives a third candy for free.

The customer can choose any candy to take away for free as long as the cost of the chosen candy is less than or equal to the minimum cost of the two candies bought.

For example, if there are 4 candies with costs 1, 2, 3, and 4, and the customer buys candies with costs 2 and 3, they can take the candy with cost 1 for free, but not the candy with cost 4.
Given a 0-indexed integer array cost, where cost[i] denotes the cost of the ith candy, return the minimum cost of buying all the candies.

 

Example 1:
Input: cost = [1,2,3]
Output: 5
Explanation: We buy the candies with costs 2 and 3, and take the candy with cost 1 for free.
The total cost of buying all candies is 2 + 3 = 5. This is the only way we can buy the candies.
Note that we cannot buy candies with costs 1 and 3, and then take the candy with cost 2 for free.
The cost of the free candy has to be less than or equal to the minimum cost of the purchased candies.

Example 2:
Input: cost = [6,5,7,9,2,2]
Output: 23
Explanation: The way in which we can get the minimum cost is described below:
Buy candies with costs 9 and 7
Take the candy with cost 6 for free
We buy cndies with costs 5 and 2
Take the last remaining candy with cost 2 for free
Hence, the minimum cost to buy all candies is 9 + 7 + 5 + 2 = 23.

Example 3:
Input: cost = [5,5]
Output: 10
Explanation: Since there are only 2 candies, we buy both of them. There is not a third candy we can take for free.
Hence, the minimum cost to buy all candies is 5 + 5 = 10.

```js
/**
 * @param {number[]} cost
 * @return {number}
 */
var minimumCost = function(cost) {
    let finalCost = 0;
    let totalCandies = cost.length;
    let sortedCost = cost.sort((a, b) => a - b);

  while (sortedCost.length !== 0) {
    let maxP1 = sortedCost.pop();
    let maxP2 = sortedCost.pop();
    finalCost = finalCost + (maxP1 && maxP2 ? maxP1 + maxP2 : maxP1 || maxP2);
    sortedCost.pop();
  }
    
    return finalCost;
};
```
Testing time with Golang
Tags: go, beginners, programming
Published: 2022-11-03 16:39:08

We can all agree that TDD is the bees knees, right? Something that can trip newbies up with golang is writing tests against a function that has a timeout.

Often when waiting for a result over a channel, it can make sense to add a timeout so we don't wait forever. Consider the following code

```golang
func doSomething(done chan struct{}) {
  // simulate an operation that takes too long
  time.Sleep(time.Second * 5)
  done <- struct{}
}

// We need to test this
func MyCode() {
  c := make(chan struct{})
  
  select {
  case <- done:
    // hurray!
  case <- time.After(time.Second * 5)
    // oh no!
}
```

Writing a unit test that exercises our timeout logic and doesn't take 5 seconds to run can seem difficult at first, but it is actually quite simple. We can use something called remote function overriding to declare a variable that we can override in our test.

```go
var after = time.After
```

And our switch statement changes like so

```go
select {
  case <- done:
    // hurray!
  case <- after(time.Second * 5)
    // oh no!
}
``` 

Now, in our tests, we can easily change the definition of after, to make it happen instantly

```go
func TestSomething(t *testing.T) {
  after = func(d time.Duration) <-chan time.Time {
    return time.After(0)
  }

  // your test code here
}
```
O que é o Advent Of Code?
Tags: programacaorecreativa, adventofcode, programming, recreationalprogramming
Published: 2022-11-03 16:35:58

## O que é?
Pra saber o que é o Advent Of Code, precisamos saber o que é o "advento".

### Advento
Advento é um período que antecede o Natal, do dia 27 de novembro ao dia 24 de dezembro. As suas origens não vem ao caso. O mais importante é entender uma prática que acontece nesse período.

Há uma tradição que consiste em guardar um docinho em cada uma de 24 caixinhas numeradas, cada uma representando um dia de dezembro antecedendo o Natal. A cada dia a dona desse calendário vai lá e pega um dos doces (que podem ser substituídos por toda sorte de coisa, inclusive cartas) e come. E nessa tradição que oi Advent Of Code se inspira. 

### Então o que é?
É uma série de desafios que vai do dia primeiro ao dia 24 de dezembro, um desafio por dia.

## Advent Of Code
Todo Advent Of Code começa com uma história sobre o Papai Noel se preparando para entregar os presentes de Natal. No entanto, algo acontece e é seu trabalho como desenvolvedora ajudar o bom velhinho a se livrar dos problemas e dar um Natal feliz a toda gente.

### Como participar?
Basta acessar https://adventofcode.com e se autenticar. Os problemas aparecem todo dia à meia-noite (UTC-5, ou seja, 2 da manhã para quem está no horário de Brasília) e ficam disponíveis pra sempre. Inclusive, se você quiser fazer um esquenta no de 2021, [fique à vontade](https://adventofcode.com/2021).

Ah, e o desafio é agnóstico no que diz respeito à linguagem. Além disso, não é necessário usar a mesma linguagem o desafio todo, então mandem ver!

## E você?
Eu pretendo participar esse ano, assim como participei ano passado. No entanto, pretendo completar dessa vez, nem que eu tenha ajuda de outras pessoas.
Vou começar com [APL](https://dev.to/feministech/voce-conhece-apl-24b6). Quando eu vir que não consigo mais continuar com essa linguagem porque eu não tenho tanta experiência com ela assim, vou tentar com alguma outra e depois arranjar uma solução em APL no discord que eu faço parte.

Pretendo também relatar isso por meio de vídeos no YouTube e artigos aqui.

Ansiosas?
How to add a disk on your vm
Published: 2022-11-03 16:18:52

- Go to your azure portal click on a running virtual machine that has been set up, check through your resource group locate or search for DISKS 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xndwgaixw1iarnlo65m1.png)
 
- click on create and attach new disk

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

- Give it a name and allocate the size(gib) you want to work with and the save after .

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

- Next we head to the remote desktop

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vrw63morq37fgtqx7mev.png)
- On the task bar click on search and type in "diskmgmt.msc"

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

- Right-click on disk 2 and click on new simple volume(then follow due processes)

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

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

- finish prompt 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sy475b0lbfvg1g0d05sb.png)
How do programmers say "I love you"? 🤔
Tags: programming, codenewbie, codedex
Published: 2022-11-03 16:04:42

**Note:** WRONG answers only! 

Feel free to reply in the comments or in the Twitter thread:

{% embed https://twitter.com/codedex_io/status/1587961941359730688 %}

That's all! Happy Thursday, Devs! 💖
Minified React error in production with Vite.js
Tags: vite, react, javascript, typescript
Published: 2022-11-03 16:02:24

At work I inherited a really old website running on React.

The code was good but by old i mean really old; last commit was 3 years ago and most of the code was 5-6 years old…

So I converted it to TypeScript and ripped out the old babel/webpack build system and installed Vite to handle all the builds.

Everything went pretty smoothly and I got the site up and running with no errors in development mode.

When going to production is when things went sideways. Some pages crashed with the following error:

```
error: Minified React error #130; visit https://reactjs.org/docs/error-decoder.html?invariant=130&args[]=object&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at vc (vendor.93c27df6.js:23)
    at d (vendor.93c27df6.js:23)
    at vendor.93c27df6.js:23
    at vendor.93c27df6.js:23
    at Ts (vendor.93c27df6.js:23)
    at ul (vendor.93c27df6.js:23)
    at ic (vendor.93c27df6.js:23)
    at tc (vendor.93c27df6.js:23)
    at ql (vendor.93c27df6.js:23)
    at zl (vendor.93c27df6.js:23)
```

Some quick googling led me to a [GitHub issue](https://github.com/vitejs/vite/issues/2139) showing me that I was not the only one experiencing this bug.

## Package problem number one
It seems that esbuild is checking for __esModule at runtime and rollup (which is used internally in Vite) is not.

So it will happen to any library that has an entry point with: `module.exports = require("./module");`

Since a file exported this way does not include the ‘magic string’ __esModule as checked by generate-exports.js it’s not converted correctly.

In my case I had two librarys acting up; react-datetime which was imported locally like this: `import DateTime from "react-datetime";` which worked fine in Vite dev but not production.

Props to [ntkoopman for the explanation](https://github.com/vitejs/vite/issues/2139#issuecomment-806416318).

## Solution
User [Haikyuu suggested](https://github.com/vitejs/vite/issues/2139#issuecomment-802981228) using the following solution which is what I used in the end.

```
import DT from "react-datetime";
// @ts-ignore
const DateTime = DT.default ? DT.default : DT;
Package problem number two
The second package with this issue was react-dropzone which in turn used the real culprit; attr-accept
```

Since the project used an old version (4.x.x, latest version is at the time of writing 14.x.x) and I got other issues upgrading to the latest version I could rule out a PR from me fixing it.

## Solution number two
Instead I used patch-package and postinstall to create a patch-file with the fix.

```
//from
import accepts from 'attr-accept';

//to
import A from "attr-accept";
const accepts = A.default ? A.default : A;
```

I how this can help if someone is stuck, and I hope it will be fixed soon because it is kind of a blocker for using Vite.js in production
Deploy React App in 10 minutes with AWS Amplify and Route 53
Tags: aws, serverless, react
Published: 2022-11-03 16:01:25

Hi there,

Let's learn how to deploy a react app with AWS Amplify. In this guide we would need the following:

1. A React App.
2. Git Provider (Github, Bitbucket, Gitlab, AWS CodeCommit, etc). 
3. Custom Domain (This is optional).

Obviously to deploy an app we need to have an app to deploy 😄.

After logging in to your AWS console search and click on AWS Amplify

![search for AWS amplify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/45i0j4p9681kbjcld5fq.png)

On the Amplify home screen click on get started.

![Getting started with AWS AWS amplify](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/red09mjlbl3cijan42ig.png)

You would now need to choose between amplify build or amplify hosting, choose the latter.

![Get started amplify hosting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3nj7yej2mxsy1xx09nug.png)

You have the option of selecting one of the git providers listed, There is also an option to use to upload code without a Git provider, but for the sake of this tutorial, we would be using GitHub.

![AWS ampify git provider image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yc26s4yrzvuvjxmmvuvw.png)
 
Clicking on GitHub will redirect you to GitHub for you to authorize AWS Amplify on your GitHub account, if that process is successful, you would see a screen like this


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


select the repository and then a default branch from the list and click next.
You would see a configuration screen, with a preview of the recommended changes, you don't need to do anything you can go ahead and click next to continue.


![AWS ampify configure page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9gdsyv4cxk5pdzl29cy3.png)

On the review page, click save and deploy

![AWS ampify review page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vqc7mx67a4qxkz3wq6pd.png)


In the next few minutes, we would have our app completely deployed on the app homepage, the page would be similar to the screen below and we would also have a random URL generated on amplifyapp domain.

![amplify complete deployment page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d8sygz4dv0n6ryqb40bt.png)

To add a custom domain, click on the domain management on the left side of the AWS Amplify dashboard, and then click on add domain as seen in the screenshot below.


![add custom domain](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lmd8x4csi2frx0mdwk6t.png)

[Add your domain using route 53](https://dev.to/aws-builders/route-domain-traffic-to-aws-with-route-53-2o3k), if that process was completed successfully, you should be able to find your domain in the search bar, do the simple configuration and save.

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


Wait for a few minutes for SSL to install on that domain. Congratulation, we have just deployed a react App with Amplify.
Javascript beginner help!
Tags: javascript, beginners, webdev, tutorial
Published: 2022-11-03 15:44:36

// Area of the first rectangle
const width1 = 10;
const height1 = 6;
const area1 =  width1 * height1;
 
// Area of the second rectangle
const width2 = 4;
const height2 = 9;
const area2 =  width2 * height2;
 
// Area of the third rectangle
const width3 = 10;
const height3 = 10;
const area3 =  width3 * height3;

Ok so I am beginner in JavaScript learning and am having a really hard time understanding 'functions' in JavaScript along with its 'return' keyword.
And above is an example for me to understand how exactly function is gonna make that code easy or in fewer steps.
I understand the functions are there as a shortcut or prevention of writing same sort of code for different things over and over again but if someone helps me create a function syntax and convert the above code into it, then that'll be easier for me to understand how function is created.

and this is how I tried so lemmi know why am not doing it right:

function areaOfRectangle(rec1, rec2, rec3){
  const area = width * height;
}
console.log(areaOfRectangle(10,6));

Regards, 
Saim Ali Nadeem
Paracetamol.test.js🧪| #10: Testea este código JavaScript
Tags: javascript, testing, spanish, webdev
Published: 2022-11-03 15:40:56

## **<center>Testea el siguiente código JavaScript</center>**
#### <center>**Dificultad:** <mark>Básico</mark></center>

```js
//arr.test.js
const frase = "Hormigas carnivoras bailarinas rojas";

test("frase contiene la palabra vegetarianas", () => {
  expect(frase).toContain("vegetarianas");
});
```

A. `❌ FAIL tests`
B. `✅ PASS tests`

Respuesta en el primer comentario.

---
Remove Digit From Number to Maximize Result
Tags: javascript, leetcode
Published: 2022-11-03 15:35:04

You are given a string number representing a positive integer and a character digit.

Return the resulting string after removing exactly one occurrence of digit from number such that the value of the resulting string in decimal form is maximized. The test cases are generated such that digit occurs at least once in number.

 

Example 1:

Input: number = "123", digit = "3"
Output: "12"
Explanation: There is only one '3' in "123". After removing '3', the result is "12".

Example 2:
Input: number = "1231", digit = "1"
Output: "231"
Explanation: We can remove the first '1' to get "231" or remove the second '1' to get "123".
Since 231 > 123, we return "231".

Example 3:
Input: number = "551", digit = "5"
Output: "51"
Explanation: We can remove either the first or second '5' from "551".
Both result in the string "51".

```js
/**
 * @param {string} number
 * @param {character} digit
 * @return {string}
 */
var removeDigit = function (number, digit) {
  let maxNumber = -Infinity;
  let index = 0;

  while (index < number.length) {
    if (number[index] === digit) {
      let newNumber = number.substring(0, index) + number.substring(index + 1);
      if (newNumber > maxNumber) {
        maxNumber = newNumber;
      }
    }
    index++;
  }
  return maxNumber;
};

removeDigit("1231", "1");
removeDigit("133235", "3");

```
Mocking Interface with jest-mock-extended
Tags: typescript, node, tdd, tests
Published: 2022-11-03 15:27:16

## Objetivo

Se você está cansado de mockar classes concretas, criar classes ou funções para usar de mock, essas duas funções abaixo vão te ajudar de uma maneira bem inteligente e prática.

## Situação

Precisamos testar um serviço que vai nos retornar uma lista de usuários.

## Fluxo do sistema

![flowsystem](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xs4rdpq9umcf63v2anxw.png)

## Testes

Muitas das vezes, criamos algum tipo de módulo/objeto para mockar dependências que seguem um "contrato" que são injetadas em um tipo de serviço. Quando usamos o princípio de Interface Segregation podemos mockar diretamente a **INTERFACE** usando duas funcionalidades do pacote _**jest-mock-extended**_ sem se preocupar com as dependências externas (ex: Repositórios concretos)

## Exemplo

Aqui temos uma interface que um repositório deve seguir.

```
import { UserDTO } from "../dtos/user";

export interface GetUsers {
    allUsers(): Promise<UserDTO[]>
}

```

E no nosso serviço vamos ter uma injeção de dependência seguindo essa interface (sem dizer quem é a classe concreta que representa isso, Inversão de Dependência).

```
import { UserDTO } from "../dtos/user";
import { ServiceProtocol } from "../protocols/service";
import { GetUsers } from "../repos/get-users";

export default class GetAllUsersService implements ServiceProtocol<null, Promise<UserDTO[]>> {
    constructor (private readonly usersRepository: GetUsers) {}

    async perform(): Promise<UserDTO[]> {
        const all = await this.usersRepository.allUsers()
        return all
    }
}
```

## Agora nos testes, a mágica =)

Repare que na variável **usersRepository** estamos utilizando o **MockProxy** na **interface** e não na classe concreta e entre os testes estamos falando para que a mesma seja mockada.

Com isso, não se preocupamos com classe concreta de repositório, apenas com a camada do serviço que precisa ser testada.

```
import GetAllUsersService from "@/domain/services/get-all-users-service"
import { mock, MockProxy } from 'jest-mock-extended'
import { GetUsers } from "./repos/get-users"

describe('GetAllUsersService', () => {
    let sut: GetAllUsersService
    let usersRepository: MockProxy<GetUsers>

    beforeAll(() => {
       usersRepository = mock()
    })

    beforeEach(() => {
        sut = new GetAllUsersService(usersRepository)
        usersRepository.allUsers.mockResolvedValue([
            {
                name: 'user 1',
                email: 'user 1',
                age: 'user 1',
                departament: 'user 1',
                created_at: new Date(),
                inative: false
            },
        ])
    })

    it('should call allUsers one time', async () => {
        await sut.perform()

        expect(usersRepository.allUsers).toHaveBeenCalledTimes(1)
    })
})
```

Valeu!

Referências: ![Manguinho](https://www.linkedin.com/in/rmanguinho/)

CÓDIGO-FONTE: https://github.com/Gabriel-Valin/clean-arch-express-based
The K8 Gateway API 🚀
Tags: kubernetes, istio, devops, tutorial
Published: 2022-11-03 15:20:26

If you follow the K8s world, you have probably heard that the Gateway API has been released as beta this past summer! 

As a superset of the Ingress API, the Gateway API provides a lot of power to teams, by letting non-admin folks get non-admin tasks completed.

If you wanted to try out the Gateway API, but weren't sure where to start, I created a simple and easy demo that walks through 3 common use cases, and you can see how simple it is!

The steps are outlined on [my repo here](https://github.com/xtineskim/gatewayapi-demo).

A rough overview is that you will deploy a sample application `httpbin`, and create a Gateway with the Istio Gateway Controller. 
Then you can try out 3 scenarios: 
1. Adding a new route to your `HTTPRoute`
2. Traffic shifting between v1 and v2 of your application
3. Trying a new Gateway! (this one is my personal fave)


Try it out, and leave any questions that you might have here! :)