teleren/devto huggingface dataset:
1.2 WordPress Smart Coding Tips | Schedule Event / scheduled tasks
Tags: wordpress, pluginmaster, wordpressplugidevelopment
Published: 2021-11-17 16:11:42


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

Normally in WordPress plugin development, we declare a scheduled event like the following.

```php
register_activation_hook( __FILE__, 'my_plugin_activation_event' );

function my_plugin_activation_event() {
	if ( ! wp_next_scheduled( 'my_plugin_activation_event' ) ) {
		wp_schedule_event( time(), 'daily', 'my_plugin_activation_event' );
	}
}

register_deactivation_hook( __FILE__, 'my_plugin_deactivation_event' );

function my_plugin_deactivation_event() {
	wp_clear_scheduled_hook( 'my_plugin_deactivation_event' );
}
```
We use this type of code in many places.
### Problem is that - This code is not re-usable.

## We can create a class for reuse.

Let's Start

1. Create a class or global functions file 

  a. First create a class name <code>Schedule</code>

```php
namespace MyPlugin\Utilities;

class Scheduler {

}
```

 b. Then add a method name <code>add</code>

```php
public static function add( $hook, $callback, $recurrence = 'daily', $start_time = null ) {
		if ( ! wp_next_scheduled( $hook ) ) {
			if(!$start_time) $start_time = time();
			wp_schedule_event( $start_time, $recurrence, $hook );
		}

	 add_action( $hook, $callback );
 }
```
** <code>$hook</code>: hook name for the event.
** <code>$callback</code>: callback function or array for add action of our event hook.
** <code>$recurrence</code>: How often the event should subsequently recur. See wp_get_schedules() for accepted values. Default id 'daily'
** <code> $start_time</code>: event first starting time. You can pass your desired time.

 c. Then we need to remove/clean our event.
For that let's create a method for removing events.

```php
  public static function delete($hook){
      wp_clear_scheduled_hook($hook);
  } 
```

### Uses

```php
Schedule::add('my-custom-schedule-event', [$this, 'event_handler']);

Schedule::delete('my-custom-schedule-event');
```


## OR you can create global  functions as like previous methods.


