teleren/devto huggingface dataset:
TS sort helper
Tags: typescript, snippet, vscode
Published: 2020-01-07 19:49:00

Instead of writing a sort function every-time, I have created a neat little helper function, and I wanted to share it with you all.
As it uses generics it works on any Array of elements that have keys.

```ts
sort<T>(list: T[], sortBy: keyof T, direction: 'asc' | 'desc' = 'asc') {
  const dir = direction === 'asc' ? 0 : 2;
  return list.sort((a, b) => {
    if (a[sortBy] > b[sortBy]) {
      return 1 - dir;
    }
    if (a[sortBy] < b[sortBy]) {
      return dir - 1;
    }
    return 0;
  });
}
```

The cool thing is that it get's type hints while you are writing, so after specifying the list to work on, Intellisense prompts you for the sortBy parameter solely on what keys exist in the type.

![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/8tykb3ncohqn7jwsiyhk.png)

Let me know if you find this helpful.
OpenNMS Horizon 25.1.2 (Pierogi) Released
Tags: releases
Published: 2020-01-13 17:46:59

---
title: OpenNMS Horizon 25.1.2 (Pierogi) Released
published: true
date: 2020-01-07 19:38:46 UTC
tags: Releases
canonical_url: https://opennms.discourse.group/t/opennms-horizon-25-1-2-pierogi-released/939
cover_image: https://i.imgur.com/74fmzvG.png
---

Release 25.1.2 is the fourth release in the Horizon 25 series.

It contains a number of alarm classification bug fixes and performance improvements, flow enhancements, and more.

