teleren/devto huggingface dataset:
814. Binary Tree Pruning
Tags: leetcode, medium, tree, algorithms
Published: 2023-07-13 03:42:44

<strong>814. Binary Tree Pruning</strong>: [here](https://leetcode.com/problems/binary-tree-pruning/description/)


### 1. Understand the problem

In this situation, we need to be able to remove a subtree that does not contain any node with a value of 1.

So if we have a root = [0] => we will return null since the whole tree will get removed.

Also, we have another observation is that, if we have a TreeNode `node` and the left subtree: `node.left` and right subtree `node.right`, then `node` as a tree will contains 1 if either `node.val == 1 or node.left contains 1 or node.right contains 1`

So, we can utilize this observation to implement a DFS approach for this problem.

### 2. Approaches:

As we can see, when we can determine whether the left and right subtree of a node contains any node with a value of 1 or not, we will be able to 1) remove that subtree and 2) know if the current node does contain a node of 1 or not.

### 3. Solution:

```java
/** 
      helper function called hasOne(TreeNode node):
      - Base case: if no left and no right sub tree
          - if root.val == 0:
              return false
          - else:
              return true
      
      boolean hasOne = false;
      - if left:
          + left result = hasOne(node.left)
          + if ! left result:
              node.left = null
          else:
              hasOne = true;
      - if right
          + right result = hasOne(node.right)
          + ! right result:
              node.right = null
          + else:
              hasOne = true
      
      return hasOne
*/
```

### 4. Implementation with Java

```java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean hasOne(TreeNode root) {
        if (root == null) {
            return false;
        }

        if (root.left == null && root.right == null) {
            return root.val == 1;
        }

        boolean doesHaveOne = root.val == 1;

        if (root.left != null) {
            boolean leftResult = hasOne(root.left);
            if (leftResult) {
                doesHaveOne = true;
            } else {
                root.left = null;
            }
        }

        if (root.right != null) {
            boolean rightResult = hasOne(root.right);
            if (rightResult) {
                doesHaveOne = true;
            } else {
                root.right = null;
            }
        }

        return doesHaveOne;
    }

    public TreeNode pruneTree(TreeNode root) {
        boolean rootHasOne = hasOne(root);
        if (rootHasOne) {
            return root;
        }
        return null;
    }
}

```
Flipping keys/values in SQL JSON
Tags: mysql, json, key, value
Published: 2023-07-13 03:41:46

Have you ever come across SQL JSON that was injected in the improper order? Something along the lines of: `{"0": "numDogs", "3": "numCats"}` when you wanted `{"numDogs": "0", "numCats": "3"}`? Not only is it hard to make sense of your data (How would you sum up all the total numDogs across all the rows?) it is critically dangerous for the collision of keys. If you have a couple of rows you could manually UPDATE/replace the individual fields but this is still tricky if you have more then a couple rows. 

I was throwing around this problem in my head and, utilizing some temp tables and the JSON cmds introduced in  5.7.8, came up with a series of SQL queries that could be a solution. They can help make the JSON's key:value => value:key (or in other words your new key:value). **Note: this only works if your values are scalar (not array/object/etc because those arent valid keys).**

```mysql
#If you want to run multiple times you have to uncomment these to drop tables. Otherwise the tables are dropped when session ends
#DROP TEMPORARY TABLE tab;
#DROP TEMPORARY TABLE tmp1;

#Create a table to separate the keys and values
#REPLACE "mytable" and "json_data" and "id" with your table/column/primary key names
CREATE TEMPORARY TABLE tab
SELECT id, mykeys, myvalues
FROM (
SELECT *,
CASE WHEN JSON_VALID(json_data) THEN JSON_KEYS(json_data) ELSE null END AS mykeys,
CASE WHEN JSON_VALID(json_data) THEN JSON_EXTRACT(JSON_UNQUOTE(json_data), "$.*") ELSE null END AS myvalues
FROM mytable
WHERE json_data!="" and json_data!="null" and json_data is not null
) mytable;

#Create and fill a table that we are just going to use as index values
#Might be a clever way to add a sequence of values to a table but this is the way I did it...
#Just verify you insert more then the number of keys in the json you are "fixing". IE my example had 2 for numDogs and numCats
create temporary table tmp1 (id tinyint unsigned not null primary key);  
insert into tmp1 values (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23),(24),(25),(26),(27),(28),(29),(30);  

#REPLACE "mytable" and "id" with your table/primary key designations
UPDATE mytable jTable,
  (
select myresultstable.id, JSON_OBJECTAGG(col2,col1) as JSONresult from
(
select
tab.id,
JSON_UNQUOTE(json_extract(tab.mykeys, concat('$[', tmp1.id, ']'))) as col1,
JSON_UNQUOTE(json_extract(tab.myvalues, concat('$[', tmp1.id, ']'))) as col2
FROM tmp1
join tab
) myresultstable
WHERE myresultstable.col1 is not null and myresultstable.col2 is not null
group by myresultstable.id
  ) t2
SET jTable.json_data=JSONresult
WHERE t2.id = jTable.id;
```