[AL EMRAN](https://alemran.me)
[Github](https://github.com/emrancu)


For Creating Awesome Structured PSR Based Plugin:
[PluginMaster, a WordPress plugin development framework](https://dev.to/plugin-master)
Adding Continuous Integration - GitHub Actions
Tags: opensource, osd600
Published: 2021-11-18 19:14:15

### Continuous Integration

In order to avoid breaking the code in the main branch, I added the Continuous Integration to the GitHub workflow. In this workflow, I want it to run on `node ver 14.x` whenever there's push or a pull request to the `main` branch. There are 2 actions I wanted to include: 
- a clean install of all dependencies: `npm ci`
- a full test run: `npm test` 

The `yml` file would look like this:
```
name: Node.js CI
on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
jobs:
  build:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [14.x]
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v2
      with:
        node-version: ${{ matrix.node-version }}
        cache: 'npm'
    - run: npm ci
    - run: npm test
```
After setting it up myself, I found that CI is not too hard to use and it also brings lots of conveniences as it can quickly detect if a push or pull request might contain a potential error.

### Adding more tests to another project

This week, I also created some test cases for another [repo](https://github.com/lyu4321/jellybean). Adding tests for someone else's code is no doubt for difficult than working on my own code. I had to understand the logic of the code and try to figure out what each function is supposed to do in order to find all possible scenarios. 

For Leyang's [project](https://github.com/lyu4321/jellybean), I found that `getHtlmlTitleBody()` was not tested yet so I decided to contribute some tests to it. This function accepts the content of the file as a string and a boolean indicating whether it's a text file or not, it then returns an object with 2 properties: title and body. 
```c
const getHtmlTitleBody = (file, isTxt) => {
  let html = {
    title: '',
    body: '',
  };

  let tempTitle = file.match(/^.+(\r?\n\r?\n\r?\n)/);
  if (tempTitle) {
    html.title = tempTitle[0].trim();
  }

  if (isTxt) {
    html.body = file
        .split(/\r?\n\r?\n/)
        .map((para) => {
            if (para == html.title) {
              return `<h1>${para.replace(/\r?\n/, ' ')}</h1>\n`;
            } else {
              return `<p>${para.replace(/\r?\n/, ' ')}</p>\n`;
            }
        })
        .join('');
  } else {
      let md = new markdownit();
      html.body = md.render(
        file.substring(html.title.length).trim()
      );
  }

  return html;
};
```

After investigating the function carefully, I came up with 3 scenarios to test:
- a text file input with title
- a text file input without title 
- a markdown input file

The details of the tests can be found [here](https://github.com/lyu4321/jellybean/pull/32/files).
Algorithm Series - Insertion Sort
Tags: algorithms
Published: 2021-11-17 21:11:13

---
title: Algorithm Series - Insertion Sort
published: true
date: 2021-11-17 16:00:00 UTC
tags: Algorithms
canonical_url: http://tatyanacelovsky.com/algorithm_series_-_insertion_sort
---

![Bright, multicolored paint cards are arranged in the shape of a hand fan on a white background.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8r6vgnxqfrc209qrgte2.jpg) Photo by [Dee @ Copper and Wild](https://unsplash.com/@copperandwild) on [Unsplash](https://unsplash.com/)

_This is a quick tutorial on the Insertion Sort algorithm and its implementation in Javascript._

### What is Insertion Sort Algorithm

Insertion Sort is a [sorting algorithm](%5Bhttps://en.wikipedia.org/wiki/Sorting_algorithm%5D(https://en.wikipedia.org/wiki/Sorting_algorithm)) that places the element in its appropriate place based on the sorting order. A good example of Insertion Sort is sorting cards held in your hands during a card game.

Let’s take a look at Insertion Sort when trying to sort the elements of an array in an ascending order:

1. Assume that the first element of the array is property sorted;
2. Store the second element of the array in a `key`;
3. Compare `key` to the first element - if `key` is smaller that the first element, then `key` is placed in front of the first element;
4. Store the next unsorted element of the array in a `key`;
5. Compare `key` to the sorted element and place it in the appropriate place with respect to the sorted elements based on whether `key` is smaller or greater than each of the sorted elements;
6. Continue with steps 4 and 5 until all elements of the array are sorted.

The array is sorted when all the unsorted elements are placed in their correct positions.

### Insertion Sort Code in Javascript

Let’s take a look at the code for the Insertion Sort algorithm described above (ascending order):

{% gist https://gist.github.com/tcelovsky/8c8d41a80c6d9525b69b7daeaf1c4b12.js %}

Let’s take a look at the code for the Insertion Sort algorithm described above (ascending order):

### Insertion Sort and Big-O

Insertion Sort compares the adjacent elements, hence, the number of comparisons is:

(n-1) + (n-2) + (n-3) +…..+ 1 = n(n-1)/2

This nearly equals to n2, therefore Big-O is O(n²) or quadratic time. We can also deduce this from observing the code: insertion sort requires two loops, therefore Big-O is expected to be O(n²).

### Conclusion

Insertion Sort inserts each element of the array in its appropriate place based on whether the array is being sorted in ascending or descending order. It is a simple way to sort a list when complexity does not matter and the list that needs sorting is short.

### Resources 

[Insertion Sort Algorithm gist](https://gist.github.com/tcelovsky/4c7b1b5a852adacf13ba7a3604000f79)

[Let’s Talk About Big-O](https://dev.to/tcelovsky/let-s-talk-about-big-o-2ah9)
Decoding CBOR with PureScript
Tags: cbor, purescript
Published: 2021-11-17 22:07:38

---
title: Decoding CBOR with PureScript
published: true
description: Decoding CBOR with PureScript
tags: #cbor #purescript
//cover_image: https://direct_url_to_image.jpg
---
If you want to decode cbor data from PureScript, there's `cborg`, which works just fine... if you use `useMaps` to deal with the `Error: CBOR decode error: non-string keys not supported (got number)` errors. Afterwards you have javascript `Map`s, which can't be decoded with argonaut. I use this code as workaround:

```javascript
const toObject = function(cbor) {
  if (cbor instanceof Map) {
    var obj = {}
    cbor.forEach(function(value, key) {
      obj[key.toString()] = toObject(value);
    });
    return obj;
  } else {
    if (cbor instanceof Array) {
      return cbor.map(ob => toObject(ob));
    } else {
      if (cbor instanceof Object) {
        var obj = {}
        cbor.forEach(function(value, key) {
          obj[key.toString()] = toObject(value);
        });
        return obj;
      } else {
        return cbor
      }
    }
  }
}
```
After that, you can decode the tags as string keys, e.g.

```purescript
decodeJson cbor :: _ { "1" :: Int }
```
What is random.shuffle() method in python? How to use it?
Tags: python, beginners, projects
Published: 2021-11-18 13:53:24

In this blog, we will explore the random.shuffle method in python, and implement this method in our password generator project.

**So Let's Get Started!**

What is the random.shuffle method? 

Basically the random.shuffle methods takes in a list like:
[1, 2, 3, 4, 5, 6, 7, 8, 9] and shuffles it like: 2, 1, 5, 6, 8, 9, 4, 7, 3].

Run this code to know more:

{%replit @vaarunSinha/Random-Shuffle-Method %}

**Let's implement this in our own project!**

In the previous blog, we had a problem:


>Now if we print/generate the password every time ,there is a 
predictable format, first numbers then special etc..

So for that first let's convert the password into a list:

```python 
password = list(numPart + spPart + smallPart + bigPart)
random.shuffle(password)
password_str = ''.join(password)
return password_str
```
This is the final code for a basic password generator!

{%replit @vaarunSinha/Password-Generator-with-secrets-module %}
**So stay tuned!**

**Happy Coding!**
Create a React App (Video)
Tags: javascript, beginners, tutorial, react
Published: 2021-11-18 19:29:55

Hi guys!

Ok so in many of my tutorials related to react JS, I have not mentioned how to get started with React JS or how to create a react app.
If you want to learn how to create an application in react js and follow along with my tutorials you can watch the below video in which I tell step-by-step how to create a react app and the commands needed.

{% youtube zLiMsF0UlpI %}

###Commands Used in terminal
These are the commands I used in the VS code terminal in the video. 
* Create a new app (replace appname with any name but make sure it is letters only and does not begin with uppercase)
```
npx create-react-app appname
```
* Change directory
```
cd directoryname
```
* Open your app or run it in the browser.
```
npm start
```

-----------------------------------------------------------------

I hope you all found the video useful.
Check out my other [tutorials](https://turbofuture.com/computers/React-and-Firebase-A-complete-tutorial-Part-1) on [hubpages](https://hubpages.com/@salehmubashar).
Also follow me on [twitter](https://twitter.com/SyntaxE85827144).
> Like my work? Buy me a coffee!

<a href="https://www.buymeacoffee.com/salehmubashar" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

Until next time,
Cheers :)
Python Programming Bundle by O'Reilly
Tags: python, beginners, machinelearning, codenewbie
Published: 2021-11-19 11:52:06

**[Python Programming Book Bundle by O’Reilly](https://www.humblebundle.com/books/python-programming-oreilly-books?partner=indiekings)**

Want to improve your Python programming… or just getting started learning? Humble Bundle teamed up with O’Reilly for the newest bundle that will help you on your way.

This coders’ package comes with $677 worth of eBooks for people of all experience levels, including Introducing Python, 2nd Edition; High Performance Python, 2nd Edition; as well as eBooks containing specialized knowledge like Web Scraping with Python, 2nd Edition; Test-Driven Development with Python, 2nd Edition; and many more.

This bundle helps support Code for America, using the principles and practices of the digital age to improve how government serves the American public, and how the public improves government.

The Python Programming Book Bundle by O’Reilly bundle launched on November 15, at 11:00 am PST and lasts through December 6, 2021, 2021. Pay what you want and support charity!
How to customize Tailwind CSS Typography
Tags: beginners, css, webdev, tutorial
Published: 2021-11-19 16:09:56

Tailwind CSS Typography provides a set of prose classes you can use to style your markdown posts. But sometimes the default styles are not enough to hit the mark. That's when Tailwind's customization API swoops in to save the day.

If you don't know what Typography is, you should read [How to style markdown with Tailwind CSS](https://ertas.dev/posts/how-to-style-markdown-with-tailwind-css/) to learn more.

Inline code styling that comes default with the plugin is one style that is replaced by many. It inserts back ticks before and after the inline code and makes it bold, instead of the more common approach:

` <p> Hello world! </p> `

The solution to this is customizing the `tailwind.config.js` file. This allows you to target specific Tailwind classes and adjust their default behavior.

```javascript
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      typography: {
        DEFAULT: {
          css: {
		  	'code': {
              color: "#333",
			  // You can also use @apply to inline existing utility classes
			  "@apply bg-gray-50 text-gray-700": "",
            },
            'code::before': {
              content: '""'
            },
            'code::after': {
              content: '""'
            }
          }
        }
      },
    },
  },
  plugins: [require("@tailwindcss/typography")],
};
```

Above example is only modifying the look of the inline code blocks. But the same method applies when altering different selectors.

```javascript
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      typography: {
        DEFAULT: {
          css: {
            color: '#333',
            a: {
              color: '#3182ce',
              '&:hover': {
                color: '#2c5282',
              },
            },
          },
        },
      }
    },
  },
  plugins: [
    require('@tailwindcss/typography'),
    // ...
  ],
}

```

You can also add new modifiers by creating a new key under `typography`.

```javascript
// tailwind.config.js
module.exports = {
  theme: {
    extend: {
      typography: {
        '3xl': {
          css: {
            fontSize: '1.875rem',
            h1: {
              fontSize: '4rem',
            },
            // ...
          },
        },
      },
    }
  },
  plugins: [
    require('@tailwindcss/typography'),
    // ...
  ],
}
```

If you want to delve into more detail, you can check out the [repository](https://github.com/tailwindlabs/tailwindcss-typography).
How to create Exam/Registration Number or pin in php/laravel
Tags: laravel
Published: 2021-11-19 20:25:10

To create an exam Number pin in php/laravel. You can achieve that using this approach


```php
function reg_number($id)
        {
            $regNum = '';
            $uniqueId = str_pad($id, 4, '0', STR_PAD_LEFT);
            $date = date('y');
            $regNum = "SCH" . '\\' . $date . '\\' . $uniqueId;
            return $regNum;
        }; 

```

The function accepts a single parameter.

The function starts with an initialised $regum variable followed by a variable  `$uniqueId` where we use str_pad() php native function that takes the first parameter which can be any positive integer, followed by a digit, for example, `4`  that determines the number of zeros which is the 3rd parameter, `'0'` then the zeros (0s) are appended to the left by `STR_PAD_LEFT`

A typical result is as follows:
```php
 echo str_pad(6, 4, '0', STR_PAD_LEFT);

// 0006
```

Next, we will need to get the last two digits in a typical calendar year with:
```php
$date = date(y);
echo $date;
// 21 
```

Then actual variable, $regNum, is where we concatenate the school name, say `Sch` followed by a backslash then year as `$date` and lastly the unique id number as `$uniqueId` then we return `return $regNum`;
Typical result is :
```php
 echo reg_number(6);
// SCH\21\0006

```
Reminder — Join the GitHub Actions Hackathon 2021 on DEV ⏰
Tags: meta, actionshackathon21
Published: 2021-11-25 00:11:29

---
title: Reminder — Join the GitHub Actions Hackathon 2021 on DEV ⏰ 
published: true
description: A reminder for those of you participating in the GitHub Actions Hackathon this year — or those considering it! 
tags: meta, actionshackathon21
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kewek3tv0gf03xftufuw.png
---

#### **This year's GitHub Actions Hackathon on DEV closes on December 8th, 2021 @ midnight PST** _(i.e. 8 AM UTC the following day)_

--- 

It's been so much fun watching submissions come in for the **[2021 GitHub Actions Hackathon on DEV](https://dev.to/devteam/join-us-for-the-2021-github-actions-hackathon-on-dev-4hn4)**. I highly encourage all of you to check out all the submissions so far — impressive stuff!

As a reminder, this contest challenges you to utilize GitHub Actions (either new or existing) to create a customized and _usable_ workflow across five categories (Maintainer Must-Haves, DIY Deployments, Interesting IoT, Phone Friendly, & Wacky Wildcards). The reward? DEV Community glory (signaled with a limited-edition badge) — oh, and a chunk of the $10,000 cash prize pool plus additional swag 🤑 

### **[>> Full details and participation rules here](https://dev.to/devteam/join-us-for-the-2021-github-actions-hackathon-on-dev-4hn4)**

---

### **Additional resources**

> _If you have any questions about Actions, GitHub, or the hackathon in general, please refer to this help thread, which is being monitored by the GitHub and DEV teams_:

{% link https://dev.to/devteam/github-actions-hackathon-2021-help-thread-1lk0 %}

> _If all you need is some positive encouragement or if you want to connect with other participants, leave a comment in this thread_:

{% link https://dev.to/devteam/share-your-github-actions-hackathon-2021-updates-57k %}

---

## Happy coding and enjoy this challenge! Two weeks remain!
Using async runtimes together
Tags: rust
Published: 2021-11-27 06:06:34

## Using both Tokio and async-std together

### Option 1 using `async-compat`

``` rust
// async-compat = "0.2.1"
// async-std = {version = "1.10.0"}
// tokio = { version = "1", features = ["full"] }
use async_compat::Compat;
			  
async fn say_hello() {
    println!("Hello, world!");
}
			  
fn main() {
    async_std::task::block_on(Compat::new(async {
   tokio::spawn(async { 
       say_hello().await; // some async function
       println!("this is also hello")
   });
    }));
}
```

### Option 2 using async-std's `tokio1` runtime

``` rust
// async-std = {version = "1.10.0", features = ["attributes", "tokio1"]}
// tokio = { version = "1", features = ["full"] }
			  
async fn say_hello() {
    println!("Hello, world!");
}
			  
#[async_std::main]
async fn main() {
    let t = tokio::spawn(async {
   say_hello().await; // some async function
   println!("this is also hello")
    });
    t.await.unwrap()
}
```
Make Custom Blade If Directive - Laravel
Tags: laravel, php, programming, beginners
Published: 2021-11-27 09:39:07

Let's start quickly if we want to define admin areas via If Directive We start User.php in Models
```php
public function isAdmin(): bool 
{
  return $this->type === 'admin';
}
```
in blade use isAdmin()
```blade
@if(auth()->user()->isAdmin())
  For Admin
@endif
```
To make the code more interesting in AppServiceProvider.php 
```php
public function boot()
{
   Blade::if('admin', function(){
     return auth()->user()->isAdmin();
   });
}
```
in blade use @admin
```blade
@admin
   For Admin
@endadmin
```
We can check if the user is logged in or not by check() 
```php
public function boot()
{
   Blade::if('admin', function(){
     return auth()->check() && auth()->user()->isAdmin();
   });
}
```
We can also use else
```blade
@admin
  For Admin
@else
  Not Admin
@endadmin
```
I hope you enjoyed the code.
A look at the ch CSS unit
Tags: css
Published: 2021-11-27 12:53:52

A while ago, I wrote about the [Tailwind typography plugin].
I was pretty blown away by how easy, and readable big text elements become.

After researching their applied styles, I've noted the prose class actually goes off on the `ch` unit.

```css
.prose {
    max-width: 65ch;
}
```

This is based on the width of the 0 character for a specific font!
Yes, so changing the font might affect this.

And the result is that it actually makes a super readable width.

## Seeing the ch unit in action

Let's give this a try and make a demo with it.

For the HTML, we render two sections with different classes to represent the different fonts.

```html
<section class="georgia">
  <p>copy</p>
</section>
<section class="helvetica">
  <p>copy</p>
</section>
```

Let's add some basic styling so we can see these two sections under each other.

```css
body {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  margin: 0;
}
section {
  display: flex;
  align-items: center;
}
p {
  max-width: 65ch;
}
.georgia {
  font-family: Georgia, serif;
}
.helvetica {
  font-family: helvetica, sans-serif;
}
```

As you can see, we use the same `max-width` value for both elements, but once we see the end result, the one is bigger.

![CSS ch unit in action](https://cdn.hashnode.com/res/hashnode/image/upload/v1637045759612/0DRii0KY2.png)

The image above shows that the top element rendering the `Georgia` font is wider.
This is caused by its `0` (zero) being wider than the Helvetica font set.

You can also have a play with it yourself in this Codepen.

{% codepen https://codepen.io/rebelchris/pen/BadGOag %}

## Extra reading

Shawn wrote this great article using this `ch` unit and just 100 bytes of CSS to make anything look great!

Here are his magic bytes:

```css
html {
  max-width: 70ch;
  padding: 3em 1em;
  margin: auto;
  line-height: 1.75;
  font-size: 1.25em;
}
```

You can read the [full article on Shawn's blog](https://www.swyx.io/css-100-bytes/).

To wrap this up, the `ch` unit is super powerful yet a bit unpredictable as the size might change.

I really like it, as I don't do static pixel design anyway, but I'm looking forward to hearing your thoughts on the `ch` unit!

### Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on [Facebook](https://www.facebook.com/DailyDevTipsBlog) or [Twitter](https://twitter.com/DailyDevTips1)
Templatico -- A RESTful API template 
Tags: productivity, opensource, javascript, api
Published: 2021-11-27 15:50:17

For many self-taught front end developers, migrating from one stack to another could be very heart breaking 😬.

# Prologue
Had my fair share of the ordeal when I tried spinning up a RESTful API with PHP in a Vue - PHP project. The worse part of the tale is dealing with CROS.

## Templatico to the rescue
So lately, I lay hold of Node.js, tried building an API the end of the story is initializing a lil project that let you spin up RESTful API in spilt second. 


I look forward to having more contributors to make the project more robust and of easy use for all🙂💃

See the project on GitHub : [Templatico](https://GitHub.com/Opeolluwa/Templatico)
Follow me on Twitter : [@_opeolluwa](http://Twitter.com/_opeolluwa)