teleren/devto huggingface dataset:
Reviving old code.
Tags: perl, hacktoberfest, cpan
Published: 2020-10-11 02:42:17

One of the joys of Perl is the rich community support that it has enjoyed over the years. Even today when other languages are surging in popularity, the Perl community is still going strong.

One of the things I ask myself every Preptember is "what will I do for Hacktoberfest?" This year, I decided that I wanted to spread the love out a little bit. In addition to banging away on some of my own projects, I also wanted to modernize at least one older CPAN module, and I also wanted to see if I could help out with one of the sponsors' issues.

`Data::JavaScript` is a module that I used _waaaay_ back when. It hasn't had much love lately, and in light of JSON, many folks kinda view it as irrelevant. Many of its use cases do indeed seem duplicative of JSON, and there's already excellent JSON support. However, there are some folks still using this module, and with Perl 7 coming out it really needed a little bit of TLC. What TLC did it need? Well, I made a list!

## 1. Implement best practices

It needed to be updated to more modern Perl best Practices. In Perl, we have warnings, errors, but we also have `Perl::Critic`. I ran `perlcritic` and started hammering out issues until the issues stopped coming. Then I ran tests to make sure I didn't break anything.

## 2. Configure CI

It needs CI, with coveralls, that way I can make sure I don't accidentally forget to update tests. For this, I chose GitHub actions, as most of the other CI providers don't really support Perl terribly well (most of them never really did). I got this working, and now I can see that Coveralls shows I have 90% test coverage, which is pretty good. This level of code coverage should help me identify any breakages.

## 3. Review dependencies

Normally, you would review all of the dependencies in use. It's super important to make sure that a security review is performed for those dependencies, as out-of-date dependencies are one of the largest threat vectors for a piece of code.

Luckily for me, this module is almost entirely self-contained. I added a few dependencies as part of implementing CI and Perl Best Practices, but there were none when I started (and the ones I added are really common).

## 4. Develop a roadmap

Once you've finished dusting off the code in the prior steps, it's super important to develop a roadmap for the application. Since no application is never really finished until it's fully deprecated, you really want to spend some time coming up with functional improvements for the application. I like to use GitHub Issues for these, as it makes it clear to other people that I'm thinking about the module when they're considering whether or not they want to use it.

## Conclusion

I think this is a pretty good pattern for reviving most legacy code. If you've got thoughts, I'd be happy to read them.

If you'd like to contribute to any of the modules I maintain, please review:

- [`Net::AMQP::RabbitMQ`](https://github.com/net-amqp-rabbitmq/net-amqp-rabbitmq)
- [`Data::JavaScript`](https://github.com/manchicken/data-javascript)

They're both opted in to Hacktoberfest.
To Optimize: Github
Published: 2020-10-11 02:24:05

Github, as an online platform built around the open source tool "Git," was not just utilized for coding related projects. One of the key features of Github is it serves as a repository for binary file platforms such as Word, Excel, and Powerpoint. Thus, Github can be a venue for tutorials and lessons for which a compilation of materials can be stored. Moreover, one may want to use markdown text format because Github cannot merge changes for the said binary files. Even the government had been storing data and laws to Github in markdown format. Data formats such as csv, json, xml, and text format can be hosted as well. Another main function of Github is tracking differences in lines of text files which are not only utilized for coding but also for writing books and music compositions. Its collaborative feature and revision history make it appropriate as writing platform.

Reference:
"Creative Uses for Github" Youtube, uploaded by Joe James, 16 July 2018, 
https://m.youtube.com/watch?v=zVqTLqr6ceQ/xxxxx
A Quick Look At Reacts useState
Tags: react, javascript, codenewbie, 100daysofcode
Published: 2020-10-11 02:22:34

#What's useState?

useState is a react hook. React Hooks are a new feature to React 16.8. Hooks allow us to use things like state, inside of functional components. 

So when you usually make some state for a class component it'll look something like this

```javascript
class FakeDate extends React.Component {
  constructor(props) {
    super(props);
    this.state = {counter: 0};
    this.handleClick = this.handleClick.bind(this);
  }
  
  handleClick = () => {
    this.setState({counter: counter++})
  }

  render() {
    return (
     <div>
      <button onClick={this.onClick}>click to change counter</button>
     </div>
<h2>It is {this.state.date}.</h2>)
  }
}

```

Now with hooks, we can utilize useState and write something like this

```javascript
const Counter = () => {
 const [counter, setCounter] = useState(0)
 const onClick = () => {
   setCounter(counter++)
 }
 return (
  <div>
   <button onClick={onClick}>
    click me to change counter
   </button>
   <h1>{counter}</h1>
  </div>
 )
}

```

Pretty cool right? 

##A Deeper Look

When we useState, we no longer require a constructor or state object. Instead, we declare our state variable along with its setVariable partner. Now anytime you want to update that specific state variable you just call setVariable and pass it a value.

##Is useState Better State?

Should you use the useState hook or the traditional state lifecycle? 

Well, it depends if you want to use a functional or class component. 

*useState is simply a tool of convenience.*

There will still be times where a class component is more useful than a functional component. Assess your needs and the answer will be obvious.

#Conclusion

We have gone over the useState hook. I hope you've gained some knowledge from this. If you have any questions feel free to reach out to my [twitter](https://twitter.com/KevSmss). 

Thank you for reading and keep coding!
Initialize Money::Currency on the test context
Tags: ruby, unittest, rubymoney
Published: 2020-10-11 02:16:55

RubyMoney is a great gem to handle real-world money.
It provides the default setting, and we can overwrite it via business requirements.
On the production environment, if we set the setting up once(it could be in the initializer), no need to update it in many cases.
However, it could happen in the test context.

In this article, I explain how RubyMoney manages the currency setting and how to initialize it when we need it.

First of all, we can set the customized currency as below


```ruby
cad = Money::Currency.find(:cad)

cad.name # => Canadian Dollar

Money::Currency.register(
  :priority            => cad.priority,
  :iso_code            => cad.iso_code,
  :name                => 'Something Different',
  :subunit             => cad.subunit,
  :subunit_to_unit     => cad.subunit_to_unit,
  :thousands_separator => cad.thousands_separator,
  :decimal_mark        => cad.decimal_mark
)

cad = Money::Currency.find(:cad)
cad.name # => Something Different
```

`Money::Currency` manages the currency setting as an instance variable called `@table`, then it should be ok to reset the instance variable.
But it provides the interface to access the table as a class method so that we should be able to reset the table like

```ruby
 Money::Currency.instance_variable_set('@table', nil)
 Money::Currency.table # => reloading the initial setting
```

See? How easy it is! But wait, we still keep getting the overwritten setting.

```ruby
cad = Money::Currency.find(:cad)
cad.name # => Something Different
Money::Currency.instance_variable_set('@table', nil)
Money::Currency.table
cad = Money::Currency.find(:cad)
cad.name # => Something Different. We still get the overwritten name!
```

Why does that happen?
That is because, if it is overwritten once, that setting should have consistency through a ruby process.
To handle it, the library manages the setting as a class variable, so that we do not need to care about the currency setting any more to develop the app.
Given that, we should initialize that class variable like below.


```ruby
cad.name # => Something Different
Money::Currency.class_variable_set('@@instances', {})
Money::Currency.instance_variable_set('@table', nil)
Money::Currency.table
cad = Money::Currency.find(:cad)
cad.name # => Canadian Dollar
```

Yay! If you write it on the spec_helper or something, your tests don't depend on `Money::Currency` context.

The latest master of `RubyMoney::Money` provides API, `Money::Currency.reset!` to handle it!
[This link](https://github.com/RubyMoney/money/pull/941) is the PR of this feature.
If anyone wanna use it, pull the latest master, and there you go.
I hope the next version of `RubyMoney::Money` includes this update!
Introduction to Creating a JavaScript Game
Tags: javascript, requestanimationframe, gamedev, game
Published: 2020-10-11 01:53:22

{% youtube UUFPEgRKwf4 %}

In this video we will create a simple javascript game. We will create a circle aka the little green blob that we will move around the screen. You will learn about taking input from the keyboard to move a character on the screen. Create a form of collision detection by detecting the edge of the screen. Lastly we will create a game loop which continuously draws the screen. We will implement the game loop with 2 different methods setInterval and requestAnimationFrame.  

With the skills we learn from this introduction to game development we will then tackle games such as Pac-Man, Tetris and Snake in later videos.
Mediator Pattern
Tags: designpatterns, java, pattern, behavioral
Published: 2020-10-11 01:39:24

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/sc4u7pmnldso23p9slio.gif)

#Participants
* Mediator: defines an interface for communicating with Colleague objects
* ConcreteMediator: implements cooperative behavior by coordinating Colleague objects.
Knows and maintains its colleagues
* Colleague classes: each Colleague class knows its Mediator object. Each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague

#Code#
```java
public class Main {

	public static void main(String[] args) {
		ConcreteMediator m = new ConcreteMediator();
		ConcreteColleague1 c1 = new ConcreteColleague1(m);
		ConcreteColleague2 c2 = new ConcreteColleague2(m);
		m.setColleague1(c1);
		m.setColleague2(c2);
		c1.send("From c1");
		c2.send("From c2");
	}
}

public interface Mediator {
	void send(String message, Colleague colleague);
}

public class ConcreteMediator implements Mediator {

	private ConcreteColleague1 colleague1;
	private ConcreteColleague2 colleague2;

	public void setColleague1(ConcreteColleague1 colleague1) {
		this.colleague1 = colleague1;
	}

	public void setColleague2(ConcreteColleague2 colleague2) {
		this.colleague2 = colleague2;
	}

	@Override
	public void send(String message, Colleague colleague) {
		if (colleague == colleague1) {
			colleague2.notify(message);
		} else {
			colleague1.notify(message);
		}
	}
}

public abstract class Colleague {
	protected Mediator mediator;

	public Colleague(Mediator mediator) {
		this.mediator = mediator;
	}
}

public class ConcreteColleague1 extends Colleague {

	public ConcreteColleague1(Mediator mediator) {
		super(mediator);
	}

	public void send(String message) {
		mediator.send(message, this);
	}

	public void notify(String message) {
		System.out.println("Colleague1 gets message: " + message);
	}
}

public class ConcreteColleague2 extends Colleague {

	public ConcreteColleague2(Mediator mediator) {
		super(mediator);
	}

	public void send(String message) {
		mediator.send(message, this);
	}

	public void notify(String message) {
		System.out.println("Colleague2 gets message: " + message);
	}
}
```

#Output#
```
Colleague2 gets message: From c1
Colleague1 gets message: From c2
```

{% github https://github.com/eidherjulian61/design-patterns no-readme %}
{% link https://dev.to/eidher/principales-patrones-de-diseno-13ao
 %}
Hacktoberfest - Week 1
Tags: hacktoberfest, opensource, javascript
Published: 2020-10-11 00:57:43

This October, we're expected to finish 4 pull requests to join the Hacktoberfest. However, consider doing pull requests might be new to some of the classmates and to avoid the competition, we can choose those repos without the Hacktoberfest topic. 

I always want to develop a chrome extension to increase some optional functionalities on Twitter. Therefore, I want to gain some experience in building browser extensions.

I spent 2 days doing research and looking for suitable repos to contribute. I don't want to choose a huge repo with a complicated issue which is way out of my league; but, I don't want to just pick up a small typo issue and make the pull requests. I ended up finding 2 repos that I believe is a little bit challenging but not way too difficult for me.

The first one, which is the one I sent the pull request this week, is a [Countdown Timer Chrome Extension](https://github.com/drgn-hart/Countdown-Timer). They have set time, start, and stop functionalities so far and they need [the pause functionality](https://github.com/drgn-hart/Countdown-Timer/issues/14). I spent some time on how to work on the chrome extension since they haven't had the instructions on how to contribute. I then used 2 days to [complete this feature](https://github.com/drgn-hart/Countdown-Timer/pull/21). Moreover, while I was testing the functionalities, I found that part of the UI design is [not that accessibility-friendly](https://github.com/drgn-hart/Countdown-Timer/issues/20) (yellow background color with white font color). Therefore, I created the issue regarding this, made the changes, and send the PR with the modification. 

This first pull request on Hacktoberfest is intriguing. The feeling of communicating with a total stranger developer and work on her repo is cool. I'm looking forward to working on the other 3 repos with their issues!
How I cured my phone addiction  
Tags: productivity, tutorial, career, discuss
Published: 2020-10-11 00:48:43

Recently, I have noticed that I was being hooked up to my smart phone a lot more than I should. My weekly screen time was so shocking to me. I was spending nearly 23 hours a week which is almost a day. It hit me. I said to myself that this better be a wake up call. 

The steps I took to reduce my screentime and increase productivity 

1. The first step is to understand the problem and accept that it's very unhealthy for a person to spend too much time hooked with a smartphone. 

2. I deleted the app I was wasting my time on. Starting with facebook. Many calls it social detox. First few days I felt the itch to check my notifications but with self restrain, I got over it and I feel so much free of negativity. I feel a lot better with only using messenger and only communicating with very few people. 

3. I stopped purchasing mobile data. I don't know if it worked for anyone else but it worked for me. Without the mobile data, I began to notice my surroundings. I am now enjoying going for walks or uber rides home because I am no longer on my phone. 

4. I increased the numbers of productivity applications on my phone. Deleted unused apps. 

5. I began to use to wifi off button. I no longer feel like it's necessary to leave the wifi on all the time. It's not, they have the on/off button for a reason. I used to be the kind of person who'd leave the wifi on and would get up from the dinner table just to check any popping notification. Now, switching off wifi feels like a bliss. 

6. Establishing a thought that my smart phone is with me all the time but it doesn't means that I should be on it all the time and I should only use it when I need to. This one simple thought helped me to reduce my screen time to 87% this week and I am glad to see that I am actually free from my smartphone's invisible handcuffs. 

I believe we must maintain a balance. I am doing everything I can with my will power to maintain that balance between productivity and entertainment. When it come's to my productivity I am not willing to make any compromises. But it doesn't means that I am willing to spend hours working with no breaks. No way, I take small breaks and big breaks as well while working/learning. Feel free to leave a comment or your thoughts.
Four Pillars of OOP
Tags: javascript, ruby
Published: 2020-10-11 00:39:51

A brief overview of the four pills of Object-Oriented Programming (OOP)

# Question

What are the four pillars of OOP?

# Answer

The four pillars of OOP are **encapsulation**, **abstraction**, **inheritance**, and **polymorphism**.

## Encapsulation
* Encapsulation is the idea of containing the attributes and behaviors of a class within itself. The state is secured and is private to the class. Only the object itself can update the state, and other objects only have access to the object's state through public methods.

## Abstraction
* Abstraction is the way in which we select and present the pertinent information for an object. All the mechanisms under the hood need not be presented, but the high-level data will be. 

## Inheritance
* Inheritance is a way in which an object acquires some/all of the properties of another object. It is a great way to reuse code and build on top of previously created objects.

## Polymorphism
* Polymorphism is distinct from inheritance because the object acquires some/all of the properties of another object, but the object will maintain its own unique methods and functions.

# Conclusion
The four pillars are fundamental to OOP. Commit them to memory!

& Remember... Happy coding, friends! =)
Memoization in JavaScript
Tags: javascript, beginners, codenewbie, 100daysofcode
Published: 2020-10-10 22:46:56


JavaScript and functional programming go hand in hand. There are times when our functions will be expensive in terms of performance. Performing the same functions with the same input over and over again could degrade the experience of the application and it is unnecessary.

**Memoization** is an optimization technique in which we cache the function results. If we provide the same input again, we fetch the result from the cache instead of executing code that can cause a performance hit.

In case the result is not cached, we would execute the function and cache the result. Let's take an example of finding the square of a number.

```javascript
const square = () => {
    let cache = {}; // set cache
    return (value) => {
        // if exists in cache return from cache
        if (value in cache) {
            console.log("Fetching from cache");
            return cache[value];
        } else {
            // If not in cache perform operation
            console.log("Performing expensive query");
            const result = value * value;
            cache[value] = result; // store the value in cache
            return result; // return result
        }
    }
}

const sq = square();
console.log(sq(21)); // Performing expensive query, 441
console.log(sq(21)); // Fetching from cache, 441
```

### Why or when to use it?

* For expensive function calls, i.e. functions that do network calls where the output might not change or functions with large computations or disk I/O.
* For pure functions (where function output stays the same given the same input).
* For functions with a limited range of input but highly recurring.
🐍 Testing exit codes with Pytest
Tags: python, sysadmin, testing
Published: 2020-10-10 22:45:33

---
title: 🐍 Testing exit codes with Pytest
published: true
description: 
tags: python, sysadmin, testing
//cover_image: https://direct_url_to_image.jpg
---
As almost every other sysadmin I know, python is the language of choice to do some scripting. And, as we all know, testing is an important part of any development.

My code is a simple parser that interacts with some Linux commands using [subprocess](https://docs.python.org/3/library/subprocess.html#module-subprocess), which instead of raising an exception it returns something != 0. In fact, the exit code is 2. How to test that with pytest? This is what I did (which might not be _the best_ way to do it):

The parser is pretty simple, this is the `cli.py`:
```python
from argparse import ArgumentParser

def create_parser():
    parser = ArgumentParser()
    parser.add_argument('list', help='List something')
    ...
    return parser
```

The tests:
```python
import pytest
from parser import cli

@pytest.fixture
def parser():
    return cli.create_parser()

def test_something_to_test(parser):
    with pytest.raises(SystemExit) as e:
        # The command to test
        parser.parse_args(['some', 'commands'])
    # Here's the trick
    assert e.type == SystemExit
    assert e.value.code == 2
```
My favorite better design of form and work!
Tags: codepen
Published: 2020-10-10 22:27:58

<p>Please, click to red heart on menu in my work and follow me on Codepen, just visit link (<a href="https://codepen.io/ExpertManSa" target="_blank">https://codepen.io/ExpertManSa</a>)!
Want know, how can i do that?
Just ask it in comments in my codepen work!</p>

{% codepen https://codepen.io/ExpertManSa/pen/pobvYOM %}
Export from Org to Markdown in Spacemacs
Tags: spacemacs, org, export, markdown
Published: 2020-10-10 22:26:40

---
title: Export from Org to Markdown in Spacemacs
published: true
description: This guide is the whole process to export from org into markdown within Spacemacs.
tags: spacemacs, org, export, markdown
cover_image: https://res.cloudinary.com/dmrgfufa4/image/upload/v1602368674/articles/export%20from%20org%20to%20markdown%20in%20spacemacs/background.png
---

Org-mode is one of the coolest features in Emacs and this case Spacemacs. It can be used to write documentation, personal notes, and also schedule your events in an awesome agenda.

In my case, I use Org files to write and export tutorials from one single file to three platforms, which are [Medium](https://medium.com/@roeeyn),[Dev.to](https://dev.to/roeeyn), and [my blog](https://roeeyn.github.io/roeeyn_blog/), using Spacemacs as my main editor. 

To be able to export to a Markdown from an Org file, you need to do the following:


# 1. Make sure you have the markdown layer installed

Having the [markdown layer](https://develop.spacemacs.org/layers/+lang/markdown/README.html#live-preview) installed will give you a better experience when editing markdown files.


# 2. Add the md export backend into Spacemacs

You need to add the `md` value into the export backends variable. The easiest way for me to do this is the following:

Inside Spacemacs type:

    M-x customize-option 

and then type `org-export-backends`.

It will bring a customization buffer in which you can move with the arrow keys, and select the `md` checkbox to enable it, and then press Enter in the `Appy and save` button.

![Modifying export backends](https://res.cloudinary.com/dmrgfufa4/image/upload/v1602368202/articles/export%20from%20org%20to%20markdown%20in%20spacemacs/step1.png "Modifying export backends")


# 3. Verify the exportation

After applying and saving the new export backend, you can do a new export doing the following:

With an org file buffer open, type:

    , e e 

![Exporting menu](https://res.cloudinary.com/dmrgfufa4/image/upload/v1602368203/articles/export%20from%20org%20to%20markdown%20in%20spacemacs/step2.png "Exporting menu")

This will open the export menu, and now we will see the new markdown option available. If you want to create a markdown file from your org file, inside the previous menu type:

    m m 

and this will create a new markdown file from your org file.


# Conclusions

From now on, whenever you want to export an org file to a markdown file, you will only need to follow step 3.

If you find this useful, please consider giving it a like.
Happy hacking!