I only ask you test and verify with your own environment before running these test queries because I am not a DBA (clearly) and this will overwrite your data 🖖
Getting started with dev.to and codespaces
Tags: beginners
Published: 2023-07-13 01:15:06

I am beginning my journey in getting accepted into the DPI Apprenticeship program. Whether I am accepted or not I am grateful to have come across this program. It has introduced me to great resources like dev.to and Github's codespaces.

**dev.to**

A great community of developers. One of the most important changes anyone can do when learning is to surround themselves with like-minded individuals. For the purposes of the apprenticeship, I will be using dev.to or my blog posts to track my progress as well as use it as an archive where I can search for previous problems and questions I had. Creating applications gets repetitive so it is a great idea to have a place where you can search for solutions of previous challenges. 

I also look forward to learning other functions dev.to has to offer in the near future.

**codespaces**

A great IDE built into Github where you can not only create your documents for projects, but also upload them to Github where they will be accessible anywhere. A fantastic option for when you are away from your main setup, but still want to get some work done.
Week note; 10 July 2023
Tags: weeknote
Published: 2023-07-13 02:08:57

This week has been mostly a blur of training videos, articles and a couple of practice exams.  Trying to juggle my time between things has been a challenge in and of itself, never mind the actual work involved.  On the go this week has been; 
- Coaching lab week 2 activities
- Flow Framework training classes
- Code and deploy the internal leave automation service
- Aussie visa paperwork

The coaching lab activities were all based around aspects of the agile coach role, how to orient yourself in a new system/team/org and then opportunities to give each other feedback on some slides pitching the coach role.  I generally consider myself a pretty introspective person but a lot of the course activities have been a nudge to to do it more and in finer detail, which surely can only be a good thing!  Providing it reveals all roses, I suppose...

I've actually enjoyed working on things that are outside of my usual comfort zone as an engineer/aspiring architect more that I thought I would but the bonus is that they all are related in the general digital profession sense.

Ticking off the achievement list:
- Submit Aus visa (so much paperwork.... Wonder if they want to talk to someone about their digital services.)
- Complete ACL week 2 homework
- Learned that mocha pot coffee is, in fact, the best home brew

And all that with my half finished FFXVI game staring at me from across the room!

It's a long weekend ahead, so hopefully my keyboard time will be low and I'll get out on a nice walk.

Mānawaita a Matariki 👋🏻
AntDB Product Advantages - Thread Pool + Coroutine Model
Tags: database, webdev, programming
Published: 2023-07-13 02:08:38

Traditional database server-side processing model generally adopts single connection single thread model or single connection single process model, which will occupy a lot of system resources and have high context switching and cannot support large concurrency (such as 100,000+ concurrency). AntDB can support millions of connections by introducing the thread pool + coroutine model.

Thread pool: Thread pool is a general technique that works by creating a certain number of threads in advance, and when a request is reached, the thread pool allocates a thread to provide service, and when the request is finished, the thread goes on to serve other requests. Compared with the model where one client connects to one thread, it takes less system resources and has higher throughput.

