teleren/devto huggingface dataset:
How to skip http interceptor in Angular App
Published: 2022-09-05 03:49:46

Angular Http Interceptor is used in many situations, such as adding header tokens, handling response errors, etc., but sometimes if you want to skip the interceptor layer intercepting request , I will expalin in this post how to deal with it using  following steps.

**Code**
HttpBackend

Interceptors sit between the `HttpClient `and the `HttpBackend `interface.

When injected, `HttpBackend `dispatches requests directly to the backend, without going through the interceptor chain.

**HttpClient  Code**

```
@Injectable()
export class HttpClient {
  constructor(private handler: HttpHandler) {}
    ...
}


```
 
`HttpBackend `interface


```
abstract class HttpBackend implements HttpHandler {
  abstract handle(req: HttpRequest<any>): Observable<HttpEvent<any>>
}
```

**Sample Code**
```
import {HttpBackend, HttpClient} from '@angular/common/http';
import {Injectable} from '@angular/core';

({
  providedIn: 'root'
})
export class SkipInterceptorService {
  private httpClient: HttpClient;
  constructor(private handler: HttpBackend) {
    this.httpClient = new HttpClient(handler);
  }
}
```

Create one manual `HttpClient`, and then `httpClient` this will not pass through the Interceptor layer, it's that simple

