teleren/devto huggingface dataset:
Pure JS is Hard
Tags: javascript, opensource, hacktoberfest
Published: 2021-12-17 02:46:18

Hey Everyone! So this one is suuuper late and it's not Rust :(. Previous related blog is here :) 
{% link antoniobennett/hacktoberfest-week-2-39l9 %}

### Project

So you might be wondering why did I say pure Javascript is hard...well that's because it is. Not hard in the sense of syntax and etc but when we start building complex apps that manage state etc it becomes annoying very quickly and you realize why we have frameworks. This [project](https://github.com/ynn1k/simple-js-tasklist) aims to create a todo app with pure JavaScript and eventlistener goodness.

### Issue

The [issue](https://github.com/ynn1k/simple-js-tasklist/issues/4) was that when a user enters tasks to do, there is no way of clearing only completed tasks.

### PR

The PR can be found [here](https://github.com/ynn1k/simple-js-tasklist/pull/19) if you want to just see it. First thing I did was creating a new button which only shows up with the clear task button as well. 

First we add the button of course. 
```javascript
<a href="#" class="btn btn-sm btn-outline-danger clear-comp-tasks">Clear completed tasks</a>
```

Then place inside a function that shows the button only when the task list is greater than 2
```javascript
if(tasks.length > 2) {
            document.querySelector('.clear-tasks').style.display = 'inline-block';
            document.querySelector('.clear-comp-tasks').style.display = 'inline-block';
            document.querySelector('.filter-wrapper').style.display = 'block';
}
```

Next is the functionality

First register the event listener to the button.
```javascript
const clearCompTasks = document.querySelector(".clear-comp-tasks");
clearCompTasks.addEventListener("click", Tasklist.deleteAllCompleted);
```

Then the functionality

```javascript
static deleteAllCompleted(){
        if(confirm('This will delete ALL completed tasks')) {
            tasks.forEach(task => {
              if(task.status === 'completed')
              document.querySelector(`[data-id="${task.date}"]`).remove();
            });
            tasks = tasks.filter(task => task.status !== 'completed');
            localStorage.setItem('tasks', JSON.stringify(tasks));
            Tasklist.filter();
        }
}
```

### Overall Thoughts

I realize why everyone loves JavaScript frameworks even more now. As complexity of the app goes up, state management becomes a pain in pure js. It is still fun figuring stuff out though.
go.reflect for a custom Print function
Tags: go
Published: 2021-12-17 02:29:49

Below, we create a function called Display that works like Println but even better: it shows the path traversed along with the value.

e.g. 
`Display([]string{"hello", "world"})`
would print 
`root.0 = hello`
`root.1 = world`

```go
package main

import (
	"fmt"
	"reflect"
	"strconv"
)

func main() {
	Display("hi")
	Display([]string{"apple", "banana"})
	Display([...]string{"apple", "banana"})
	var i interface{} = 3
	Display(i)
	type astrct struct {
		Z string
	}
	type strct struct {
		A string
		B int
		astrct
	}
	Display(strct{"js", 1234, astrct{"nodejs"}})
	Display(&strct{"js", 1234, astrct{"nodejs"}})
	Display(map[string]int{"m1": 1, "m2": 2})
}

func Display(d interface{}) {
	fmt.Printf("-- Display for %T --\n", d)
	display("root", reflect.ValueOf(d))
}

func display(path string, v reflect.Value) {
	switch v.Kind() {
	case reflect.Slice, reflect.Array:
		for i := 0; i < v.Len(); i++ {
			display(fmt.Sprintf("%s.%v", path, i), v.Index(i))
		}
	case reflect.Struct:
		for i := 0; i < v.NumField(); i++ {
			display(fmt.Sprintf("%s.%s", path, v.Type().Field(i).Name), v.Field(i))
		}
	case reflect.Ptr:
		if v.IsNil() {
			fmt.Println("%s = nil", path)
		} else {
			display(fmt.Sprintf("*%s", path), v.Elem())
		}
	case reflect.Map:
		if v.IsNil() {
			fmt.Println("%s = nil", path)
		} else {
			for _, i := range v.MapKeys() {
				display(fmt.Sprintf("%s[%s]", path, i), v.MapIndex(i))
			}

		}
	case reflect.Interface:
		display(fmt.Sprintf("%s.value", path), v.Elem())

	default:
		fmt.Printf("%s = %s\n", path, formatToPrint(v))
	}
}

// formatToPrint formats a value without inspecting its internal structure.
func formatToPrint(v reflect.Value) string {
	switch k := v.Kind(); {
	case k == 0:
		return "invalid kind"
	case k == 1:
		return strconv.FormatBool(v.Bool())
	case k >= 2 && k <= 6:
		return strconv.FormatInt(v.Int(), 10)
	case k >= 7 && k <= 12:
		return strconv.FormatUint(v.Uint(), 10)
	case k >= 13 && k <= 14:
		return strconv.FormatFloat(v.Float(), 'E', -1, 64)
	case k >= 15 && k <= 16:
		return strconv.FormatComplex(v.Complex(), 'E', -1, 64)
	case k == 18 || k == 19 || k == 21 || k == 22 || k == 23:
		// reference types:
		// chan, func, map, ptr, Slice
		return "type=" + v.Type().String() + " 0x" + strconv.FormatUint(uint64(v.Pointer()), 16)
	case k == 24:
		// string
		return strconv.Quote(v.String())
	case k == 17 || k == 20 || k == 25:
		// aggregate types:
		// array, interface, struct
		return "type=" + v.Type().String()
	case k == 26:
		// unsafeptr
		return "unsafe ptr"
	default:
		return "N/A"
	}
}

```

Output from above code = 
```
-- Display for string --
root = "hi"
-- Display for []string --
root.0 = "apple"
root.1 = "banana"
-- Display for [2]string --
root.0 = "apple"
root.1 = "banana"
-- Display for int --
root = 3
-- Display for main.strct --
root.A = "js"
root.B = 1234
root.astrct.Z = "nodejs"
-- Display for *main.strct --
*root.A = "js"
*root.B = 1234
*root.astrct.Z = "nodejs"
-- Display for map[string]int --
root[m1] = 1
root[m2] = 2
```
How to use a loop in blade files - Laravel
Tags: loop, blade, laravel, loopinblade
Published: 2021-12-17 01:45:47

## Introduction
When we talk about the loop in the blade, we mean PHP array passed into HTML template what called blade in Laravel. There is some way to loop in the blade. I will show you the easiest way, with the controller. 

## Let's go
When we successfully installed the new Laravel application we will  create Controller called ProjectsController. 

```
php artisan make:controller ProjectsController -r
```

Now we get all rows from the database under the Projects column. We use the Project model to get it. Save all projects into the `$projects` variable then we pass it into the blade template.

```
use App\Models\Project;

public function index()
    {
        $projects = Project::all();
        
        return view('projects', ['projects' => $projects]);
    }
```

Create blade file in _view_ folder called _project.blade.php_ and we use `@foreach` to loop over the `$project` variable what we got from _ProjectsController_ using table structure to format the results.

```
<table class="table table-bordered" >
   <thead>
      <tr>
         <th>Project Title</th>
         <th>Project description</th>
         <th>Created</th> 
      </tr>
   </thead>
                           
   <tbody>
      @foreach($projects as $project)
         <tr>
            <th>{{ @project->title }}</th>
            <th>{{ @project->description }}</th>
            <th>{{ @project->created_at }}</th>
         </tr>
      @endforeach
   </tbody>
</table>
```

## Conclusion
See how easy to use the loop method in Laravel? When we just pass some array from the controller into blade file.
Iot Software Development Company
Tags: devops
Published: 2021-12-17 01:11:35

Fusion Informatics, the top IoT app development company aims and intends to provide solutions for all business concerns and provide insights by embracing the innovative IoT ideas that allow devices to communicate. Our solutions ensure innovative business models that not only improve operational excellence but also achieve high business. We offer comprehensive and custom IoT based application development and services to harness the power of digital advantage.
Visite us to : www.fusioninformatics.com, Em – sales@fusioninformatics.com / Ph: +14242357391 / Add: 75 Broadway Suite 202, San Francisco, CA 94111, United States
100 dias de codigo: 44, React en The Odin Project.
Tags: spanish, 100daysofcode, webdev, react
Published: 2021-12-17 00:47:40

Foto de [Rumman Amin](https://unsplash.com/@rumanamin?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) en [Unsplash](https://unsplash.com/s/photos/food-chrismas?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
  
¡Hey hey hey!

Hoy, como los últimos días, me he dedicado a la sección de React de The Odin Project. 

Ciertamente es una buena guia para comenzar a aprenderlo y contiene algunos detalles que no había visto en las guías anteriores que tome para aprender esta libreria. 

Algunas de las curiosidades que note que muchas guías no te indican son:
- Que debes aprender a crear componentes con clases y funciones porque pueden ser necesarios dependiendo de la versión y los requerimientos del componente.
- La explicación que te dan sobre todos los complementos que instala al crear una aplicación con create-react-app.
- Las buenas practicas del lenguaje.

Realmente es curioso volver a aprender un idioma. Se siente como si lograras ver los detalles que no visualizaste al aprenderlo por primera vez. Realmente recomiendo volver a la documentacion de algun lenguaje que domines despues de un tiempo para que logres visualizar detalles que, a lo mejor, pasaste por alto.

Ahora volvamos con la sección regular:

### Ayer:
- Practique 30 min de Touch Typing.
- Retome el aprendizaje de Jest para el test unitario.
- Aprendí las bases para crear funciones puras las cuales principalmente se basan en crear funciones que no muten ninguna variable y no modifiquen ningun valor fuera de su alcance.
- Avance hasta la sección Introducción a React en The Odin Project.

### Hoy
- Practique 45 minutos de Touch Typing para calentar las manos por la mañana mientras escuchaba un podcast sobre marketing.
- Escribí algunas ideas sobre algunos proyectos nuevos para realizar aparte de The Odin Project.
- Avance hasta la sección CV Project en The Odin Project.

Ya siento que la navidad esta por llegar. Casi puedo saborear el pavo. Espero que tengan mucho éxito con sus proyectos y animo.

Adiós mundo!
Day 499 : Light Switch 
Tags: hiphop, code, coding, lifelongdev
Published: 2021-12-17 00:29:22

_liner notes_:
- Professional : Had a pretty good day. There were a few meetings, but I got to talk and plan with some folks about what's coming in the new year. Pretty excited about it. I also worked on updating a blog post I wrote with some new code in a recent release.

- Personal : So I basically finished the side project that I've been working on, or at least that's what I thought. haha More on that later. I ran into some issues trying to include some libraries into my code instead of pulling from a CDN. I was able to get one working, but I think the other library is older and the newer compilers that I'm using for this project kind of dropped support for the thing older libraries relied on. For some reason, the CDN versions are a little different and work. I'll probably look into it further, but for now, I just want to get the project launched. So yeah, I switched back and got everything working. Also got  the domain pointed to the Netlify servers.

![View from a mountain looking down at some green fields and a few houses in Sutton Bank, England with other small hills in the distance.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9m2v3i5041s346tnry1v.jpg)

After work, I finished up my side project. It has been deployed to https://xoXR.games . It's the home for a WebXR (Augmented and Virtual Reality) TicTacToe game I created for a talk earlier this year and any upcoming games I make as I learn more about WebXR next year. It's also my entry into the https://dusty.domains charity event Netlify is hosting. I thought I had everything working until I tried the game in AR mode and the makers weren't showing up. Then the light switch went of in mind that I ran into the issue the first and remembered how to fix it. Got that working and created the Social Share image that pops up on some sites when you enter the URL and pushed everything. I tested everything out and it seems to be working. That is the reason why this blog is done at a later time. Super happy I got it done. Going to submit it and promote it on Twitter tomorrow. Hopefully people can use it to connect to family and friends both in person and long distance during the holidays. I'm out. Got some stuff to work on like getting ready for the radio show.

Have a great night!

peace piece
Dwane / conshus
https://dwane.io / https://HIPHOPandCODE.com
{% youtube jQa-R-wBkXQ %}
December 16th, 2021: What did you learn this week?
Tags: weeklylearn, discuss, weeklyretro
Published: 2021-12-17 00:12:35

It's that time of the week again. So wonderful devs, what did you learn this week? It could be programming tips, career advice etc.

<center>

![Image of the brain](https://media.giphy.com/media/ojmB7lOn3VUU8/giphy.gif)
</center>

Feel free to comment with what you learnt and/or reference your TIL post to give it some more exposure.

{%tag todayilearned %}
<!--
And remember, if something you learnt was a big win for you, then you know where to drop it as well.👇👇🏻👇🏼👇🏽👇🏾👇🏿

{%link https://dev.to/devteam/what-was-your-win-this-week-4h3g %}

<center>

![Little kid making a fist as if to say "Yes!"](https://media.giphy.com/media/6brH8dM3zeMyA/giphy.gif)
</center>
-->
Photo by <a href="https://unsplash.com/@qmikola?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Mikołaj</a> on <a href="https://unsplash.com/s/photos/book?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
The quickest way to test changes in your forked React library
Tags: react, javascript, tooling, productivity
Published: 2021-12-17 00:04:13

I found that I was repeating myself in a fairly easy-to-automate task: create a React sandbox so I could easily test my projects in an isolated environment.

Then, I rolled up my sleeves and end up creating my first command-line application! It's called `create-sandbox` ✨

The first thing that might come to mind is "how is it different from codesandbox.io?"

Well -- codesandbox.io, despite being a great project that I do use extensively, only allows the installation of published packages. Not only that, it does not let you browse `node_modules`, making it impossible to change the source code.

It also does not support [linking](https://docs.npmjs.com/cli/v8/commands/npm-link), therefore you cannot iterate changes in your library in real-time.

You can run it like that:

```sh
npx create-sandbox <source>
```

Where `source` is either a Git repository URL (it doesn't matter if it's SSH or HTTPS) or an existing folder in your file system.

For testing, I'll pick my own [use-data-structures](git@github.com:zaguiini/use-data-structures.git) library. As one can guess, it exposes a few hooks that enables powerful data structures inside React. Let's go! 

```
➜  npx create-sandbox git@github.com:zaguiini/use-data-structures.git

✔ Cloned successfully
✔ React sandbox created successfully
✔ Project dependencies installed
✔ Dependencies linked

  Done!

  Now enter the `use-data-structures-sandbox` directory,
  run `yarn start` and enjoy your development sandbox!
```

And 💥! My sandbox is created!

When running `yarn start` in my sandbox folder, along with `yarn start` in my forked project, I can test my changes in real-time!

This is my usage in the sandbox:

![Sandbox usage source code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hjfgg9aj9kxsx41l9k4.png)
 
And this is what I see in the browser:

![Sandbox output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/asvfq8m5csrt2efbsbov.png)

Now look what happens when I change the `peek` method return value in my forked project to `blue da ba dee da ba di`:

![Forked project changes reflected in real-time](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m4va9bkekw114gsd8pom.png)

Pretty cool, right?! It only took me a single command to clone the repository, create a sandbox, link the forked project and start iterating over it. A cool thing is that `create-sandbox` uses whatever project manager the forked package uses, be it NPM or Yarn.

This is just the beginning. Right now, `create-sandbox` only works on simple React projects. In the future, monorepos will be supported.

Not only that -- I'm planning to support _other_ JavaScript frameworks, such as Vue, Angular and even Svelte, if possible!

The future looks bright, indeed. If you're wondering how I did that, [here's the repository](https://github.com/zaguiini/create-sandbox). It has the full roadmap, along with documentation! Come join us!

Thanks for reading! Let me know if there are any questions.
Native cloning is coming to Javascript soon!
Tags: javascript, node, webdev
Published: 2021-12-16 23:52:02

---
title: Native cloning is coming to Javascript soon!
published: true
description: structuredClone is a new native Javascript method for deep cloning objects
tags: javascript, node, webdev
cover_image: https://images.unsplash.com/photo-1616121474380-abe0aa516c00?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1632&q=80
---

If you've ever wondered "why doesn't Javascript have a method to deep clone?", you wouldn't be the only one.

For years we've been using various methods or libraries to clone objects and it's never felt quite right. Thankfully, [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone) is coming to a browser near you! Don't get scared off by the [sea of red](https://caniuse.com/?search=structuredClone) for browser support. All browsers have implemented it in their nightly releases, so it's on the way.

How do we use it you say? Simple:

```
const myObj = {
  title: 'Something',
  myNestedObj: {
    title: 'Something else',
    // ... and so on
  }
}
const myDeepCopy = structuredClone(myObj);
```

That's it. You now have a deep clone of your object. There are [some limitations](https://web.dev/structured-clone/#features-and-limitations) to be aware of though.

As always,
Happy coding! 🤓
[Cover photo credit](https://unsplash.com/photos/QtiZpH_N2sA)
Guide on Github deployment with MongoDB Realm
Tags: mongodb, realm, atlashackathon, github
Published: 2021-12-16 23:50:28

Hi, me and a friend teamed up for the MongoDB hackathon. And I'm super excited for it! With our idea, it seems like Realm would be the cool features to utilize for this. 

It sounds like AWS Lambdas, so I kind of have an idea how this works. And so I was looking for a way to integrate github deployment to my Realm app. Turns out they do have that option! But I hit some roadblocks:

- In the docs, it says there should be an [app configuration](https://docs.mongodb.com/realm/manage-apps/configure/config/), but there were so many folders, which ones are actually required?
- What's the best way? To start with an empty repo or with the app config?

1. I advise you guys to start with a repo with an /app and a realm_config.json inside it
2. Link your github account in Realm.

![link github to realm](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ah7w9hd33fllj3xs64qn.png)

It should practically look like that. Make sure the directory  points to `/app` (the docs says its on /dist, and that really confused me), and enable Automatic Deployment so that everytime you make changes in your repo, it will deploy here

3. Then to populate your repo, go to Environment Tab, and choose Development, hit Save

![environment tab](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v60zmctdtk538woqd10m.png)

4. Go to History Tab, there should be a button saying: `Review Draft & Deploy`. Click that and deploy it, what it does is the changes merges to your repo and it populates your app directory

That should be it, let me know if this helped you,

Cheers!
FM
log4shell の JAR 検査ツール
Tags: security, java, log4j, vulnerability
Published: 2021-12-16 23:45:20

"log4shell"、すなわち [Log4j](https://logging.apache.org/log4j/2.x/) に関わる深刻な RCE 脆弱性 CVE-2021-44228 に関して、[CERT/CC](https://vuls.cert.org/) から JAR ファイルをスキャンする検査ツールがリリースされました。

CVE-2021-44228_scanner
https://github.com/CERTCC/CVE-2021-44228_scanner

PowerShell 版、Python3 版、bash 版が公開されています。

CERT/CC (CERT Coordination Center) は
カーネギーメロン大学のソフトウェアエンジニアリング研究所の一部門です。

---

本記事は[小社のツイート](https://twitter.com/scqrinc/status/1471625215784660992)をもとにしています。
My Apple purchase regrets
Tags: apple, purchases
Published: 2022-03-05 23:41:41

---
title: My Apple purchase regrets
published: true
date: 2021-12-16 23:02:03 UTC
tags: apple,purchases
canonical_url: https://www.solarwinter.net/my-apple-purchase-regrets/
---

![](https://www.solarwinter.net/content/images/2021/12/danie-franco-Zi8-E3qJ_RM-unsplash.jpg)

I read [an interesting article by Mark Ellis](https://markellisreviews.com/the-apple-purchase-i-regret-the-most/) the other day which got me thinking about my biggest Apple purchasing regret.

To be clear up-front, I’m very happy with most of their devices, and quite snug in their ecosystem. While they do have their faults I’m happier to have them making my phone than Google or any of the interchangeable Android OEMs.

## Runner-up

The runner-up has to be my previous laptop, the MacBook Pro 2012.

To be clear, the MacBook itself didn’t really do anything wrong. What really let it down was the keyboard, and the freaking Touch Bar.

The keyboard had no travel to speak of. It was horrible to type on. I really should have trusted my instincts when I was in the shop, rather than thinking I’d get used to it. It was never good for typing - and as someone who writes code as well as starting to dabble in writing text, that was a major drawback.

The Touch Bar also was not a good thing. It _looked_ good, all fancy and stuff, but having things move around on you destroys muscle memory. It’s much better now I can rely on shift-F6 being in the same place the whole time, rather than having to think “what’s the Touch Bar showing at this moment? Am I going to refactor my code, or launch iTunes?”, and it's much more productive.

For reference - I’m currently happily typing away on an M1 MacBook Air - light, responsive, great battery life, _and_ the keyboard is a pleasure to use.

## Winner

However — the winner has to be the Apple Watch.

I got hooked on the idea of it, and it looked all nice and sleek when I got it. It was only after a while that I realised that the UI was clunky, and it was really useful for only a couple of things:

- subtly letting me know of notifications
- measuring your heartbeat, and maybe your steps.

A Fitbit can do the second two much, much more cheaply. Setting my phone to vibrate on the notifications I cared about approximated the first one.

I’ve also never really liked big watches on my wrist - I thought I’d get used to the Apple Watch, but I never did. (It has that in common with the MacBook - I really must learn to listen to my instincts more.)

It’s spent pretty much the whole of lockdown on the charger, and honestly, I haven’t missed it.

What has taken its place is the [Pulse HR from Withings](https://www.withings.com/uk/en/pulse-hr). Great battery life, light, and does what I need much more cheaply.

* * *

How about you folks out there? Any tales of “buyer’s remorse” to share, be it Apple gadgets or otherwise?

* * *

_Photo by [Danie Franco](https://unsplash.com/@dani_franco?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/regret?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)._
IndiePoetry is now live!
Tags: replit, python, flask, deta
Published: 2021-12-16 22:57:35

I created a website called IndiePoetry that enables writers to share their poems! I'll gladly take improvement ideas. :)
Visit the site at https://indiepoetry.herokuapp.com/

### Tech Stack
* It was written on replit.com in Flask and Python.
* It's hosted on Heroku.
* The database I used is [deta.sh](https://web.deta.sh).

#### To contribute or file an issue: 
{% github mordy-python/indiepoetry %}