Coroutine: In contrast to threads, coroutine does not require kernel’s participation when switching contexts, and the timing of the switch can be controlled by the application layer code itself. AntDB will assign a coroutine to each client connection, one by one. The use with thread pool can further solve the problems caused by thread pool model such as jittering of thread number and deadlock.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qvu9vfbsh8m0temgjc9f.png)
React Native Passkeys SDK
Tags: passkeys, reactnative
Published: 2023-07-13 02:05:35

Wanting to implement passkeys in React Native? Authsignal has just released our [React Native SDK](https://www.npmjs.com/package/react-native-authsignal) and [documentation](https://docs.authsignal.com/sdks/client/react-native) to help you implement passkeys.

Accompanying our React Native SDK is our [Android](https://docs.authsignal.com/sdks/client/android) and [iOS SDK](https://docs.authsignal.com/sdks/client/ios).
Understanding the toFloat() Function
Tags: apacheag, internship, c, softwareengineering
Published: 2023-07-13 00:15:13

## Introduction

In this blog post we will discuss about the `toFloat()` function. This function allows developers to convert various data types to floating-point numbers, enabling them to perform arithmetic operations, comparisons, and other calculations.

## toFloat() function

This function converts a value and returns the value of floating point value. If any value are not convertible to floating point they will be null.

**Example**:

```sql
-- toFloat()
SELECT * FROM cypher('expr', $$
    RETURN toFloat(1.3)
$$) AS (toFloatList agtype);
 tofloatlist 
-------------
 1.3
(1 row)
```

This function is in [Apache AGE](https://github.com/apache/age/), and it helps the data manipulation of a database. Suppose you have a database table with a column that stores numeric values as strings, and you want to perform calculations or analysis on those values as floating-point numbers. However, some of the values may not be directly convertible to floats, this function can help you with it!!
A new Chapter in our platform!
Published: 2023-07-13 14:30:01

---
title: A new Chapter in our platform!
published: true
date: 2023-07-13 00:00:00 UTC
tags: 
canonical_url: https://blog.brainstory.ai/chapters/
---

## What are Chapters?

Chapters are a topical timestamped outline for your video! You can add them natively on hosting platforms like YouTube, or just publish it as text for your blog. This makes it easy for audiences to consume longer videos at a glance, especially if you cover a variety of topics.

## Why are people using it?

Ben Hong livestreams Office Hours for Obsidian on Twitch. Afterwards, he uploads his videos onto YouTube. This [hour long video](https://www.youtube.com/watch?v=77-trTtRmQU) covers a variety of topics! With Contenda Chapters, Ben’s audience can more easily navigate to subjects they want to find.

Here’s the Contenda Chapters for the above video:

> 0:00:00 Re-introduction of Obsidian Office Hours  
> 0:01:15 Expectations for Obsidian Office Hours  
> 0:03:46 Question and Answer: Writing Notes on Technical Subjects  
> 0:09:53 Understanding Input Type Color in JavaScript  
> 0:10:55 Note Taking Strategies  
> 0:18:44 Usage of Other Note-Taking Apps  
> 0:19:28 Collaboration and Note-Taking Tools  
> 0:22:27 Note-Taking Techniques and Practices  
> 0:24:02 Obsidian’s New Canvas Feature  
> 0:30:50 Memory Techniques and Mind Palaces  
> 0:31:42 Benefits of Obsidian and its Note Linking Feature  
> 0:33:51 Obsidian’s Data Structure and Accessibility  
> 0:35:37 Integration of Notes in Obsidian Canvas  
> 0:39:56 Obsidian Canvas Relationship to Epic Notes  
> 0:40:40 Canvas Embedding and Linking  
> 0:41:48 Canvas Customization and Features  
> 0:46:16 Tips and Issues with Obsidian Canvas  
> 0:49:32 Final Thoughts on Obsidian Canvas

## How can I use it?

This feature is live! On the Job Submission page, you can now choose Chapters.

<video controls width="500" height="400">
  <source src="https://contenda.co/blogimages/Submit-Chapters-Short.mp4" type="video/mp4">

Love it? _Hate it_? Tell us why!
TIL Blog
Tags: webdev, beginners, programming, productivity
Published: 2023-07-12 23:58:28

7/12 Today I learned that the command rackup changes the bash prompt to puma. This allows you to know which program is running in the terminal. The puma web server allowed me access to the live application preview which showed me a display of the code I typed. I also learned how to deploy a static website using Fly.io

7/16 Today I learned about the concepts of HTML and how it works in regards to a webpage. I learned that HTML is the structure and content of a webpage. I also learned several tags that can be used to diversify and organize a webpage.
tsParticles 2.11.0 Released
Tags: typescript, showdev, javascript, webdev
Published: 2023-07-12 23:43:03

## tsParticles 2.11.0 Changelog

### Bug Fixes

- Removed console log, closes #5003
- Fixed getPositionOrSize function
- Fixed some shapes

### New Features

- Added refresh flag for loading plugins, this will prevent multiple refresh of the instance
- Added animated gif support to image drawer (use it with caution, gifs are heavy)
- Added setLogger and getLogger functions, this will prevent `console.log` mistakenly left in the code.
- Added export plugins, previous export functions were removed (barely used), and a 3 new plugins are available. The available exports plugin are: Image, JSON, Video. The first two were already present, the third one is new.
- Added new rounded polygon shape

### Other Changes

- Removed fallbacks for requestAnimationFrame, they're useless.
- Added tree shaking capabilities
- Added ESLint `no-console` rule, to avoid other issues likes #5003, `getLogger` must be used when needed some logs.

#### How do `setLogger` and `getLogger` functions work?

If you want to customize the log of `tsParticles` you can call `setLogger(logger)` function, passing a `ILogger` object.

The `setLogger` function prevents `undefined` properties assigning the default one.

```ts
setLogger({
    debug: console.debug,
    error: console.error,
    info: console.info,
    log: console.log,
    verbose: console.log,
    warning: console.warn,
});
```

This assigns all the log functions console functions, but you can use empty functions (`() => {}`) to disable every function.

If there's a `console.log` left like in #3552, #3528 or #5003, you can disable the `log` property of the `setLogger` parameter to get rid of it, so you don't have to wait the next release.

The `getLogger` function, returns the object set using `setLogger`, every plugin *MUST* use `getLogger()` for logging things, so mistakes can be fixed easily, even errors can be muted or redirected to your favorite logging platform.

If you want to log something use this code:

```ts
getLogger().log("tsParticles is awesome");
```

--

## Social links

- [Discord](https://discord.gg/hACwv45Hme)
- [Slack](https://join.slack.com/t/tsparticles/shared_invite/enQtOTcxNTQxNjQ4NzkxLWE2MTZhZWExMWRmOWI5MTMxNjczOGE1Yjk0MjViYjdkYTUzODM3OTc5MGQ5MjFlODc4MzE0N2Q1OWQxZDc1YzI)
- [WhatsApp](https://chat.whatsapp.com/KQyHc9UEbRc2qlqNQR2J5c)
- [Telegram](https://t.me/tsparticles)
- [Reddit](https://www.reddit.com/r/tsParticles/)

---

{% github matteobruni/tsparticles %}
NestJS Vs Loopback : Whick One To Choose In 2023?
Published: 2023-07-12 23:41:57

Choosing between NestJS vs Loopback or any node.JS frameworkis very confusing, especially when there are so many great options. Choosing the right one requires an understanding of not only the project you are working on, but also both frameworks and when to use them.

I was not a fan of using frameworks to build backend node apps before. You could say we had a love-hate relationship, but a few years ago I tried using NestJS and was amazed! Back then, I thought Nest was the best out there…

…but only till I started doing experiments with Loopback 4. Now I’m clear!
see full article on - [Click here](https://devxilyas.com/nestjs-vs-loopback-whick-one-to-choose/)
Best React UI Frameworks In 2023
Published: 2023-07-12 23:40:33

If you’re looking to develop a React-based application, you may be wondering which UI framework to use. There are many options available, each with their own strengths and weaknesses. As a developer, it’s important to choose a framework that fits your project requirements, team size, and development workflow.

So if you are facing same issue! then dont worry In this post, we’ll take a look at some of the Best React UI Frameworks available, comparing their features, strengths, and weaknesses.

See full Article on - [Click here
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s34wuefkza2qkagrcojv.png)](https://devxilyas.com/best-react-ui-frameworks/)
Demystifying Factorials with JavaScript/TypeScript
Tags: webdev, javascript, beginners, typescript
Published: 2023-07-12 23:33:31

Let's unravel the mystery of factorials using cool JavaScript/TypeScript code.

## What Are Factorials?
Don't panic, factorials might sound complex, but they're actually pretty cool. Imagine you have a number, let's say 5. The factorial of 5 is written as 5! and it's all about multiplying positive numbers together from 1 up to 5.

###### Let's Break It Down:
Now, let's dig into some code that calculates factorials using JavaScript/TypeScript:

```
function calculateFactorial(num: number): number {
  if (num === 0 || num === 1) {
    return 1;
  } else {
    return num * calculateFactorial(num - 1);
  }
}

const number = 5;
const factorial = calculateFactorial(number);
console.log(`The factorial of ${number} is: ${factorial}`);
```
## The Code Unraveled:
We kick off with a super cool function called calculateFactorial. This function takes a number (num) and works its magic to calculate the factorial. It uses something called recursion, which means it calls itself with a slightly smaller number each time.

Here's the fun part: the code checks if the number is either 0 or 1. If it is, it quickly returns 1 because the factorial of 0 or 1 is always 1. But if it's not, we multiply the number by the factorial of the number minus 1, found by calling calculateFactorial(num - 1). This goes on until we reach the base case.

## Time to Play:
Let's bring our code to life! We pick a cool number like 5 and use const number = 5 to store it. Then, we unleash our function by calling calculateFactorial(number) to find the factorial. Finally, we display the result using console.log() and marvel at our coding powers!

Boom! You've unlocked the secret of factorials and how to calculate them using JavaScript/TypeScript. By using recursion, we've split the problem into bite-sized steps until we cracked it wide open.

Don't stop here! There's a whole coding universe waiting to be explored. Challenge yourself, experiment, and keep asking questions. The journey of a coding wizard starts with curiosity and a sprinkle of awesome.
Dzień 3 - Power BI
Published: 2023-07-12 22:32:48

---
title: Dzień 3 - Power BI
published: true
---

Tym razem stworzyłem rozdział o Power BI. Ponieważ w internecie jest sporo chłamu na temat tego jak bardzo wspaniała jest to aplikacja co nie zawiera wad, ciężko było mi się dokopać do sensownych informacji na temat funkcjonalności. Jak dla mnie jest to program do robienia wielkiej czerwonej strzałki dla prezesa firmy, w którym kierunku faktycznie należy iść.

Ok. Na jutro przewiduję tworzenie rozdziału na temat ASP.NET, może dorzucę jakąś krótszą historię. Najwyraźniej zarówno Power BI jak i ASP.NET mogą wypaść na tyle małe że może nie warto tworzyć ich jako osobne rozdziały, raczej jako podrozdziały. O ASP.NET powinienem powiedzieć parę słów więcej, o ewolucji od ASP.NET Framework do ASP.NET Core etc. Być może. ASP.NET powinien być pojedynczym rozdzialikiem. W skryptach DevOps być może będzie trochę więcej - ale znowu, niewiele wiecej, bowiem to głównie PowerShell i Terraform. Może powinienem po prostu rozdzielić ten rozdział na dwa podrozdziały i wstawić to wszystko do używanych technologii.

Dobra, to co właściwie mamy jeszcze do zrobienia:

1. Dokończyć rozdział na temat historii chmury Azure.
2. Stworzyć rozdział o ASP.NET - w sumie mam sporo napisane w pracy, może stamtąd to wezmę.
3. Stworzyć rozdział o PowerShell.
4. Stworzyć rozdział o Terraformie.
5. Stworzyć pytania do strony internetowej.
6. Dokończyć stronę internetową.
7. Utworzyć pobieranie danych od użytkowników na temat rozwiązanych ankiet.
8. Powiązać funkcjonalność statystyki ankiet ze stroną internetową.
9. Dokończyć rozdział o tworzeniu strony internetowej - w zasadzie będą to trzy rozdziały.
10. Doszlifować pracę inżynierską.

I to wszystko do końca lipca. Być może się uda. W sumie praca idzie dość solidnie.