teleren/devto huggingface dataset:
Clickable tristate checkbox
Tags: webdev, javascript, beginners, tutorial
Published: 2021-03-29 19:11:06

There is `HTMLButtonElement.indeterminate`, but you cannot set it normally on click.

This one is quite simple. You need two things.

- JavaScript onclick handler
- Place to hold the state

A simple implementation for this, is to store on `Element.target.value`, however, it can only be strings (otherwise, it will be coerced to string).

```js
function tristateHandler(e) {
  const states = ['true', 'null', 'false']
  
  const i = states.indexOf(e.target.value) + 1
  e.target.value = i < states.length ? states[i] : states[0]
  switch(e.target.value) {
    case states[0]:
      e.target.checked = true
      break
    case states[1]:
      e.target.indeterminate = true
      break
    default:
      e.target.checked = false
  }
  
  // Sadly, e.target.value is coerced to string
  console.log(typeof e.target.value)
}

document.querySelector('input[type=checkbox]').onclick = tristateHandler
```

{% codepen https://codepen.io/patarapolw/pen/BapLwOe %}
Schedule a job on Windows
Tags: schtasks, windows, schedule
Published: 2021-03-29 19:10:58

Hey there!

I use macOS on a daily basis but I'm working into a multi-platform application which runs on Windows and Linux then I needed to schedule a job the first time on Windows and I found that application called Schtasks.exe that helps to create and manage schedule jobs into Windows.

So if you wanna schedule a job to run every 5 minutes you can run that command line on terminal:

```
schtasks /create /sc minute /mo 5 /tn "Open MyProgram" /tr "c:\Users\admin\AppData\Local\Programs\myprogram.exe"
```

And then if you want to stop that schedule job you can run:

```
schtasks /delete /tn "Open MyProgram"
```

UPDATE #1:

If you want to force a command line above so use `/f` at the end of the command line. 

There are many other parameters and you can see here: https://docs.microsoft.com/en-us/windows/win32/taskschd/schtasks

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/schtasks-create
Implement the bubble sort algorithm using TypeScript
Tags: typescript, algorithms, javascript
Published: 2021-03-29 19:10:47

without any exaggeration, Let's go to the main topic! we start with a question:

## *what's bubble sort?*
bubble sort is a simple sort algorithm to sort a list by scanning and swapping the values in each step if they are in the wrong place (*it depends on sort order [ascending/descending]*).


![bubble sort visualization](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gojkyppew0qds6m4vqsd.gif)


## *Let's go!*
in this scenario, we want to sort an array in ascending order.
as we know, an algorithm consists of several specified properties:
- Input: an initial value in a specified structure.
- Output: the expected value after processing on `Input` value.
- Finiteness: algorithm must stop working after a specified step.
- Definiteness: the operations of each step must be specified.
- Effectiveness: the instructions must be simple and without any unnecessary actions.

first of all, to obtain the first requirement (input) we have to construct a function that returns an un-sorted array with random numeric values like the below example:

```ts
function genRandomArray(arrLength: number) {
  return [...Array(arrLength)].map(() =>
    Math.floor(Math.random() * (100 * arrLength))
  );
}
```

okay, now we have a dataset generator so let's explain the algorithm:

in this algorithm we have two pointers, like this:

![bubbleSort](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0ub60m6xkf5xz3k4i8u.gif)

in each step, each value will be compared with its next value:

- if `currentValue` was bigger than `nextValue` swap them.

- if `currentValue` was smaller than `nextValue` pass the step and compare the two next values.

- if `currentValue` was equal to `nextValue` do nothing and the same as the last case, pass it and compare the two next values.

- if pointers reach the end of the list: Repeat the algorithm.

End Of Process: these operations are repeated until all of the numbers are fully sorted (if this not make sense, take a look at the following example).

now come to take a look at implemented code:

```ts
function bubbleSort(arr: number[]) {
  const cpyArr = [...arr];
  const { length } = cpyArr;

  const swap = (a: number, b: number): void => {
    cpyArr[a] = cpyArr[a] + cpyArr[b];
    cpyArr[b] = cpyArr[a] - cpyArr[b];
    cpyArr[a] = cpyArr[a] - cpyArr[b];
  };

  for (let x = 0; x < length - 1; x++)
    for (let y = 0; y < length - 1 - x; y++) {
      const [currentIndex, nextIndex] = [y, y + 1];
      if (cpyArr[currentIndex] > cpyArr[nextIndex])
        swap(currentIndex, nextIndex);
    }

  return cpyArr;
}

console.log(bubbleSort(genRandomArray(10)));
```


*a short quotes about swapping from Wikipedia*:
> In computer programming, the act of swapping two variables refers to mutually exchanging the values of the variables.
> Usually, this is done with the data in memory.

HINT: if you want to sort the array in descending order, you merely have to change the `Greater than` operator to `smaller than ` operator in `if` condition, it makes the algorithm works reverse!

thanks for reading!
Designing forms for mobile
Tags: ux, webdev, design, frontend
Published: 2021-03-29 19:09:37

Designing forms for mobile can be a hiccup especially when it has many fields. I don’t know how many people know this; the on-screen keypad can cover your form or the submit button making it difficult for users to click thus disrupting the sign-in/sign-up flow.

## What I’m Working On
I’m rebuilding an old project, a forms app. The app has so many issues; performance, bugs, inappropriate loaders and **Bad forms** especially on mobile. I just built *something that worked* but I should’ve put more work into the form’s layout on mobile. The app was responsive, yes but I didn’t know the effect of the on-screen keypad on forms. It was until I deployed and checked it on my phone before realising the bad.

## Better form layout for mobile
A good lesson I learnt from  [web.dev](https://web.dev/sign-in-form-best-practices) (which I recommend you check out yourself), use multi-step form. You don’t have to crump everything on a single page.

![Form's initial design](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y10au3tjm71k7xffkidc.png)


![Form's new multi-step design](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/iyackeszzrcvoa1wnb9l.png)

The screenshots above shows before and after splitting up the form. In the second part, we ensure that the on-screen keypad doesn’t cover any part of our form.
Sure, this works but there is a caveat. Due to the differences in  [pixel densities](https://material.io/design/layout/pixel-density.html)  among devices, this may not work for all devices as expected, specifically devices with low-density screens like the iPhone 5. *This phone again* 🤦‍♂‍. 

## A little detail
“God is in the detail”. Since we are talking about on-screen keypads on mobile phones, there’s no need for desktop users to be affected by this. Desktop users shouldn’t go through steps to complete the registration when they can just do it once even if they’re viewing the page in window mode.

This is important because we want the sign-up flow to be smooth and swift, therefore if there aren’t many fields and they can all fit into the viewport then why bother users with multiple steps.

For desktop devices, all fields go on the same page because they can

![Form's new design on desktop](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qlclkc8bxi1jb2iq9u3q.png)
When in window mode or when resized into a really small size.

![Form's desktop design in window mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1sb92unmrvv3a9jed94r.png)

With the user-agent string, you can determine users' platform then give the multi-step form to only the mobile and tablet users. I talk about how to achieve this in my previous article.

## Conclusion
A badly designed form can affect the conversion rate for your site or app; therefore, you should do your best to make the flow smooth and simple. When designing for mobile, responsive layout isn’t all. Interactions matter, therefore be sure to test your app on an actual mobile device.
Generating A New Apple Distribution Certificate 
Tags: xcode, ios, certificate
Published: 2021-03-29 19:05:33

---
title: Generating A New Apple Distribution Certificate 
published: true
description: How to generate A New Apple Distribution Certificate 
canonical_url: https://monicagranbois.com/blog/swift/generating-a-new-distribution-certificate/
tags: xcode, ios, certificate
---

This post is a note to my future self about generating Apple Distribution Certificates. I received an email stating:

> Your Distribution Certificate will no longer be valid in 30 days. To generate a new certificate, sign in and visit [Certificates, Identifiers & Profiles](https://developer.apple.com/account).

After signing in, the Certificates, Identifiers & Profiles page will list two certificates:
1. Apple Distribution certificate
	* Used to distribute apps to TestFlight and the App Store. 
	* An expired certificate does not affect my apps on the App Store. However, I cannot update my apps or upload new apps with the expired certificate. 
1. Apple Development certificate
	* Used to run apps on devices and use app services.  
	* It will have my computer's name appended to the certificate name.

To generate a new certificate I followed the [steps from this StackOverflow answer](https://stackoverflow.com/a/59850970/4704303):

> * Open Xcode
> * Open Xcode Preferences (Xcode->Preferences or Cmd-,)
> * Click on Accounts
> * At the left, click on your developer ID
> * At the bottom right, click on Manage Certificates...
> * In the lower left corner, click the arrow to the right of the + (plus)
> * Select Apple Distribution from the menu


I also revoked the old certificate on the [Certificates, Identifiers & Profiles](https://developer.apple.com/account/resources/certificates/list) page. I did this by clicking on the distribution certificate and then clicking the revoke button.

XCode manages my provisioning profile, so I did not need to manually update it.

References:
* [https://stackoverflow.com/a/59850970/4704303](https://stackoverflow.com/a/59850970/4704303)
* [https://developer.apple.com/support/certificates/](https://developer.apple.com/support/certificates/)
* [https://help.apple.com/xcode/mac/current/#/dev3a05256b8](https://help.apple.com/xcode/mac/current/#/dev3a05256b8)
How to connect Greenhouse data with Firestore using Typescript
Tags: firebase, typescript, database
Published: 2021-03-29 18:47:24

Hello there!

I decided to share a small guide of this process because I found it challenging but also really satisfying!

This is a step by step guide on how to bring the data from greenhouse api to firestore. Is an integration that I struggled as a junior developer but I think this might help you in any system you might connect to the firestore.

##Step 1:

Create a firebase web app. Is super simple:
Please see this video →
https://www.youtube.com/watch?v=PKwu15ldZ7k&amp%3Bt=2808s
You don’t need to create the signup form just the setup of the firebase part.

##Step 2:

You create a greenhouseData.ts file in order to create a class that will call your data with the .get() method later on.

For instance:

```js
const URL = ‘XXXX
const greenhouseAuth = Bearer ‘Token’ -> here you replace Token with your admin api key.

export default class GreenhouseData {
  async getdata(): Promise<AxiosResponse<any>> {
    return axios.get(‘url / endpoint’, {
      headers: {
        Authorization: greenhouseAuth
      }
    });
  }
}
```
##Step 3:

Now on your firebase.ts file where you put all the configurations of firebase.
Change the function app to a class.
```js
export default class FirebaseData {
  db: any
  initialise() {
    const app = {
      //all your config data such as apiKey:
     //...
    }
    admin.initializeApp(app);
    this.db = admin.firestore();
```

this async basically will be called on another file — you will see below why..

```js
async post(data: any) {
const docRef = this.db.collection(‘yourCollection’).doc(‘yourcollectionID’);
await docRef.set(data);
}}
```

##Step 4:

Create an index.ts file and this is the file that we will call on our local terminal to see if what we made is working.
On that file take that piece of code and replace the values you need to.

```js
import FirebaseData from “./xxx”;
import GreenhouseData from ‘./xxx’;

async function main() {
  const dfFirebase = new FirebaseData();
  const dfGreenhouse = new GreenhouseData();
  dfFirebase.initialize();
  const datafromGH = await dfGreenhouse.getdata();
  const participantsDataId = participantsDataId.data
  for (let key in participantsDataId) {
    //this again depends on the type of your data — array/ object
    const participantDataId = participantsDataId[key].id;
    //this is the function that you use to post on the firestore
    dfFirebase.post({
      myCollection: participantDataId
    })
  }
}
main();
```
Hope that will help you and save you time! :)
Cerebral Debugger in Next.js
Tags: nextjs, cerebral, javascript, websocket
Published: 2021-03-29 18:37:36

If you are getting below error:

```
ReferenceError: WebSocket is not defined
    at Devtools.createSocket
```

when trying to hook [Cerebral Debugger](https://cerebraljs.com/docs/introduction/devtools.html) up in Next.js try to refactor your bootstrap code from this:

```javascript
const devTools =
  process.env.NODE_ENV === "production"
    ? null
    : {
        devtools: DevTools({
          host: "localhost:8585",
        }),
      };
```

to this:

```javascript
let devTools = null;

if (process.env.NODE_ENV !== "production" && typeof window !== "undefined") {
  devTools = {
    devtools: DevTools({
      host: "localhost:8585",
    }),
  };
}
```

Now you're be able to use Cerebral Debugger whilst still using Next.js when calling below:

```javascript
export default App(({ app }) => {
  app.on("initialized", () => {
    app.getSequence("initialize")();
  });
  return {
    state,
    sequences,
    providers,
  };
}, devTools);
```
Using FontShare - a free collection of professional grade fonts
Tags: css, gettingstarted
Published: 2021-03-29 18:14:16

---
title: Using FontShare - a free collection of professional grade fonts
published: true
date: 2021-03-29 18:13:19 UTC
tags: CSS,GettingStarted
canonical_url: https://adithya.dev/using-fontshare-in-website/
---

FontShare recently announced their public release of fonts that's available for usage in both personal and commerical projects.

> Fontshare is a free fonts service launched by the Indian Type Foundry (ITF). It’s a growing collection of professional grade fonts that are 100% free for personal and commercial use. Our mission is to make high-quality and technically sound fonts accessible to everyone across the globe.

### How to use FontShare

Similar to Google Fonts, you can use the CDN directly or download it and use it in your projects.

- Go to [FontShare.com](https://www.fontshare.com/)
- Select a font you like (customization available) and then **"Click to view Family"**
- Click on " **Download Family**", extract it and open the " **WEB"** directory
- Copy the " **fonts**" folder and paste it into your web project
- Enter " **css**" folder, copy your **font-name.css** and paste it in your web project
- In your stylesheet, import it using `@import url('font-name.css');` followed by the font families that you would like

For example, for the font [Ranade](https://www.fontshare.com/fonts/ranade), you would import the following fonts

```
@import url('ranade.css');
//The following font-family are available for usage with @font-face
//Example
@font-face {
  font-family: 'Ranade-Variable';
}
font-family: 'Ranade-Variable';
font-family: 'Ranade-VariableItalic';
font-family: 'Ranade-Thin';
font-family: 'Ranade-ThinItalic';
font-family: 'Ranade-Light';
font-family: 'Ranade-LightItalic';
font-family: 'Ranade-Regular';
font-family: 'Ranade-Italic';
font-family: 'Ranade-Medium';
font-family: 'Ranade-MediumItalic';
font-family: 'Ranade-Bold';
font-family: 'Ranade-BoldItalic';
```
Mastering PHP Arrays
Tags: php, laravel, beginners
Published: 2021-03-29 17:51:37

---
title: Mastering PHP Arrays
published: true
description: 
tags: PHP, laravel, beginner
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/iczmzu0j54ngchvwoeho.png
---

If you like this post and want more follow me on Twitter: <a href="https://twitter.com/justericchapman?ref_src=twsrc%5Etfw" class="twitter-follow-button" data-show-count="false">Follow @justericchapman</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

<h2>PHP Arrays</h2>
```php
//Array declaration
$names = ['Mike', 'Peter', 'Shawn', 'John'];

//add to array
$names[] = 'Micheal';

// Array merge
$array3 = array_merge($array1, $array2);

// Array Concat with Spread Operator
$names = ['Mike', 'Peter', 'Paul'];
$people = ['John', ...$names]; // ['John', 'Mike', 'Peter', 'Paul']

//Array to string
$text = implode(', ', $names); // 'Mike, Peter, Paul'

// String to Array
echo explode(',', $text); // ['Mike', 'Peter', 'Paul']

// Direct access
echo $names[1]; //output Peter

// Remove and preserve keys
unset($names[1]); 
// It is now => [0 => 'Mike', 2 => 'Paul']

// Or remove and change keys
array_splice($names, 1, 1);
// It is now => [0 => 'Mike', 1 => 'Paul']

//loop for each array entry
foreach($names as $name) { 
   echo 'Hello ' . $name;
}

// Number of items in a Array
echo count($names);  

//Associative array:
$person = ['age' => 45, 'genre' => 'men'];

//Add to ass. array:
$person['name'] = 'Mike';

//loop ass. array key => value: 
foreach($names as $key => $value) { 
   echo $key . ' : ' . $value;
}

// Check if a specific key exist
echo array_key_exists('age', $person);

// Return keys
echo array_keys($person); // ['age', 'genre']

// Return values
echo array_values($person); // [45, 'men']

//Array filter (return a filtered array)
$filteredPeople = array_filter($people, function ($person) {
	return $person->active;
});

// Array map (return transform array):
$onlyNames = array_map(function($person) {
	return ['name' => $person->name];
}, $people);

# Search associative array
$items = [
        ['id' => '100', 'name' => 'product 1'],
        ['id' => '200', 'name' => 'product 2'],
        ['id' => '300', 'name' => 'product 3'],
        ['id' => '400', 'name' => 'product 4'],
    ];

# search all value in the 'name' column
$found_key = array_search('product 3', array_column($items, 'name'));
# return 2

```
SPACE Framework for developer productivity
Tags: github, productivity, framework
Published: 2021-03-29 17:29:57

The SPACE framework to measure developers productivity:

S – Satisfaction & Well Being
P – Performance
A – Activity
C – Collaboration & Communication
E – Efficiency & Flow

**Satisfaction**

Satisfied developers deliver additional value to end users by writing higher quality, more secure software faster. 

**Performance**

Performance is the outcome of a system or process. 

**Activity**

Activity is a count of actions or outputs completed in the course of performing work.

**Communication & Collaboration**

Active code sharing with internal repositories, discussions and strategic technical alignment are all practices deeply tied to the innersourcing model.

**Efficiency & Flow**

An uninterrupted period of time to be able to focus on delivering tasks related to project work items. Achieving a prolonged flow means more task completion in a day and greater overall satisfaction with work, thus a virtuous cycle of productivity.
Sum of digits of a number to a single-digit integer.
Tags: algorithms, datastructures, maths, youtube
Published: 2021-03-29 16:34:31

---
title: Sum of digits of a number to a single-digit integer.
published: true
description: Find the sum of digits of a number to a single digit in 1 second.
tags: Algorithm, DataStructures, Maths, YouTube
cover_image:  https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ysjfwywn85pcqp5y1iq0.png
---
Dropped another video on youtube this time it's a basic math problem but most of us don't think it in that direction.

Go through the logic of this problem and enhance your knowledge.

Check out the video on youtube: https://youtu.be/9baLG_4gohE

Follow me on GitHub to find some of my projects: https://github.com/salRoid

Please like, share, and subscribe to the channel will be dropping a lot of things ❤️❤️.
Simple, Easy HTML Dropdown
Tags: html
Published: 2021-03-29 16:34:11

Make a simple dropdown menu with bare HTML!
Use the following code:
```
<details>
<summary>This text will always be visible</summary>
This text is hidden until the dropdown is clicked
</details>
```
{% codepen https://codepen.io/CMFdev/pen/oNBzZJY %}
Colorful Mosaic Pattern Generator
Tags: html, css, javascript, 100daysofcode
Published: 2021-03-29 16:33:31

the day 99 of challenge #100DaysOfCode

Colorful Mosaic Pattern Generator Using HTML5, CSS3 & JS

Demo : https://color-mosaic.netlify.app/

Code : https://github.com/saidMounaim/100DaysOfCode/tree/main/Day99
Booleans: A Retrospective PSA
Tags: music, beginners, firstyearincode, psa
Published: 2021-03-29 16:11:06

So one of the coolest things about learning in a bootcamp setting is the speed at which you acquire new skills. Throughout my time at Flatiron School, as I would pair-program with my cohort-mates, I would frequently point out how cool it was that we were facing the challenges that we were at that moment (as opposed to the ones we had faced previously) because it would highlight to me the distance we had traveled in our learning. The problems we once had were no longer problems and things that we were doing with ease would have seemed impossible at one time not too long before. And as I am starting to wrap up my final project for Flatiron School, I have been spending a lot of time reflecting on the journey, and one very specific resurfaced.

When we first learned about Booleans way back when, I had a pretty big problem. And it wasn’t just me. Once I mentioned it to my cohort, it became apparent that a handful of my cohort-mates had made the exact same mistake: we had all mispronounced “Boolean.” Now, if you’re reading this, odds are you know how to pronounce the word. But just for a moment, imagine that you didn't. Sound it out. Go on, I’ll wait.

…

Yeah. Ok so maybe you got it right. But maybe you’re one of many that sounded it out the way I did: Boo-leen. Nowhere in any readings or blog posts or the like did anyone make clear how to say the word. And prior to being corrected, I had turned it into a song to help me study… I have since done a little updating to reflect some newer knowledge (including the proper pronunciation) and, to commemorate reaching the end of my program, I figured I’d share it with you all. Enjoy.


[https://youtu.be/eX8RvKoHvus](http://)

*Originally published on January 25, 2021*