The codename for 25.1.2 is *[Pierogi](https://en.wikipedia.org/wiki/Pierogi)*.

##### Bug

* possible issue in JCIFS Monitor - contiously increase of threads - finally heap dump (Issue [NMS-12407](http://issues.opennms.org/browse/NMS-12407))
* Wrong links in the Help/Support page (Issue [NMS-12418](http://issues.opennms.org/browse/NMS-12418))
* Classification Engine reload causes OOM when defining a bunch of rules (Issue [NMS-12429](http://issues.opennms.org/browse/NMS-12429))
* TCP Listeners are broken (Issue [NMS-12430](http://issues.opennms.org/browse/NMS-12430))
* Cannot define a specific layer in topology app URL (Issue [NMS-12431](http://issues.opennms.org/browse/NMS-12431))
* Classification UI: Error responses are not shown properly (Issue [NMS-12432](http://issues.opennms.org/browse/NMS-12432))
* Classification Engine: The end of the range is excluded, which is not intuitive (Issue [NMS-12433](http://issues.opennms.org/browse/NMS-12433))
* Ticket-creating automations are incorrectly enabled by default (Issue [NMS-12439](http://issues.opennms.org/browse/NMS-12439))
* Enable downtime model-based node deletion to happen when unmanaged interfaces exist (Issue [NMS-12442](http://issues.opennms.org/browse/NMS-12442))
* Improve alarmd Drools engine performance by using STREAM mode (Issue [NMS-12455](http://issues.opennms.org/browse/NMS-12455))

##### Enhancement

* Refactoring of the Cassandra installation instructions (Issue [NMS-12397](http://issues.opennms.org/browse/NMS-12397))
* SNMP detector should use snmp profiles (Issue [NMS-12406](http://issues.opennms.org/browse/NMS-12406))
* Allow telemetry flows to balance across Kafka partitions (Issue [NMS-12427](http://issues.opennms.org/browse/NMS-12427))
* Add system test for IpfixTcpParser (Issue [NMS-12434](http://issues.opennms.org/browse/NMS-12434))
* Associate exporter node using Observation Domain Id (Issue [NMS-12435](http://issues.opennms.org/browse/NMS-12435))
How to Handle Logging in Laravel
Tags: laravel, laravel6, laravelcodesnippet
Published: 2020-01-08 17:51:24

---
title: How to Handle Logging in Laravel
published: true
date: 2020-01-07 19:12:39 UTC
tags: Laravel,Laravel 6,Laravel Code Snippet
canonical_url: https://codebriefly.com/how-to-handle-logging-in-laravel/
---

 ![How to Handle Logging in Laravel](https://codebriefly.com/wp-content/uploads/2020/01/How-to-Handle-Logging-in-Laravel.jpg)

In this article, we will discuss “How to Handle Logging in Laravel”. Laravel logging is quite simple and easy to manage. By default, all the error writes in the file located at “/storage/logs/laravel.log”. Yes, it’s easy to get the error information in this file. But day by day it’s getting bigger and than not so […]

The post [How to Handle Logging in Laravel](https://codebriefly.com/how-to-handle-logging-in-laravel/) appeared first on [Code Briefly](https://codebriefly.com).
How far can you take the JAMstack?
Tags: jamstack, jamuary
Published: 2020-01-07 19:05:56

Critics have often made the argument that the JAMstack doesn’t scale well despite its many benefits like improved site performance and better security. This criticism isn’t without reason. In the worst of cases, frontloading your build process can result in lengthy build times. It can also mean compromising on core implementation details by relying on external APIs, not to mention having to trust that an API will be available and consistent in the long run. However valid these criticisms may be, the power of the JAMstack and its ability to scale comes from its flexibility. The JAMstack by design gives developers the option to curate a desired architecture for a site and iteratively work on functionality without holding back deploys to production. This is possible because of the vast and growing API ecosystem. With access to so many external third party services, developers can prototype a site quickly and offload complex tasks to APIs. What’s more, the decoupled, compartmentalized approach of using single purpose services (an auth service that handles authentication, a payments service to handle payments, a CMS to handle content etc) means there is room to switch them out or even build out a custom API down the road. 

The examples of companies both small and large who have bet on the JAMstack for scalability and performance is extensive and rapidly growing. If you’re curious to learn just who these companies are, check out my earlier post on [Who is using the JAMstack?](https://dev.to/shortdiv/who-is-using-the-jamstack-3a59) and dive into videos from JAMstack conf 2019 where companies like [Restaurant Brands International](https://www.youtube.com/watch?v=dKBDUhGi76o), [Loblaw](https://www.youtube.com/watch?v=6VGu4PvEBag) and [Citrix](https://www.netlify.com/blog/2019/06/12/jamstack_conf-nyc-session-recap-citrix-delivers-better-ux-with-less-overhead-using-jamstack-and-netlify/?utm_source=devto&utm_medium=citrixjamstack-div&utm_campaign=devex) cover enterprise use cases for the JAMstack.
Can't make a search on Dev.To :(  
Tags: question, devto
Published: 2020-01-07 18:36:14

---
title: Can't make a search on Dev.To :(  
published: true
description: 
tags: question, dev.to
---
Every time I try to do a search here I get a blank screen, with the normal styles and menus of Dev.To but with nothing in the result .. same with the app on Android.
Will it have something to do that I access from Cuba?
Freelance Software Consulting Contract [TEMPLATE]
Tags: software, contract, freelance, template
Published: 2020-01-07 18:34:56

---
title: Freelance Software Consulting Contract [TEMPLATE]
published: true
description: My consulting agreement, templatized! Free to use :)
tags: software, contract, freelance, template
---

The first major hurdle to signing my first customer was drafting a consulting agreement that fit my needs. The few free templates available online either felt too restrictive for the developer or didn't seem robust enough to offer real assurance for either party.

Below is a template version of the agreement I use with freelance customers. It is a 30 day agreement that automatically renews.
[Custom Software Consulting Agreement [template]](https://docs.google.com/document/d/1he7H0W6vSkoTqbrEHCcvNrfK7ZHwVlx43vrrqitdvts/edit?usp=sharing)

Some features of this contract include:
- terms of payment
  - invoicing on the 1st and 15th
  - expected payment within 15 days of invoice
  - expectations about invoice disputes
  - late fees
- expectations about acceptance testing
- limited liability for developer
- terms of termination
- use of software for reference in personal sales and marketing
- protections for customer
  - ownership of software
  - intellectual property
  - confidentiality

Please download and modify to meet your needs and feel free to suggest edits or comment in the google doc :)
Operator Overloading in JavaScript, yes you can!
Tags: javascript
Published: 2020-01-07 18:11:19

It struck me that it would be nice to have some form of ByteString in JavaScript utilizing `TextEncoder` but instead of having some fancy newing up and going through a couple of hoops to make something that couldn't be handled like a string anymore what if a user could just do this.

``` js
b`hello world`;
```

And here is what the idea is based on, Rust's byte string.

``` rust
b"hello rustations";
```

The JavaScript version would take on the form of a tagged function for a template literal, that's cool in itself, it never occurred to me that we could make such psudo primitive types. Okay what would the Byte string return? In theory it should return a Uint8Array of unicode utf8 encoded bytes, this is all doable so far. But what if I want to concatinate them?

JavaScript doesn't officially offer the ability to change what `+` does, but a couple of languages do, this is known as operator overloading, changing an oporators behaviour on a type that you own. Therefore if I want to do:

``` js
b`hello` + b`world` // TypedArray + TypedArray 😵
```

Unfortunately though this is possible it does mean that I must provide the return value as part of an API, remember the result of this string notation is Not a string, it's a Uint8Array, you cannot add 2 TypedArrays together, so the API version could be kind of useful, a bunch of methods on my type would make it feel just a bit more native.

Here's how it's done:

``` js
function b(str) {
   const _value = str[0];
   return {
      _value,
      toUtf8Bytes() {
         return new TextEncoder().encode(_value)
      },
      valueOf() {
         // When the interpreter asks for the value of this object we give it the original string.
         return _value;
      }
   }
}
```

The `valueOf` overides the method used by the interpreter to compute and display values in Console etc etc, as far as JavaScript is concerned, this is a regular string, Meaning that any time I do use any operator, the `valueOf` will be called like a setter getter. In my example in fact it's like I'm adding 2 objects together but tricking the interpreter into thinking it's a string. Don't worry if this is safe, everything is an object in JavaScript anyway it's not that wierd. What would work even better would be a es6 class instance of ByteString extending String, Anyway I found this absolutely fascinating and could be an incredible technique, I hope you did learn something too.

### But why?
Post note, you can use interpolation syntax with this (with some modifications as to how you put the pieces back together) and pass this to webgl or Wasm really easily.

If byte strings are not your thing, what about a Vector class instance you could just add together or an abstraction of the CSSOM units, I can think of a lot of cool uses for this *ahem* hack.
2020 Goal: Organize my notes and internalize knowledge by writing short essays.
Tags: career, productivity
Published: 2020-01-07 18:08:49

While listening to various software and tech podcasts, I find tons of great insights. Sometimes between the lines, sometimes in seemingly unrelated shows.

Over time I collected lots of quotes and notes from episodes I listened to.

My New Year's Resolution is to revisit and compile them into short essays.

While doing such, I am connecting the dots between seemingly unrelated notes and explore common concepts. 

Writing it down in the form of an essay requires additional research and helps internalize the knowledge.

Sharing it with you is learning in public, which is also one my 2020 goal :)

Here is the link to my publication
https://altabits.substack.com


If you have tons of notes and little incentive to organize and learn from them, try this approach!
Upload to S3 with CircleCI orbs - Building SaaS #22
Tags: python, django, saas
Published: 2020-01-07 18:02:51

{% youtube KgXF6qyS-hQ %}

In this episode, we worked on uploading to S3.  We took the Shiv app from previous streams that we built on CircleCI and used their new orbs feature to deliver the app to an S3 bucket for later deployments.

Show notes for this stream are at [Episode 22 Show Notes](https://www.mattlayman.com/building-saas/upload-s3-circleci-orbs/).

To learn more about the stream, please check out [Building SaaS with Python and Django](https://www.mattlayman.com/building-saas/).
Grouping Related Methods Together in an Object in Vue
Tags: vue
Published: 2020-01-07 18:00:28

---
title: Grouping Related Methods Together in an Object in Vue
published: true
description:
tags: vue
---

tl;dr: https://stackoverflow.com/a/59614452/34806

When first working with AngularJS about 6 years ago I was a bit distrurbed by the the lack of organization allowed within `$scope` --- both attributes and methods could be added anywhere in any order.  So I asked the following question on stackoverflow: https://stackoverflow.com/q/21285627/34806

In reply I not only got validation for my design, but also informed of an important, if esoteric reason, for why my idea was a good one in a way I'd not even thought of.  When I moved to Vue years later, this was one of the improvements that I recognized: data was in `data` and methods in `methods`

Sometimes though you might like to further organize your Vue methods.  For instance, if all handlers could reside within an `on` object, then it would be a matter of looping over them to nullify them in a beforeDestroy/destroyed hook lifecycle method (but be careful as noted here: https://dev.to/dexygen/linus-borg-s-nor-other-expert-s-advice-not-to-be-followed-blindly-1712)

There are a number of attempts at solving this given at: https://stackoverflow.com/questions/36108953/is-it-possible-to-nest-methods-in-vue-js-in-order-to-group-related-methods/ but IMO not of them is particularly clean.  My idea is to not add this object containing methods, to `methods`, but rather, to declare them in the `created` hook:

    created() {
      this.on = {
        test: () => {console.log(this)}
      }
      this.on.test();
    }

See this codepen https://codepen.io/dexygen/pen/povpxqy and open developer tools to see what gets logged.
🔥 5 Things Your Browser Can Already Do
Tags: webdev, pwa, chrome
Published: 2020-01-07 17:46:34


These features are incredibly powerful for building Progressive Web Apps and fascinating the user.

In the last years, browsers have implemented many features focused on performance and security, but other very interesting ones have been taking place, bringing news about *user experience*.

I gathered the recent features that caught my attention. If you know others, leave in the comments so I can add it in this article :)

## Credential Management API

Allows the user to login using your own browser, avoiding the need to implement forms with login / password.

[https://developers.google.com/web/fundamentals/security/credential-management/](https://developers.google.com/web/fundamentals/security/credential-management/)

## Web Share API

Allows the user to share links and files with other device apps (WhatsApp, Instagram, Notes, etc.)

[https://web.dev/web-share/](https://web.dev/web-share/)

## Web Payments API

Allows the user to make credit card transactions using their own browser. User can control sensitive information, select credit card, etc. Very cool!

[https://developers.google.com/web/fundamentals/payments](https://developers.google.com/web/fundamentals/payments)

## Picture-in-Picture

Allows the user to continue playing video content by overlaying other apps in the corner of the screen.

[https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture](https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture)

## Web Speech API

Allows the browser to "hear" and "understand" audio from the user's microphone. That way you can use voice commands or maybe even implement a new Siri.

[https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture](https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture)

Have you used any of those? Share it in the comments!
A simple blog tool
Tags: github, dev, bash
Published: 2020-01-07 17:44:27

---
title: A simple blog tool
published: true
tags: github, dev, bash
---

# Use bash github actions to (cross-)post to dev.to

I want to start a series a tutorial about [Gwion](https://github.com/fennecdjay/Gwion),
It should be part of Gwion's [doc](https://fennecdjay.github.io/Gwion/).
as well as available on [dev.to](https://dev.to),

[devto.sh](https://github.com/fennecdjay/devto.sh) is a part of this process,
the one that takes a directory of markdown files and publishes the content to [dev.to](https://dev.to).

It is a both a [github action](https://github.com/features/actions)
and a [template](https://help.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-from-a-template),
so it should be easy for anyone to reuse :smile:

---
EDIT: looks like we can add tags

<!-- DO NOT EDIT BELOW LINE. added by devto.sh -->
<!-- DEVTO_POSTID 232689 -->
Learning Algorithms Through Games
Tags: games, showdev, algorithms, javascript
Published: 2020-01-07 17:43:03

I'm studying algorithms through games. I recently re-created one of those number slider games. As a kid, I remember getting these free puzzles from the flight crew.

<img src="https://thepracticaldev.s3.amazonaws.com/i/0itfdwe9y8pdmaknczq8.gif" />

See the code here:

https://github.com/babakness/number-slider

## Algorithm

Making this game presents a number of neat challenges. The key algorithm to making this work is, given a matrix of numbers with size N*M, and empty piece, E; move each piece from a select piece P<sub>0</sub> toward E.

Suppose we number each piece adjacent to P<sub>0</sub> in an increasing fashion, ie P<sub>1</sub>, P<sub>2</sub>, ...P<sub>n</sub> until we reach the empty square E. After the move, P<sub>n</sub> will occupy the position of E, and each piece before it will move likewise until P<sub>0</sub> is in the position of P<sub>1</sub>.

Finally, after P<sub>0</sub> moves, the piece E is placed in its prior position.

## Game Design

This game can be thought of as breaking down following the MVC structure. The main algorithms can be thought of as the Model, and the code manipulates the DOM as the Controller. Finally, the html page and the styles involved can be considered the View.

I use these names loosely, the essential idea is to break up our code into just enough abstractions to organize our code; but not so many as to create confusion.

## Vanilla JS

No frameworks! The game uses the DOM API directly. It can be a good review of how to use regular DOM and CSS animations to achieve game play animations.

## Useful functions

Some pretty nice functions came out of this. 

Here is a function that throttles calls to an async function--only allowing the function to be called again after it has completed it task.

```ts
/**
 * HOF to prevent calls to an async function before it resolves
 * @param fn async function to throttle until resolve
 */
function throttleAsyncCalls<A,B>( 
    fn: (...args: A[]) => Promise<B> 
  ) {
  let wait = false
  return async function( ...args: A[] ) {
    if( wait === true ) {
      return
    }
    wait = true
    let result = await fn( ...args )
    wait = false
    return result
  }
}
```

How about this one, it dispatches a mouse click when you click "enter" on an element. This is useful for a11y.

```ts
  /**
   * When enter is pressed on an element, dispatch a click event on that element
   * @param event Keyboard Event
   */
  function routeEnterToClick( event: KeyboardEvent ) {
    let mouseClick = new MouseEvent( 'click', { bubbles: true } )
    if( event.key.toLowerCase() === 'enter' ) {
      event.target.dispatchEvent( mouseClick )
    }
  }
```

And much more 😁

## Play around!

Have fun!

https://number-slider.algogames.dev

Follow me on Twitter at <a href="https://twitter.com/babakness">Babakness</a>.
7 jQuery Practical Tips - Javascript Tips
Tags: javascript, jquery, webdev
Published: 2020-01-07 17:34:48

### 1, Create "back to top" scroll animation

```javascript
$('a.top').click(function (e) {
    e.preventDefault();
    $(document.body).animate({scrollTop: 0}, 800);
});
```

### 2, Use `detach` to detach element first if you have heavy DOM operations

```javascript
$ele = $container.first().detach();
// a lot operation on this $ele
// then append it back
$container.append($ele);
```

### 3, Add `disabled` and `enabled` function to jQuery element object

```javascript
$.fn.disabled = function () {
    return this.prop("disabled", true);
}
$.fn.enabled = function () {
    return this.prop("disabled", false);
}
// To use it:
$btn.disabled();
$btn.enabled();
```

### 4, If an image failed to load, show a customized broken image

```javascript
$('img').on('error', function () {
    $(this).prop('src', 'img/broken.png');
});
```

### 5, Set global error (404, 500 response) handler for ajax request

```javascript
$(document).ajaxError(function (e, xhr, settings, error) {
    console.log(error);
});
```

### 6, Forbid user select text inside an element 

```javascript
$.fn.disableSelection = function() {
    return this.attr('unselectable', 'on')
               .css('user-select', 'none')
               .on('selectstart', false);
}
// To use it:
$txt.disableSelection();
```

### 7, In page search: hide DIVs which doesn't contain searched keyword

```javascript
var search = $('#search').val();
$('div:not(:contains("' + search + '"))').hide();
```