teleren/devto huggingface dataset:
Creating a toggleable dark mode theme
Tags: webdev, javascript, css, design
Published: 2021-06-03 20:47:37

Read it on [My Blog, The Coder's Codex](http://thecoderscodex.herokuapp.com/Posts/ViewPost/creating-a-toggleable-dark-mode-theme)

It can be surprisingly simple to add a dark mode toggle to your site, but the challenging part can be making that choice persist for the user throughout your app.  

#Step 1: Allowing the toggle
I'm using AdminLTE as a template(its free to download and its great), which luckily has a wonderful little class ("dark-mode") that can be applied to the body to quickly apply a dark theme to the whole site.  Adding a button with the onclick function "toggleDark()" allowed me to access the function I wrote in my site.js file.
```
function toggleDark() {
    var element = document.getElementById("layoutBody")
    element.classList.toggle("dark-mode")
}
```
That was really all it took to be able to toggle, once I added the #layoutBody Id to my body element.  Then came the tougher part, making that persist across multiple pages

#Step 2: Saving user preference to Localstorage
Using localstorage, we can save the user's preference to the browser.  

I wrote a function called loadDark() that takes care of this, and called it using jquery.  
```
function loadDark() {
    //default is light mode
    console.log("dark mode is ", JSON.parse(localStorage.getItem("jamesonDarkMode")))
    let dark = JSON.parse(localStorage.getItem("jamesonDarkMode"))
    if (dark === null) {
        localStorage.setItem("jamesonDarkMode", JSON.stringify(false))
    }
    else if (dark === true) {
        document.getElementById("layoutBody").classList.add("dark-mode")
    }
}
```
And the Jquery:
```
    <script>
        $(window).on("load",loadDark());
    </script>
```
This will create a default user preference, but theres no way to change it yet.

#Step 3: Changing the user preference 
Now back in our other function, we need to add some stuff to our toggleDark functionchange that localStorage variable.  Otherwise we will only ever have the default setting of false.  


```
function toggleDark() {
    var element = document.getElementById("layoutBody")
    element.classList.toggle("dark-mode")
    let dark = JSON.parse(localStorage.getItem("jamesonDarkMode")) 
    if (dark) {
        localStorage.setItem("jamesonDarkMode", JSON.stringify(false))
        console.log("Dark mode off")
    }
    else {
        localStorage.setItem("jamesonDarkMode", JSON.stringify(true))
        console.log("Dark mode on")
    }
    //optional to change fontawesome icon on button
    var buttonElement = document.getElementById("darkIcon")
    buttonElement.classList.toggle("fa-moon")
    buttonElement.classList.toggle("fas")
    buttonElement.classList.toggle("far")
    buttonElement.classList.toggle("fa-sun")
}
``` 
Now whenever the user clicks the button the localstorage variable will be updated, and saved across your site.
100 algos in 100 days (Day 2)
Published: 2021-06-03 20:45:29

##Overlapping rectangles


These were my thoughts on the overlapping rectangles algo question on interview cake. https://www.interviewcake.com/question/javascript/rectangular-love?course=fc1&section=general-programming

<h3>Plan of attack</h3>

Bottom left is min y and X

Top right is max y and max X

A point is within the rectangle if it's y >= min y and y<=max y.

A point s X is within the rectangle if its X>= min X and X <= max X

Now check what section of rectangle is within

Find first point within
Or 
Check outside

Find all points in rectangle
Iteration over the X and y fixed
Can skip some iterations if too low / too high

<h4>Potential Improvements</h4>
Find midpoint X and midpoint y
Can you do a kind of binary. Is it in left half.. in right half?

Might still need to cycle over all the points

Is it a ring thing
Are any of the points on the outside ring? Then incrementally check the inner rings.
Creating TimeWarpScan.me
Tags: tensorflow, tiktok, webdev
Published: 2021-06-03 19:01:57

---
title: Creating TimeWarpScan.me
published: true
description: You can use TensorFlow.js to build a React website for playing with the webcam
tags: tensorflowjs, tensorflow, tiktok, webdev,
cover_image: https://timewarpscan.me/twittercard.jpg
---

You don't have to use AI tech like TensorFlow.js for AI only.  I enjoyed adding GPU acceleration to my JavaScript to make a wild project.  Want to know what it is?  Watch the promo video I made:

{% youtube OQuDWmW2blA %}

Building with JavaScript is quite rewarding.  I hope you get the feel of it, too.  Just watch us enjoy the site on a Walkthrough Wednesday with friends.

https://www.twitch.tv/videos/1044068063

I've been fortunate enough to talk about this at Magnolia JS conf and other places!  It's a fantastic Open Source project for people learning and looking to contribute during their #100DaysOfCode 

The site is here:  http://timewarpscan.me/
The source code is here:  https://github.com/GantMan/timewarp/tree/main/timewarpscanme

The site is hosted on AWS Amplify and written in React!

And of course, if you want to be a master of TensorFlow.js to make your own fun projects, here's the obligatory book link:

https://amzn.to/3dR3vpY
![Learning TensorFlow.js](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/69b8779ur5v000zl8cxu.jpg)
#RenderRoundtable meets Front End Happy Hour
Published: 2021-06-03 20:06:47


For last week's #RenderRoundtable, we had the pleasure of having libations and lively conversation with [Shirley Wu](https://shirleywu.studio), [Jem Young](https://jemyoung.com/about/), and [Ryan Burgess](https://twitter.com/burgessdryan) from none other than the [Front-End Happy Hour](https://frontendhappyhour.com): a podcast featuring a panel of Software Engineers, who discuss all things front-end. 

However, we decided to switch it up and talk about working from home. A lot of us have gotten accustomed to attending meetings with our pajama pants on, napping on our lunch breaks, and zoom meetings with dogs in the background over the past year. For some, it's made us realize how much we hate the commute or love the flexibility, and for other's it's been hard to be as productive or as social. 

I think the important thing that we all learned here is that there's drawbacks to every model. While various degrees of remote work and different team structures will work incredibly well for some companies, it simply wont for others. And that's okay! Whatever your working flavor is, what we all agreed on was that working from home has sparked a broader conversation about inclusion. People who normally wouldn't be able to work in certain positions now can, because they can telecommute. And (in theory), they can do so without the backlash that often comes with having a non-traditional schedule or work environment.

As we move towards being an industry that is pioneering being successful from anywhere, we need to be sure that we are empowering, not punishing remote employees. And that teams who choose to be remote or have remote members, do so because they have the resources and are willing to commit to creating an environment where these employees can thrive.

As we approach the arrival of RenderATL, these conversations continue to be of the utmost importance. And while we won't be having a #RenderRoundtable next week, we will be launching our first ever spotlight piece on another dope individual doing great work in tech.

For a sneak peek at who this might be, be sure to follow us on [Twitter](twitter.com/renderatl), and subscribe to our [newsletter](https://ti.to/render-atlanta/Tickets). We'll be dropping some exclusive conference previews on [Instagram](instagram.com/renderatl) too, so be sure to check us out!

And if you haven't already, check out our [menu](https://www.renderatl.com/food) (chef-cooked meals and drinks are included alllll conference long), take a look at our amazing [speakers](https://www.renderatl.com/speakers), and grab a [ticket](https://ti.to/render-atlanta/Tickets)-- there's only a few left, before they're all gone!

Until next time!
Label your Code-Review comments
Tags: codereview
Published: 2021-06-03 19:51:32

## TL;DR
Add labels to your code review comments to let the author of the code know what weight you put on each of them.

## The story
In one of the previous companies I worked for I faced multiple situations when the debates over a piece of code were fierce and lengthy, sometimes leading to unfortunate personal comments. Code review process can of course be stressful, and sometimes it is hard to separate the judgement about your work from the judgement about you personally. But it is a part, and I believe - a very valuable part - of our profession, and can be a great tool for learning and teaching. 

As it turned out lots of the misunderstandings during code review process were due to the lack of a simple thing: the author of the code was unsure how "serious" a comment from a reviewer was. Was it a tip? Something which is absolutely necessary? An improvement? Should he answer?

## The labels
In your usual CR, there's a mix of cosmetic, business, architectural and technical remarks, all with different weights. In one of the teams I've worked with, we've come up with the idea of labelling the comments, and I tend to use this idea whenever I do code review today.

To keep the system simple there are three labels:
- **cosmetics**- a cosmetic change / suggestion. Whether it is a formatting, local variable or private function name. Something the author of code may ignore, as this is more of a personal taste thingy.
- **rethink** - a piece of code which you find more troubling, and expect at least an explanation from the author why he took this-and-that approach. Maybe there exists a better solution?
- **nogo** - that code is a clear no-go, it introduces a bug, a serious maintenance / performance problem, violate domain rules.

The labels, of course, won't end heated discussions, but they are a clear sign from the reviewer what parts of the review are more important for him. And one of the key elements to become successful development team is the quality of the communication inside the team - the labels are, at least for me, a simple but useful tool in my daily CR routine.
Learning about PWAs? You HAVE to play this game.
Tags: todayilearned, codenewbie, codequality, firstpost
Published: 2021-06-03 19:45:12

You read that right. A game.  It's found here: https://serviceworkies.com/

![Screen grab showing the serviceworkies code sections](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fkpjb9wx2sz3zce06zpp.PNG)

The developers (Google developers) teach the key concepts of progressive Web apps (PWAs) in a cool way as a game.

I've just completed all the levels and defeated a giant snail, beetle and some other crazy beasts while simultaneously learning about cache, service workers and the life cycle of service workers. 

![Screen grab showing the serviceworkies game play](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1r0ucaafsiaoc13cjiqh.png)
 

You can't simply copy and paste code and at the end of each stage there is a challenge to try and remember all the code from the previous lessons. I loved it and I'm sure you will! 
Go to https://serviceworkies.com/ and sign in to learn how to work with service workers to make your website work offline, feel like a native app and have fun along the way!
AWS Data Lake with Terraform - Part 2 of 6
Tags: aws, terraform, awsdatalake, bigdata
Published: 2021-06-03 19:31:17


**Amazon Glue**

Up to this point you are halfway to complete your data lake foundation. Let’s recap what you have achieved so far. First you created individual Terraform templates of your services, tested them, added security policies and streamed your data from EC2 to your S3 bucket landing zone using Kinesis. Now we need a fully managed extract, transform, and load (ETL) service that makes it easy for you to prepare and load the data for analytics. Glue is perfect for this job. With AWS Glue you can complete this task in two different ways such as manually or you could use AWS Glue Crawler.

Once your database is ready you can run Glue Crawler which after a minute or two would be extracting the metadata from your S3 bucket into a nice table schema. Although Glue would not give headers or partition names to this schema so you would need to edit it manually. Nonetheless Glue would be able to recognize the type of data in the schema (E.g. string, bigint, double)

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

**Terraform Glue section**
```
resource "aws_glue_catalog_database" "athena_db" {
  name = "athena_db"
}
resource "aws_glue_crawler" "glue_crawler" {
  database_name = aws_glue_catalog_database.athena_db.name
  name          = "s3_crawler"
  role          = aws_iam_role.crawler_role.arn

  s3_target {
    path = "s3://${aws_s3_bucket.data_logs.bucket}"
  }
}
```
Now that you have a structured table in AWS Glue for the data storage in your S3 bucket you can start treating S3 as a data lake database. Next stop Athena.

**Amazon Athena**

Athena is a serverless service so you do not need to worry about managing anything. This is super cool personally speaking. Athena is also an interactive query service for s3 which offers you a console to query S3 data with standard SQL or NoSQL. Athena also supports a variety of data formats such as:

- CVS
- JSON
- ORC
- Parquet
- Avro
- TSV

**Athena interface example shown below:**

![Athena](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2fdruc5saob072d2z8ne.png)

With Athena there is no need to load your data from S3. What do I mean by this? Well the data would actually live in S3 and Athena is smart enough to know how to interpret the data and query it interactively. For those who are familiar with Presto – Athena is using Presto under the hood.

**Diagram version 2: Data lake**
![Diag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xf1ddn20d4bd238opugo.png)

**Diagram final version: Data lake**
![Diag](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fgnzhqg35ef62jj8tdwe.png)

***It is time for a mini break at this point please stay tune for part 3***
Google Crowdsource Community
Tags: contributorswanted, eventsinyourcity, architecture, machinelearning
Published: 2021-06-03 19:18:07

Join the global community of passionate Crowdsource users!

What is Crowdsource?
Crowdsource is a fun, easy way for you to use your own abilities to contribute to the building blocks of Artificial Intelligence (AI). This helps us make the Google products that you love even better for your language, region and culture. Answers from you and millions of others around the world are used in Machine Learning based products, making them work well for the diversity of global population.

Your Crowdsource contributions improve Google Translate, Maps, Photos, Assistant, and more!

Why it matters?
Artificial Intelligence (AI) powers some of the most magical experiences in your favorite apps and products. It helps organize your photos, understand your voice commands, show you the most relevant reviews for products and businesses, and much more!

AI learns these skills by studying vast numbers of examples. The more examples it has for your language, region, or culture, the better it gets for you and everybody in your community.

Diversity in AI
You bring your own unique background, experiences, and perspectives to Crowdsource. As a member of our global community of contributors, you're helping to create AI that can best serve the rich and varied diversities of our planet!

Try Crowdsource. Make a difference.


YOU CAN ALSO CHECKOUT MY WEBINAR ON GOOGLE CROWDSOURCE COMMUNITY:
shorturl.at/ahpCD
Angular: SSR vs SSG
Tags: angular, scully, ssr, ssg
Published: 2021-06-03 19:13:49

## Server Side Render (SSR)
Nesse modelo a renderização fica a cargo do servidor, o que torna o carregamento da aplicação mais eficiente. Além de possibilitar melhor performance, nesse modelo também podemos lidar com alguns problemas de SEO (como indexação).


### Vantagens
- Indexação: é possível definir o conteúdo que será carregado a partir do servidor, sendo assim, este conteúdo seria indexado nos motores de busca. 
- Aparelho do usuário: como a renderização acontece do lado do servidor, ocorre uma menor exigência do dispositivo do usuário. 
- Performance: Na maioria dos casos tem boa performance e bons resultados na experiência por parte do usuário.

### Desvantagens
- Time to first byte maior, já que o servidor irá preparar o conteúdo a ser carregado.
- Reload nas mudanças de rota.

### Angular Universal (SSR)
Como indicação para desenvolver com SSR no Angular, indicamos o Angular Universal, inclusive o mais recomendado pela comunidade. 

Bons resultados com SEO, se quisermos atingir todos os motores de buscas. Possui rastreadores de mídia social e melhora de performance. 

## Static Site Generation (SSG)

As vezes a utilização do modo estático para criação de páginas é o mais recomendado. Exatamente se você tiver uma aplicação que raramente sofre algum tipo de alteração em seu conteúdo. Ex: Site Institucional.

### Vantagens
- Pouco uso do servidor.
- Pode ser usado como CDN.
- Ótimo SEO.
- Baixo consumo de memória, processador, etc.

### Desvantagens
- Não usar caso a aplicação seja muito grande ou é alterada com frequência. 

### Scully (SSG)
Recomendamos o Scully caso você queira investir na criação de uma aplicação estática. O mesmo encontra-se nos padrões de boas práticas do JAMStack.

O Scully explora as rotas da sua aplicação e cria uma estrutura listada com as rotas e gera um index.html para cada uma. 

Através do Scully é possível evitar longo tempo de carregamento e o tamanho da aplicação é até mesmo reduzido. 

Conta também com um sistema de plugins que podem tornar sua aplicação estática mais poderosa. 

### Qual usar?:computer:

Depende.

Depende do objetivo da aplicação.
Para um site simples sem grandes modificações, recomendamos o uso do SSG. Entretanto, se o seu site tem dinamismo, você tem preocupação com indexação nos motores de busca e experiência do usuário, o ideal seria o SSR.
How to deploy a Static Site to Heroku for free?

Tags: heroku, html, freehosting, deploy
Published: 2021-06-03 19:11:14

First: What is Heroku Platform?

Heroku is a hosting platform where you can deploy dynamic applications in Rails, PHP, Node.js and Python web applications.

Prerequisites:

In order to deploy a Static Site you need a couple of things:

1. Have git installed.
2. A Heroku Account – Sign up [here](https://signup.heroku.com/).
3. [Download the Heroku CLI](https://devcenter.heroku.com/articles/heroku-cli) – A command line interface for managing your Heroku Apps from Terminal.
4. Run `heroku login` in your Terminal or Command prompt and fill in your Heroku Account Credentials.

Deploying your Site:

First, You need to navigate to your project in the command prompt.

`cd Projects/my-site`

We can trick Heroku to deploy a static site by including 1 dynamic file.

The `index.php` file will be served by Heroku before your `index.html`. We need to make the browser redirect from `index.php` to `index.html`. We only need to include one line of PHP code.

`<?php header( 'Location: /index.html' ) ;  ?>`

Notice: Make sure there is no spaces before the `<?php` otherwise it won’t work!

Then we will use the command line tool called git to initialize or create a version of the site you want to deploy. To do that run the command:

`git init`

Then,

`git add .`


The `add .` means add all the files to the git repository.

Then you want to commit or save all the changes for your site. With a message describing what you have done.

`git commit -m "My site ready for deployment."`

Now you want to create your site on Heroku. If you are already logged in (because you ran `heroku login` earlier), you can issue the following command:

`heroku apps:create my-static-site-example`

Insert your desired name instead of `my-static-site-example`.

If the name is not taken you can deploy your site using git:

`git push heroku master`

Once you see “remote: Verifying deploy…. done.”
So, Congratulations. You can now visit your site at `https://<whatever-name-you-selected>.herokuapp.com/`.

If you want to add your own domain check out the [Heroku Documentation](https://devcenter.heroku.com/articles/custom-domains).

If you need to make changes to your site:

Add the changes.

`git add .`

Save the changes.

`git commit -m "Add useful message"`

Then deploy.

`git push heroku master`

Then your edits are published.
Integrating Jest with Gulp
Tags: jest, gulp, unittest
Published: 2021-06-03 19:00:35

The Gulp-jest plugin for running jest tests are extremely limited in their integrations with gulp workflow. Fortunately, Jest provides `jest-cli`, a library that allows you to run jest tests programmatically and also returns the result of the test. Taking advantage of this package, you can customize the operation of your gulp workflow.

To get started, install the `jest-cli` in your project:
```bash
npm i jest-cli
yarn add jest-cli
```
To run jest tests programmatically with `jest-cli`,  a sample code on how this is done is provided below:
```javascript
const jest = require('jest-cli');
const testRunner = async () => {
  const { results } =  await jest.runCLI(
    {json: false}, // jest cli options, check out more on https://jestjs.io/docs/cli
    ['project_directory'] // array of project directories in order to run multiple project tests
  )
  console.log(results);
  return results;
}

testRunner();
// clipped result
`{
    numFailedTestSuites: 0,
    numFailedTests: 0,
    numPassedTestSuites: 5,
    numTotalTestSuites: 7,
    numTotalTests: 98,
    success: true,
    testResults: [
      [Object]
    ],
    wasInterrupted: false
 }`
 ```

_Please note, the code above should work on versions of `jest-cli <= 24.9.0`, but might fail to work on newer versions of `jest-cli`, this is due to `runCLI` which is a private method not guaranteed to have the same behaviour across all versions of `jest-cli`._

<span id="customise">From</span> the returned results of the `jest.runCLI`, you can write a lot more jest integrations with your gulp workflow, and customise the behaviour of the workflows better than gulp-jest allows. 
A popular integration of test frameworks with gulp workflows would be aborting workflows if tests don't pass, a simple way to implement this with the help of `jest-cli` is shown below:
```javascript
// gulpfile.babel.js
const jest = require('jest-cli');

async function testJS() {  
   const testResults =  await jest.runCLI({json: false},['project_directory'])
   const { results } = testResults
   const isTestFailed = !results.success;
   if (isTestFailed) {
       console.log('You have some failed test cases, kindly fix')
       process.exit() // Breaks Gulp Pipe
   }
}

gulp.task('build', gulp.series(
  testJS,
  buildAssets,
  // Any other gulp tasks
))
```
With the implementation above, Test checks of Jest test is fully integrated into the gulp build workflow.

Too long did not read:
1) Install `jest-cli` in your project.
```bash
yarn add jest-cli
```
2) Use `jest-cli` to run your Jest tests programmatically. A sample code is shown below plus the returned result.
```javascript
const jest = require('jest-cli');
jest.runCLI({json: false},['project directory'])
    .then((testResults) => console.log(testResults))
```
3) Use the result from the `jest-cli` to customise your gulp workflow. check a sample of how it's done [here](#customise)
The First Gaming blog here in dev community
Tags: gamedev, vscode, computerscience, csharp
Published: 2021-06-03 18:50:25

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6pn81oc9lz8zy8c4csah.png)
#**Hey**,**There**
Tired Hardworking Devs its me tirth, the one and only gaming blogger on dev from nowonwards i will posting valorant, fortnite , and pubg etc. blogs here on dev community so do follow me for more if play one of these games adios!!.