teleren/devto huggingface dataset:
TypeScript type guard for empty JSON object
Tags: typescript, typeguard, optionalparams, graphql
Published: 2023-02-06 17:41:59

---
title: TypeScript type guard for empty JSON object
published: true
date: 2023-02-06 13:55:38 UTC
tags: TypeScript,Typeguard,Optionalparams,GraphQL
canonical_url: http://dfberry.github.io/2023.02.04-github-graphql-commit-history-with-typescript
---

Commit history for a repo on GitHub can be optional, if there are no commits yet. The TypeScript SDK created by the [GraphQL CodeGen](https://www.npmjs.com/package/@graphql-codegen/cli) represents this optionality is represented with an empty object, null, or undefined. If a commit is present, its represented as a nested JSON object with more optional parameters.

<pre>
```
declare var x: {} | 
    null | 
    undefined | 
    {'a': { ... more optional params } }
```
</pre>

<button type="button" aria-label="Copy code to clipboard" title="Copy"><span aria-hidden="true"><svg viewbox="0 0 24 24"><path d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z"></path></svg><svg viewbox="0 0 24 24"><path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"></path></svg></span></button>

The empty JSON object, `{}`, is tricky in JavaScript. There are several examples of testing for an empty object but they generally don't work as type guards in TypeScript for type safety.

## Type guard with `in`[​](#type-guard-with-in "Direct link to type-guard-with-in")

After asking on [StackOverlow](https://stackoverflow.com/questions/75278401/how-do-i-get-type-target-history-from-github-graphql-on-defaultbranchref) and getting no response, I reached out to my local TypeScript expert for help.

He helped boil the issue down to the type shown in the previous code block with a type guard using the `in` keyword:

<pre>
```
if (x !== null && x !== undefined && "a" in x) { 
    // no null 
    // not undefined 
    // x has property 'a' so it isn't empty 

    console.log(x.a);
}
```
</pre>

<button type="button" aria-label="Copy code to clipboard" title="Copy"><span aria-hidden="true"><svg viewbox="0 0 24 24"><path d="M19,21H8V7H19M19,5H8A2,2 0 0,0 6,7V21A2,2 0 0,0 8,23H19A2,2 0 0,0 21,21V7A2,2 0 0,0 19,5M16,1H4A2,2 0 0,0 2,3V17H4V3H16V1Z"></path></svg><svg viewbox="0 0 24 24"><path d="M21,7L9,19L3.5,13.5L4.91,12.09L9,16.17L19.59,5.59L21,7Z"></path></svg></span></button>
O que é DevSecOps?
Tags: veracode, beginners, tutorial, security
Published: 2023-02-06 13:49:11

DevSecOps é uma abordagem para garantir a segurança na entrega de software. É uma combinação de desenvolvimento de software (Dev), segurança (Sec) e operações (Ops). A ideia é integrar as práticas de segurança desde o início do processo de desenvolvimento, em vez de tratá-las como uma adição tardia ou um passo separado.

Isso significa que as equipes de segurança, desenvolvimento e operações trabalham juntas ao longo de todo o ciclo de vida do software, desde a concepção até a entrega e manutenção, para garantir que as aplicações sejam seguras, escaláveis e de alta disponibilidade.

A implementação bem-sucedida de DevSecOps requer colaboração e comunicação eficazes entre equipes, automação de processos, integração de ferramentas de segurança em todas as etapas do processo de entrega de software e treinamento para garantir que todos os membros da equipe estejam cientes das práticas de segurança necessárias.

O objetivo de DevSecOps é acelerar a entrega de software de forma segura e eficiente, sem comprometer a segurança das aplicações e dos dados.

Para saber como a Veracode e a M3Corp podem lhe ajudar em seu programa de segurança, entre em [contato](https://www.m3corp.com.br/contato/).
AspNet Core Web API Basics to Advanced Part1
Tags: dotnet, csharp, webdev
Published: 2023-02-06 13:47:33

**What is Web API.**
API stands for Application Programming Interface, which in simple terms allows two applications to talk to each other. 
![AspNet Core Web API ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nywdqjvi3rkcphskfati.JPG)

**ASP.NET Web API** is Microsoft .Net framework for building HTTP services that can be accessed from any client such as browsers, desktop applications and mobile devices. ASP.NET Web API can be used to build both RESTful and SOAP services. 

**ASP.NET Web API Core** ASP.NET Core is an open-source, cross-platform framework for building modern, cloud-based web apps and we can chose whatever platforms we want to build them on. We can build and run ASP.Net Core applications on Windows, macOS or Linux. Some of the benefits we get when working with ASP.Net core are:

1. It is a cloud-ready. 
2. Comes with Built-in dependency injection. 
3. Very lightweight.
4. High-performance and modular HTTP request pipeline.
5. We can host ASP.Net Core applications on IIS, Nginx, Apache and Docker.

**Let us build our first Web API in ASP.NET Core5**
To build a project select create a new project.
![AspNet Core Web API ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wa7y5lqv7lmogdqynuc9.JPG)

Select ASP.NET Core Web API
![AspNet Core Web API ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8qa7kmsxpx0fhogv9c7.JPG)

Select where we want to save it.
![AspNet Core Web API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/112uk9d5mfi096irwm34.JPG)

For the last step, select additional information. I am leaving everything as default but in future series we will investigate other options.
![AspNet Core Web API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g98921igrff43jsl839b.JPG)  

Now build and compile your Web API and you should see your WeatherForecast Endpoint.
 ![AspNet Core Web API](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s0158qge0otpwouoawtl.JPG)

 [AspNet Core Web API Part 2 Database Context >>](https://dev.to/scorpio69/web-api-net-core-basics-to-advanced-part2-db-dco)
How to compile Arduino-ESP32 core with ESP_LOGx
Published: 2023-02-06 13:42:26

**Why?**
In Arduino IDE you can set the core debug level, however, this only sets debug level for files in Arduino-esp32 but the core which is distributed as a precompiled library in .sdk files, located in your Arduinio installation folder, is unaffected - the debug level remains the default “error”.

**What?**
If you want to change the core code or debug level, you need to clone the repo: [https://github.com/espressif/esp32-arduino-lib-builder](https://github.com/espressif/esp32-arduino-lib-builder), make the modifications there, compile and apply the changes (automatically by the build script).

**How?**
There are 2 basic approaches. Both of them involve editing file `esp32-arduino-lib-builder/configs/defconfig.common`.

The first option is to edit the file directly and then build.
Later you can `git restore configs/defconfig.common` to go back.

The second option is to copy the file `cp configs/defconfig.common configs/defconfig.debug`, edit the debug version and then compile.

Open the defconfig file
`vim configs/defconfig.common` or `vim configs/defconfig.debug`

Edit `line 45` containing by default `CONFIG_LOG_DEFAULT_LEVEL_ERROR=y` to one of the following lines depending on your desired log level:
```
CONFIG_LOG_DEFAULT_LEVEL_NONE=y # No output
CONFIG_LOG_DEFAULT_LEVEL_ERROR=y # Errors - default
CONFIG_LOG_DEFAULT_LEVEL_WARN=y # Warnings
CONFIG_LOG_DEFAULT_LEVEL_INFO=y # Info
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y # Debug
CONFIG_LOG_DEFAULT_LEVEL_VERBOSE=y # Verbose - All of the above
```
Then simply build the libs for all SoCs or one specific SoC. Note that building for all SoCs takes a lot of time, so if you work only with one specific SoC, build only for that one.
If you have copied the defconfig file and the debug settings are in file `configs/defconfig.debug` add flag `debug`
example : `./build.sh debug`
Build all SoCs: `./build.sh`
Build only selected SoC: `./build.sh -t <soc>`
The exact text to choose the SoC:
- esp32
- esp32s2
- esp32c3
- esp32s3
Example: `./build.sh -t esp32`
A wrong format or non-existing SoC will result in the error `sed: can't read sdkconfig: No such file or directory`
NightCrit v2.0 (release 1.0)
Tags: unity3d, art, vr
Published: 2023-02-06 13:34:03

I've completed the first iteration of NightCrit v2.0 in it's current form several days ago:

https://nightcrit.com


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

There were a number of obstacles that had to be overcome:

## How will Unity render the output of my project?

It is important to me that NightCrit is rendered out so that it is available on the web. A VR-only environment was too limiting for what I wanted.

I was looking for releasing this project to the largest audience possible, while still attempting to be as immersive as possible. I looked into WebGL and this seemed like it would be the best approach.

## How do I host this Unity WebGL project?

I already had the domain and a S3 bucket set-up for the Vue project that was NightCrit v1.0. I replaced the contents of that project with the output from Unity.

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

The biggest headache was getting errors on the `index.html` around the `Content-Encoding:` not being set correctly. For those that stumble onto this issue in the future (including myself) and are wondering what needs to be updated in order to have `.gz` data fetched correctly from S3, this is what needs to be accomplished:

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

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

The `Content-Encoding` _needs_ to be set on the S3 bucket object itself.

## Future Plans

There are a few other number of things I wanted to accomplish. The most important thing is that the bones of this project seem to be there; and because of that I felt compelled to publish what I had.

There will be further updates in trying to make the models better and adding more atmospheric elements to get the feeling that I had in the dream down.

What's important is to try and show people what I've accomplished thus far.

Thank you for reading.
The Top 5 Stanford University Free Courses. You Shouldn’t Miss .
Tags: webdev, javascript, beginners, tutorial
Published: 2023-02-06 13:33:11

Stanford University’s Free Courses Program The Top 6 courses that you must enroll in are listed below.

Live Link : [Click Here](https://ziontutorial.com/the-top-5-stanford-university-free-courses-you-shouldnt-miss/)

I hope all is well with you. In today's article, we'll talk about the best 5 Stanford University courses. those are completely cost-free. The top 5 free courses are shown below along with a link. The Top 5 Free Courses at Stanford University. Because this course is completely free, you shouldn't miss it.
Tips To Stop At-Risk Customers From Churning
Tags: startup
Published: 2023-02-06 13:31:33

Churn is a significant issue for businesses because losing customers can lead to decreased revenue and decreased market share.

The first tip is to identify at-risk customers early. Businesses should use data and analytics to identify customers who are likely to leave, such as those who have decreased their usage or stopped purchasing altogether.

The second tip is to proactively reach out to at-risk customers. This can be done through targeted email campaigns, phone calls, or in-person visits. The goal of these outreach efforts is to understand why the customer is at risk of leaving and to address their concerns.

The third tip is to offer incentives to retain at-risk customers. This could include special promotions, discounts, or loyalty programs. The goal is to make it more attractive for the customer to stay with the business rather than switch to a competitor.

The fourth tip is to provide excellent customer service. This includes being responsive, friendly, and helpful. By treating customers well and addressing their concerns, businesses can reduce the likelihood of customers leaving.

In conclusion, reducing customer churn is crucial for the long-term success of a business. By identifying at-risk customers early, proactively reaching out to them, offering incentives, and providing excellent customer service, businesses can reduce the likelihood of customers leaving and increase customer retention.

**[Read more](https://churnfree.com/blog/4-tips-to-stop-at-risk-customers-from-churning/)**
Github action that generate chat SVG with current date and weather
Tags: github, bash, shell, tarikmanoar
Published: 2023-02-06 13:26:54

```
name: Generate chat bubble SVG

on:
  schedule:
    - cron: '0 0 * * *'

env:
  API_KEY: ${{ secrets.WEATHER_API_KEY }}

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
    - name: Checkout repository
      uses: actions/checkout@v2

    - name: Set up Node.js
      uses: actions/setup-node@v2
      with:
        node-version: 14

    - name: Install dependencies
      run: npm ci

    - name: Get current date and weather
      run: |
        date=$(date +"%B %d, %Y")
        weather=$(curl "http://api.openweathermap.org/data/2.5/weather?q=San Francisco,us&appid=${API_KEY}&units=imperial" | jq '.main.temp')
        echo "::set-env name=DATE::$date"
        echo "::set-env name=WEATHER::$weather°F"

    - name: Generate chat bubble SVG
      run: node generate-svg.js "$DATE" "$WEATHER"

    - name: Commit and push changes
      uses: actions/github-script@0.11.0
      with:
        script: |
          git config --local user.email "github-actions@example.com"
          git config --local user.name "GitHub Actions"
          git add chat-bubble.svg
          git commit -m "Update chat bubble with current date and weather"
          git push

```


In this example, the Action runs on a schedule (daily at midnight) and uses a weather API to retrieve the current temperature in San Francisco. The date and weather information are then passed to a JavaScript script that generates an SVG file, which is committed and pushed back to the repository.

Note that you'll need to replace WEATHER_API_KEY with your own API key from the OpenWeatherMap API, and you may need to modify the curl command to retrieve weather information for your desired location.
NFT without breaking the bank.
Tags: beginners, productivity, 100daysofcode, blockchain
Published: 2023-02-06 13:09:54

1.Imagine owning a one-of-a-kind NFT without breaking the bank. Wondering how? 

2 Introducing a new way to experience the world of NFTs: NFT renting! 

3. #NFTrenting #cryptoart #NFTs

4. NFT renting allows you to borrow an NFT for a certain period of time, giving you the chance to showcase it on your digital wall and experience the joy of ownership.

5. Not only does it make NFTs more accessible for everyone, but it also opens up new opportunities for creators and collectors alike.

6.  Keep an eye out for more updates on this innovative concept
Ajuda para criar um programa
Published: 2023-01-16 18:02:23

Fala galera, sou iniciante na programação, ainda esto aprendendo HTML/CSS3 e JS e python mas eu queria desenvolver um programa que faça que tenha a seguinte função:

O programa vai ter um banco de dados com 09 terminais (conjuntos de números adicionados por mim)

quando clicado em V quero que fique verde um quadradinho do lado do terminal que foi clicado e quando F que fique vermelho, ao mesmo tempo que quero que contabilize sequencialmente o mesmo quadradinho

Os cliques nos terminais são em ordem aleatória, ou seja, o usuário pode clicar V no terminal 1, logo em seguida F no terminal 9, depois F no terminal 5, depois V no terminal 3… enfim, não importa as ordens, como também pode clicar no mesmo sequencialmente, vai da escolha do usuário

o programa tbm pode calcular qual terminal ta sendo mais clicado e retornar uma porcentagem ao lado de cada terminal com cores relativas ao valor
ex:
terminais

10 % | 0 - 6/7: V | F |(ai o usuário escolhe a opção): [01 verde] (aqui no caso o usuário escolheu V)

10 % | 1 - 8/3: V ou F : [04 vermelho] (aqui no caso o usuário escolheu F)

40% | 2 - 9/2: V ou F: [02 verde] [5 verde] [7 vermelho] [8 vermelho]

Enfim, conforme eu vá clicando em cada terminal no valor desejado, contabilize sequencialmente e ao mesmo tempo vá para a cor que significa cada valor…

Se alguém puder me ajudar com esse problema ficarei muito feliz, gostaria tbm de uma explicação pois já bati tanta cabeça kkkkkk

um abraço a todos!

20% | 3 - 3/5: V ou F: [03 vermelho] [6 vermelho]
MacOS can remove backgrounds from images
Tags: macos, images, background
Published: 2023-02-06 12:59:14

---
title: MacOS can remove backgrounds from images
published: true
description: A new option in the finder context menu allows you to remove backgrounds from images.
tags: macos, images, background
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
# published_at: 2023-02-06 12:55 +0000
---

Today I learned that MacOS can remove backgrounds from images, much like [remove.bg](https://www.remove.bg/) does.

{% youtube d7nq1WigNvk %}

All you need to do is right-click an image and select Quick Actions > Remove Background.

![Remove background option of the finder context menu.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/codrlchl0np25zkoocas.png)

For example, it turned this image

![Chris Heilmann holding a cup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6710zangg27bdxohz7qt.jpg)

into this one:

![Same image but with removed background](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/palgc2l9crcpgedegjot.png)
Just launched my mental health app
Tags: startup, mentalhealth, mobile, xamarinforms
Published: 2023-02-06 12:41:56

Hi everyone, I wanted to share my latest project and talk about the reasons for making it.

One a Day is a gratitude and positivity platform for people struggling with their mental health. It offers a safe space where we can practice gratitude and celebrate our achievements, no matter how small. 

When dealing with mental health issues, we encounter problems, which we think should be trivial to solve. We get frustrated thinking "Why am I like this!?" or we compare ourselves to others thinking "This should be easy, everyone can do it". Even when we manage to do something hard, we often don't give ourselves credit, but rather shoot ourselves down thinking "It wasn't that hard" or "I should have done this a long time ago".

These thoughts contributes to further feelings of shame, guilt and isolation. We don't appreciate ourselves for the good things. We feel unworthy of praise. We don't want to open up to people thinking they wouldn't understand, or worse, they'd scoff at us. We keep fuelling our depression, anxiety, eating disorders, you name it. 

I've been there. To be honest, I still am. This is why I decided to build One a Day. To find others like me. To help them and to get help myself. To tackle those issues by building a community where we all support each other on our path to recovery by practicing gratitude and making that One small step a Day. 

If you were so kind as to give my app a go, and let me know your thoughts, whether it’s around the idea, the technical aspects, usability, or anything else, I would be extremely grateful. Or if it's not for you, perhaps you know someone who would benefit from it. In that case, please pass it on.

I hope it can grow into something meaningful.

Thank you!

[S﻿ee on Play Store](https://play.google.com/store/apps/details?id=com.oad.oneaday)

[See on App Store](https://apps.apple.com/app/one-a-day-gratitude-platform/id1662212197)

[S﻿ee product page](https://www.oneadayapp.com/)
VS Code ShurtCode active tab
Published: 2023-02-06 12:46:00

**In macOS,** you can assign keyboard shortcuts to quickly open the related code file in VS Code. To do this, follow these steps:

**Go to Code** > **Preferences** > **Keyboard Shortcuts.**
On the page, click the "edit **keybindings**.json" button on the top right.
Append the configuration below and save.

```
[
    {
        "key": "cmd+0",
        "command": "workbench.action.openLastEditorInGroup"
    },
    {
        "key": "cmd+1",
        "command": "workbench.action.openEditorAtIndex1"
    },
    {
        "key": "cmd+2",
        "command": "workbench.action.openEditorAtIndex2"
    },
    {
        "key": "cmd+3",
        "command": "workbench.action.openEditorAtIndex3"
    },
    {
        "key": "cmd+4",
        "command": "workbench.action.openEditorAtIndex4"
    },
    {
        "key": "cmd+5",
        "command": "workbench.action.openEditorAtIndex5"
    },
    {
        "key": "cmd+6",
        "command": "workbench.action.openEditorAtIndex6"
    },
    {
        "key": "cmd+7",
        "command": "workbench.action.openEditorAtIndex7"
    },
    {
        "key": "cmd+8",
        "command": "workbench.action.openEditorAtIndex8"
    },
    {
        "key": "cmd+9",
        "command": "workbench.action.openEditorAtIndex9"
    },
    {
        "key": "ctrl+1",
        "command": "workbench.action.focusFirstEditorGroup"
    },
    {
        "key": "ctrl+2",
        "command": "workbench.action.focusSecondEditorGroup"
    },
    {
        "key": "ctrl+3",
        "command": "workbench.action.focusThirdEditorGroup"
    }
]

```

With these keyboard shortcuts, you can use CMD+[1-9] to switch between tabs and CTRL+[1-3] to focus editor groups in VS Code.




🌎🙂😎 Let's Connect!
My Twitter: [@muzeyrozcan](https://twitter.com/muzeyrozcan)
[My Substack ](https://muzeyr.substack.com/)(here I will publish more in-depth articles)
Nostr NIP-05 verification with Cloudflare Workers
Tags: nostr, damus, cloudflare, cloudflareworkers
Published: 2023-02-06 12:42:41

---
title: Nostr NIP-05 verification with Cloudflare Workers
published: true
description: 
tags: ['Nostr', 'Damus', 'Cloudflare', 'CloudflareWorkers']
# cover_image: https://direct_url_to_image.jpg
# Use a ratio of 100:42 for best results.
---

If you have a domain managed by Cloudflare, you can use Cloudflare Workers to get Nostr NIP-05 verification.

## 1. Create a Service

```src/index.ts
export default {
  async fetch(request) {

    const data = {
      "names": {
        "<username>": "<hex key>"
      }
    };

    const json = JSON.stringify(data, null, 2);

    return new Response(json, {
      headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json;charset=UTF-8',
      },
    });
  },
};
```

If you're a [Damus](https://twitter.com/damusapp) user, you can use [damus key converter](https://damus.io/key/) to convert a damus key to a hex key. You also need to add the CORS header: `Access-Control-Allow-Origin: *` so it can be validated from the app.

## 2. Create Workers Routes

Once the service has created, you need to add Worker Route.

```wrangler.toml
[route]
pattern = "tetsuya.dev/.well-known/nostr.json*"
zone_name = "tetsuya.dev"
```

Note that because [route patterns cannot contain query parameters](https://developers.cloudflare.com/workers/platform/triggers/routes/#route-patterns-may-not-contain-any-query-parameters), you must use a wildcard `*` to have a route pattern match URLs with query parameters.

## Result

```
$ curl --include 'https://tetsuya.dev/.well-known/nostr.json?user=tetsuya'
...
access-control-allow-origin: *
...

{
  "names": {
    "tetsuya": "28d1243fb879d353c15c4cfc7537bf88f6fe18db2160c553beee408147eb0be5"
  }
}⏎
```

![NIP-05 verified](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rgql7ivvui79jfd1e5n8.jpg)

Follow me on Nostr: npub19rgjg0ac08f48s2ufn782dal3rm0uxxmy9sv25a7aeqgz3ltp0js9txe3x