References
[Angular API - HttpBackend](https://translate.google.com/website?sl=auto&tl=en&hl=en&u=https://itnext.io/bypass-angular-interceptors-with-request-metadata-cf28061cda69)
[Bypass Angular Interceptors with Request Metadata](https://angular-io.translate.goog/api/common/http/HttpBackend?_x_tr_sl=auto&_x_tr_tl=en&_x_tr_hl=en)
Build markdown blog site by casual-markdown-blog
Tags: markdown, javascript, html, blog
Published: 2022-09-05 03:17:36

[casual-markdown-blog](https://github.com/casualwriter/casual-markdown-blog) is a handy solution to build blog site by markdown files and single index.html

No installation, just copy a single index.html, and config home page at index.md, then start write post in markdown! 

![blog layout](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ownrf7ne2ufcq8i3cuf.jpg)

It is very handy to build simple blog-site from markdown files, and host on static web hosting. For example,  

* Self-host on github: https://raw.githack.com/casualwriter/casual-markdown-blog/main/source/index.html
* Casual-Markdown's Blog: https://casualwriter.github.io/casual-markdown/blog
* Dark theme: https://casualwriter.github.io/casual-markdown/blog?theme=dark
* Dark (always): https://casualwriter.github.io/casual-markdown/blog?home=index-dark.md
* Nav at right-side: https://casualwriter.github.io/casual-markdown/blog?home=index-right.md 

### Usage Guide

simply copy [index.html](https://github.com/casualwriter/casual-markdown-page/blob/main/source/index.html) to web server, or fork [this repo](https://github.com/casualwriter/casual-markdown-blog). 

* config site at index.md (title, subtitle, header-color, navigation, etc..)
* start to write blog post using markdown
* to publish, just add the post in index.md by syntax 

```
* yyyy/mm/dd: [post-title](md-file) { #tags }
```

below is sample setup from [Sample Blog: index.md](https://raw.githubusercontent.com/casualwriter/casual-markdown-blog/main/source/index.md)

```
------------------------------------------------------------------title      : Casual-Markdown's Blog 
subtitle   : Simple is the best
nav-group  : featured, new-3, tags, months
nav-width  : 320px
css-header : background:linear-gradient(to bottom right, #06c, #fc0); color:white
menu       : 
   Home    : ?
   Github  : https://github.com/casualwriter/casual-markdown-blog
   Dark    : javascript:darkmode()
   About   : ?page=about.md
------------------------------------------------------------------
<style comment="additional style">
......
</style>

<div id="md-post">

home page in markdown syntax...

## Archive

* yyyy/mm/dd: [Post Title](md file)  { #tag1, #tag2 }
* yyyy/mm/dd: [Post Title](md file)  { #tag1, #tag2 }
...
* yyyy/mm/dd: [Post Title](md file)  { #tag1, #tag2 }

</div>

```



looking forward to your advice to help it getting better,  

thanks,
Quickly mocking a REST API
Tags: rest, http, mock, api
Published: 2022-09-05 02:21:07

For quick tests, there are some good public mock APIs available such as [httpbin.org](https://httpbin.org), [ReqBin](https://reqbin.com), or [Reqres](https://reqres.in).

But for a simple GET request my favorite is requesting some word on Wikipedia API (like ["pencil"](https://en.wikipedia.org/api/rest_v1/page/summary/pencil)):

```
https://en.wikipedia.org/api/rest_v1/page/summary/<some word>
```

Or a [random article](https://en.wikipedia.org/api/rest_v1/page/random/summary):

```
https://en.wikipedia.org/api/rest_v1/page/random/summary
```

Another quick but effective option for simple GET requests is creating a bunch of files on a folder then running a [HTTP server](https://docs.python.org/3/library/http.server.html) out of it with Python:

```
$ vim somedata.json
$ python3 -m http.server
Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ...
127.0.0.1 - - [04/Sep/2022 23:10:07] "GET /somedata.json HTTP/1.1" 200 -
```
Welcome to the new Vue Storefront Developer Portal
Tags: vue, portal, dx, education
Published: 2022-09-05 02:13:22

Have you ever wondered why educational material and documentation cannot have a nice DX?

Why can't companies create a concise experience throughout their material and make it easy to understand what is needed to start developing or simple tutorials to help your daily tasks?

> I also feel the same, and dang; this sucks 😟 - Heitor Ramon

That's why we, the community team at Vue Storefront, decided to create a developer portal to combine all the information you need to start developing with Vue Storefront and help you with those pesky questions, which sometimes require a lot of research and Googling.
We’d like to introduce the new Vue Storefront Developer portal, [https://developer.vuestorefront.io](https://developer.vuestorefront.io).

Our portal concept is a unique place for all the Vue Storefront developers to find answers, acquire new knowledge, get the latest news related to the Vue Storefront community and develop even faster with Vue Storefront.

Do you like open-source projects? So do we. We made the portal open-source and chose the best future-proof tech stack for a Vue ecosystem project. Using **Nuxt 3**, **nuxt-content**, and more.

As an open-source project, you are more than welcome to participate in the decisions regarding the roadmap, features, enhancements, translation, and much more. We want to create a friendly and welcoming place for our community members.

Right now, our portal has a documentation hub , an easy link to our community, and a video section. All to help our developers find the information they need, quickly.There is more to come, full cross documentation search, certifications and badges, an integrated community area, user area, events area, a single stop for all the docs (_yes, all the docs will be available in the portal)_, and much more.

As an open-source project, we are happy to have your participation in the decisions and coding of the portal. The portal being open-source is a way for our community to empower it and choose what is best for it.

There will be an open roadmap with the features planned by the community team, but we are always available for new features, enhancements, fixes, and more. Check the code of the portal at [https://github.com/vuestorefront/developer.vuestorefront.io](https://github.com/vuestorefront/developer.vuestorefront.io).

Come visit our portal, and let's share this amazing news with all of your developer friends and community.
A Brief Introduction To Images
Tags: images, pixel, color
Published: 2022-09-05 02:02:26

## What are Images?
Images are the representations of the external form of objects or person...well that's true but they are much more than that. They are 3-Dimensional representations that consist of pixels(the smallest unit). The three dimensions are:
1. The Width 
2. The Height
3. The Channel / Depth

There are two ways images are compressed: 

###Lossless Compression 
Lossless Compression is a type of compression that allows the original data(images) to be perfectly reconstructed from compressed data with no loss of data(pixels). Examples of images that use lossless compression are PNG, SVGs. No single data is lost in lossless compression, all pixels of the image are reconstructed back. It's a garbage in, garbage out process. This type of compression is good for image quality but it does not filter out the noise(unwanted data). Images that use lossless compression are usually large in size. Huffman and LZ77 are some of the algorithm used for lossless 

###Lossy Compression 
In this type of compression the data(pixels) in the images is removed and not restore to its original form after decompression. An example is JPEG, which is one of the most used image format. [Discrete Cosine Transform](!https://www.geeksforgeeks.org/discrete-cosine-transform-algorithm-program/) is a very popular way of compressing and filtering images. 

This article is just a brief introduction about Images and doesn't have enough information about the topic but if you wish to research further here are some articles that might help 

[Discrete Cosine Transform] (https://www.geeksforgeeks.org/discrete-cosine-transform-algorithm-program/)
[Lossless Compression] (!https://en.wikipedia.org/wiki/Lossless_compression)
Sobre a propriedade display
Tags: css, display, inlineblock, beginners
Published: 2022-09-05 02:00:55

Para entender a propriedade `display`, primeiro é preciso saber que tudo no CSS e Html são caixas. 
Ao digitar uma palavra por exemplo, o entorno do que foi escrito é um retângulo. Se teclo "Z", a letra é um elemento da área em geral invisível. Portanto, `display` é a caixa ou área que circunda um elemento.
É possível modificar o comportamento padrão do `display` e ter o resultado desejado, pelos valores `inline`, `block` e `inline-block`;

### Inline
Os elementos ficam em sequência e na mesma linha, alinhados à esquerda do `display`. Ao aplicar o estilo `inline`, a `tag` comporta-se como uma palavra. Isso significa que não há possibilidade de modificar altura e largura da área. Com esse valor, o conteúdo define o tamanho da caixa.

Vantagens
- mesma linha;
- `height` e `width` fixos;
- alinhamento customizável;
- `tag` como palavra;
- tamanho com base no conteúdo;

### Block
É o oposto da `inline`. 
Por padrão o valor `block` ocupa toda a linha, mesmo com outra `tag` definida como `inline`. A largura e o tamanho podem ser modificados. Quando não especificado a `width` é definida pela `tag` parent e a `height` pelo conteúdo.

Vantagens
- ocupa toda a linha;
- altura e largura configuráveis;
- `width` 100% da `tag` parent (padrão);
- `height` 100% do conteúdo (padrão);

### Inline-block
O melhor das tags anteriores. 
Herda comportamento de palavra, fica ordenado na mesma linha com outros elementos e tags inclusive, a largura e tamanho são configuráveis.

Vantagens
- mesma linha;
- `tag` como palavra;
- altura e largura modificáveis;
- `width` 100% da `tag` parent (padrão);
- `height` 100% do conteúdo (padrão);
Reverse Singly Linked List
Tags: javascript, leetcode
Published: 2022-09-05 01:53:32

Recursion 1
```js
var reverseList = function (head) {
  let previous;
  return reverse(head, (previous = null));
};

const reverse = (head, previous) => {
  if (head === null) {
    return previous;
  }
  let next = head.next;
  head.next = previous;
  return reverse(next, head);
};
```
Recursion 2
key point for below solution
 -- at **last** we have to connect it to head for for that we will need head reference & we knw head.next & next of head can become head now.


```
var reverseList = function(head) {
    
const reverseR = (head) => {
   if (head === null || head.next === null) {
    return head;
  }
  let last = reverseR(head.next);
  const rest_tail = head.next;
  rest_tail.next = head;
  head.next = null;
  return last;
}
return reverseR(head);
    
}
```

Iterative 
```js
var reverseList = function (head) {
  let current = head;
  let previous = null;

  while (current !== null) {
    const tempNode = current.next;
    current.next = previous;
    previous = current;
    current = tempNode;
  }
  return previous;
};
```
React Native PressableHighlight
Tags: reactnative, android, ios, mobile
Published: 2022-09-05 01:32:59

What if you want to use something similar to TouchableHighlight on both iOS and Android with a ripple effect? Using the Pressable component is not enough, so we can create a PressableHighlight component that handles both a background highlight change for iOS and a ripple effect for android.

You can find the code on this [snack](https://snack.expo.dev/@nyashanziramasanga/pressablehighlight-example)

![PressableHighlight onPress event](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1387jvgtn71dzisw1gsc.gif)

**Requirements:**

- For iOS a background highlight onPress
- For Android a ripple effect

**PressableHighlight Component**


```javascript
export default function PressableHighlight(props) {
  return (
    <Pressable
      android_ripple={{
        color: '#676B5F',
      }}
      style={({ pressed }) => [
        Platform.select({
          ios: {
            backgroundColor: pressed ? 'rgba(0,0,0,0.1)' : 'transparent',
          },
        }),
        props.style,
      ]}>
      {props.children}
    </Pressable>
  );
}
```

The android_ripple takes an object which accepts the ripple color, the onPress event can be used to change the backgroundColor which in this case is a black color with an opacity of 10% when pressed and transparent when inactive.
How to implement Login with Logify in React
Tags: react, javascript, sso, login
Published: 2022-09-05 00:11:42

**Easiest and free way to add login service to any project.**
{% embed https://youtu.be/EnCJuliVq6k %}
**Step 1: Get a domain key from [logify](https://logify.id)**
Follow this [article](https://dev.to/logify/how-to-get-a-domain-key-at-logify-httpslogifyid-34o7) to get your Domain Key if you do not already have it.

**Step 2: Setup React Project**
Create new folder with name `react-logify-basic`


Open `react-logify-basic` in visual studio code


Run `git clone https://github.com/logify-id/react-logify-basic.git .` in terminal to clone the repository. Github Repo


Install all dependencies with `npm i`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k3lz6hmzrukk2p3ivbxg.png)
Create `.env` file


Paste `REACT_APP_LOGIFY_DOMAINKEY = YOUR_DOMAIN_KEY`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zdn7rao6c8vgwj71xb9j.png)
**Step 3: Run the Project**
Start your project with `npm start`

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

If I click on the login button, I can see login screen

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wreav0yryqihyqtxrrj6.png)
After login, I can see my details.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/56i73krbxm3x8ioseym3.png)
Merge SOMETHING every day
Tags: trunkbaseddevelopmen, continuousintegratio, featurebranches, pullrequests
Published: 2022-09-25 09:54:51

---
title: Merge SOMETHING every day
published: true
date: 2022-09-05 00:00:00 UTC
tags: trunkbaseddevelopmen,continuousintegratio,featurebranches,pullrequests
canonical_url: https://jhall.io/archive/2022/09/05/merge-something-every-day/
---

Making [continuous integration](https://jhall.io/glossary/#ci) and [trunk-based development](https://jhall.io/glossary/#tbd) habits can be a challenge. I’ve never met anyone (myself included) who was able to switch from the habit of weeks-long feature branches to continuous integration over night.

Changing habits like that takes a while. The hardest part, at least in my experience, is learning to think about “large” features more incrementally and interatively. But there are a few tricks I’ve found that can help learn to think in this new way.

One of the most powerful ones is to determine to merge _something_ every day, even if you still have a long-lived feature branch.

I don’t think I’ve ever seen a large feature branch that couldn’t have _something_ cherry-picked out of it, and merged early. And usually when that’s possible, it’s also desirable. First, here’s how it works:

Imagine you have a large feature you’re working on, but it’s not complete. In the process of building your feature, you discover a pre-existing bug, or you rename an existing variable, or maybe you add some simple utility function to help calculate π to exactly 8,324 digits. Any of these could easily be merged into your mainline codebase, without the rest of your feature, and without risk of breaking anything. In fact, in the case of the bug fix or refactor, they almost certainly _should_ be merged first, to reduce the risk if your feature is later reverted.

So here’s what you do (assuming you’re using git):

1. In your working copy, checkout the latest version of `main`

2. Create a new branch for your cherry-picked bug/refactor/utility

3. Apply just your single change to the new branch.

4. Push the new, micro branch up to your central server for review and merge.

5. Once merged, rebase\* your large feature branch on top of the new version of `main. Your large feature branch is now a bit smaller than it was before, because it no longer contains your small change. And what’s more: customers, and other developers, can immediately benefit from that change, and you’ll never have to resolve a merge conflict related to it again!

\*If rebasing scares you, it would be good to spend some time learning how to do effective rebasing, as in the long run it’s much less error-prone than merging from `main` into your working branch. But that’s a topic for another day.

* * *
_If you enjoyed this message, [subscribe](https://jhall.io/daily) to <u>The Daily Commit</u> to get future messages to your inbox._
Chrome插件开发 - Creating the TurboReader browser extension
Published: 2023-08-13 02:12:41

---
title: Chrome插件开发 - Creating the TurboReader browser extension
published: true
date: 2022-09-05 00:00:00 UTC
tags: 
canonical_url: https://manon.icu/blog/translate/build-chrome-extensions/creating-the-turboreader-extension
---

本章学习如何创建`turboReader`插件，如下图：

<video
  src={
    'https://cdn.jsdelivr.net/gh/manonicu/pics@master/uPic/turboreader_ghlbnk.webm'
  }
  autoPlay
></video>

## 初始化项目

```bash
mkdir turboReader && cd turboReader
```

添加`manifest.json.json`

```json
{
  "manifest_version": 3,
  "version": "1.0",
  "name": "TurboReader",
  "description": "Become a faster reader with TurboReader",
  "action": {},
  "icons": {
    "48": "icons/icon-48.png"
  },
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["activeTab", "scripting"]
}
```

添加`background.js`，获取活动标签，并注入名为`turboMode`的函数。

```js
const turboMode = () => {
  // do something
}

chrome.action.onClicked.addListener(async () => {
  const [tab] = await chrome.tabs.query({active: true, currentWindow: true})
  chrome.scripting.executeScript({
    target: {tabId: tab.id},
    function: turboMode
  })
})
```

## 创建函数

首先获取页面内所有段落

```js
const paragraphs = document.getElementsByTagName('p')
```

判断当前是否是阅读模式

```js
const isTurboMode = document.body.classList.contains('trms')
```

遍历并处理段落

```js
for (const paragraph of paragraphs) {
  if (isTurboMode) {
    // 阅读模式已开启就返回当前段落
    paragraph.innerText = paragraph.innerText
  } else {
    // 阅读模式未开启，返回处理后的段落
    paragraph.innerHTML = paragraph.innerText
      .split(' ')
      .map((word) => {
        const length = word.replace(/[^a-zA-Z0-9]+$/, '').length
        const boldLength = length === 1 ? 1 : Math.floor(length / 2)
        return `<strong>${word.substring(
          0,
          boldLength
        )}</strong>${word.substring(boldLength)}`
      })
      .join(' ')
  }
}
```

在循环外部加入判断

```js
isTurboMode
  ? document.body.classList.remove('trms')
  : document.body.classList.add('trms')
```

完整代码

```js
const turboMode = () => {
  const paragraphs = document.getElementsByTagName('p')
  const isTurboMode = document.body.classList.contains('trms')
  for (const paragraph of paragraphs) {
    if (isTurboMode) {
      paragraph.innerText = paragraph.innerText
    } else {
      paragraph.innerHTML = paragraph.innerText
        .split(' ')
        .map((word) => {
          const length = word.replace(/[^a-zA-Z0-9]+$/, '').length
          const boldLength = length === 1 ? 1 : Math.floor(length / 2)
          return `<strong>${word.substring(
            0,
            boldLength
          )}</strong>${word.substring(boldLength)}`
        })
        .join(' ')
    }
  }

  isTurboMode
    ? document.body.classList.remove('trms')
    : document.body.classList.add('trms')
}
```

## Source Code

[【Source Code】](https://github.com/rebelchris/turbo-reader)
Leetcode Diary: Unique Email Addresses
Tags: javascript, leetcode, algorithms
Published: 2022-09-04 23:48:18

https://leetcode.com/problems/unique-email-addresses/submissions/

this is a good question to start with if you haven't had leetcode style interviews or it's been a while since you leetcoded.

the problem is rather simple, to process email strings to eliminate certain characters. You should follow three rules:
1.) leave the parts after @ sign untouched
2.) ignore the parts after + but before @ 
3.) remove all dots
the return value is how many unique emails are there after processing. 

below is the pseudo for the easy version:

```
pseudo:
emailsSet = new Set()

for each email in emails
parts = email.indexOf("@")
local = parts[0]

noPlus = ignorePlus(local)
noPlusNoDot = removeDots(local)

returnEmail = noPlusNoDot + parts[1]

emailsSet.add(returnEmail)
return eamilsSet.length();
```

If you are aiming for an entry-level job. This is something you should be able to implement in full code without much problem. 

If you are more advanced than entry, think of an answer without using javascript built-in functions but the substring(). 

the thinking is like this:
Q: is there any complex rule that need to refer to previous characters?
A: no, okay then maybe all we need is a loop
Q: how do we loop through?
A: you provide conditions for add or ignore character
Q: is that all there it is?
A: well, you have to be careful about the + and @ conditions. You ignore until you hit the @ after hitting +.
Q: how do you order the conditions, does it even matter?
A: it matters, because once you hit @, you just append everything, so that's one good reason condition ordering matter. 

Additionally, once you hit a +, you do not add to the string, so adding to the string must be the final default condition. 

With that in mind you should be able to come up with a code like this: 

```
var numUniqueEmails = function(emails) {
    const emailsSet = new Set();
    for (let email of emails) {
        let finalString = ''
        let facedPlus = false;
        
        for (let i=0; i < email.length; i++) {
            const current = email[i];
            if(current === '@') {
                finalString += email.substring(i)
                break;
            } else if (current === ".") {
                continue;
            } else if (current === "+") {
                facedPlus = true;
                continue;
            } else if (facedPlus) {
                continue;
            } else {
                finalString += current;
            }
        }
        
        emailsSet.add(finalString);
    }
    
    return emailsSet.size
    
}
```
Please let me know if I missed something that's unclear, thank you!

Please hit me with a follow if you’d like to see more content, I’ll update irregular but somewhat frequently.

If you’d like a 1-1 conversation with me going over your resume or your career trajectory in general, please reach out to me at https://www.fiverr.com/kevtseng

Socials:
www.twitter.com/KevinTseng1991
https://www.linkedin.com/in/kevintseng1991/