teleren/devto huggingface dataset:
Func delegates in C#
Tags: todayilearned, csharp
Published: 2019-09-02 06:58:17

Today I added another delegate to Lychen and will likely add it to other things in the near future. This one is the famous (?) `glob` which appears in all sorts of languages.

```csharp
            v8.Script.glob = (Func<string, string[]>)Glob;
```
`Func<>` is different to `Action<>` in that the last parameter inside the angle-brackets defines the return type. `Action<>` is for `void` returns. `Func<>` for everything else (except a third thing that I don't understand yet.)

Glob's implemented like this.
```csharp
        private static string[] Glob(string wildcard)
        {
            var path = Path.GetDirectoryName(wildcard);
            if (path.Length == 0)
            {
                path = ".\\";
            }
            wildcard = Path.GetFileName(wildcard);
            return Directory.GetFiles(path, wildcard);
        }
```
Note that the definition of the delegate must match the implementation. In this case the delegate is declared as having a string input and a string array output. 

Glob uses `System.IO.Path` functions to split the incoming parameter into path and wildcard before giving both to `Directory.GetFiles`. Somewhere down the line I'm going to have to allow for the optional third parameter to `GetFiles` but for now this meets the need.

The other issue is that a non-native array is returned to Lychen. This means that `.length` doesn't work. Instead, you use `.Length` to get the number of items in the array. In fact, `.map` and `.forEach` etc don't work either. There is a fix for this also, but again, the motivation is lacking.
JS Heaps
Published: 2019-09-02 06:54:36

---
title: JS Heaps
published: true
description: 
tags: 
---

/* Heaps is a type of tree.

Binary Heaps is similar to Binary Search Tree, but with different rules.
Each node can have most two child nodes. No order to the left or right,
as long as they are smaller or larger than the parent node.

MaxBinaryHeaps- parent nodes are always larger than child nodes.

MinBinaryHeaps- parent nodes are always smaller than child nodes.

Binary Heaps evens out the left and right and the tree is always compact
rather than one sided.

*/

/*Use array or list to present a heap tree

    special rules: 
    from a parent node, for any index in an array, the left child is placed in 2*index+1,
    the right child is placed in 2*index+2.

    to find the parent node from child nodes, use Math.floor((index -1)/2)

    much like stack/queue, heap can be implemented with array

*/
Glaciary.JS - The best, secure, and fast way to build your next API

Tags: javascript, githunt, node, npm
Published: 2019-09-02 06:53:55

# Glaciary.

> The Rest API framework based on Express.JS and Socket.IO

## Get Started 

Make sure you have [npx](https://www.npmjs.com/package/npx) installed (`npx` is shipped by default since [npm](https://www.npmjs.com/get-npm) `5.2.0`)

```bash
npx create-glaciary-app <my-project>
```

Or starting with npm v6.1 you can do:

```bash
npm init glaciary-app <my-project>
```

Or with [yarn](https://yarnpkg.com/en/):

```bash
yarn create glaciary-app <my-project>
```

## Links
* :book: Docs: [Docs](https://github.com/GabrielLeonte/glaciary-docs)
* :earth_africa: Discord: [Join](https://discord.gg/h3uKEt4)

## Features :fire:
* A simple way to setup a new route or event
* Configurable with a config.glaciary.js file
* Configurable default HTTP route with defaults.glaciary.js
* Configurable default Socket.IO Event with defaults.glaciary.js
* Easy to setup SSL Certificate with defaults.glaciary.js (still testing)
* Simple Debug system

## Incoming Features :smirk:
* Plugins
* Global Store Array
* Local SQLITE3 database

<br/> 

> If you want to contribute with any idea, you're welcome to share it with us :smile:
How to redirect in Koa with TypeScript
Tags: typescript, koa
Published: 2019-09-02 06:11:34

---
title: How to redirect in Koa with TypeScript
published: true
description: 
tags: TypeScript, Koa
---

This post explains how to redirect in Koa with TypeScript.

## How to redirect in Koa

The `redirect()` method is available in the `ctx` object. So to redirect, just call it.

```ts
ctx.redirect(url)
```

## Full example of `ctx.redirect`

```ts
import Koa from "koa";
import _ from "koa-route";

const app = new Koa()
app.use(_.get('/old', async ctx => {
    ctx.redirect('/new')
}))
app.use(_.get('/new', async ctx => {
    ctx.body = 'redirected!'
}))

app.listen(4000)
```

When you send a request to the path `/old`, the server will respond to 302 status. Also, the `Location` header value will be the URL that was passed to the `redirect` method.


```http
HTTP/1.1 302 Found
Connection: keep-alive
Content-Length: 39
Content-Type: text/html; charset=utf-8
Date: Mon, 02 Sep 2019 06:01:51 GMT
Location: /new

Redirecting to <a href="/new">/new</a>.
```
Placeholder images of animals. A simple PHP service.
Tags: php, design, tailwindcss
Published: 2019-09-02 05:33:56

I whipped up a fun little placeholder image service called Wildcard.fun.

https://wildcard.fun


The idea was to make a service that would generate any size image you wanted as a placeholder and size/crop the image to those dimensions.

For the basic structure of the application, I used vanilla PHP in combination with a fast router called "PHRoute - Fast request router for PHP".

https://github.com/mrjgreen/phroute

In order to resize, crop, and compress the images based on the request I used ImageMagick for that.

The images come from Unsplash.com as well.

![image of animal](https://wildcard.fun/r/400/400)


Give it a shot!
Merge-Descriptors Library | JavaScript Library Code Breakdown
Tags: javascript, node, code
Published: 2019-09-02 05:13:02

---
title: Merge-Descriptors Library | JavaScript Library Code Breakdown
published: true
description: Code Breakdown
tags: #javascript, #node, #code
series: ReadCode TV
---

{% youtube QepTcYpAKTo %}

The Merge-Descriptors library is a NodeJs package with more than 8.5million download/week and used by Express. 

In this video, you will learn

* What merge-descriptors are
* Merging JavaScript Objects
* How merge-descriptors package works

[ReadCode TV](https://www.youtube.com/channel/UCG916fExDk8GotibsYmN3nw) is a youtube channel where I go through the codes of libraries to see how they work and learn about different programming concepts and techniques and how they have been applied. The aim is to help us become better programmers. The libraries will come from different languages including JavaScript, Java, Kotlin, PHP, Dart and other languages that I work with.

[Click here](https://www.youtube.com/channel/UCG916fExDk8GotibsYmN3nw) to subscribe.
Follow ReadCode TV on [twitter](https://twitter.com/ReadcodeTV)
What do you think of minimalist UI?
Tags: productivity, discuss
Published: 2019-09-02 04:52:45

There is a lot of software that claims to have the "minimalist UI", but they just end up to hide most of the features to show that their interface is minimalist and the software is simple. 

The key to minimalism isn’t making the interface simple per se. It’s about making it as simple as it needs to be.

There are some of the software with the minimalist interface that actually work. 

1.  [Instagram](https://instagram.com)

Instagram is one of the biggest social media platforms now. Last year, after they underwent the design change, the user experience got so much smoother and easier. 

Now when you scroll your newsfeed on Instagram, you will focus on the content uploaded rather than other clutters in design. 

2. [Medium](https://medium.com)

If you blog everyday, you must know about Medium. One of the best thing with Medium is, you can actually focus on your readings rather than the fancy design or colorful photos that can easily distract you. 

Most recently redesigned last October, the Medium app lets you personalise what kind of blog posts you receive in your feed, and offers a selection of ‘Top Stories’ and 'Editors’ picks' on its homepage. But where it really comes into its own is in the reading experience, which is elegantly and artfully designed for relaxed and enjoyable reading.

3. [Pinterest](www.pinterest.com)

Pinterest is a great source of beautiful and inspirational photos for you.  They have photos to set up as cards. You can create organization and flow in a design. Cards also rely on established user behavior patterns, making UI easy to use. 

Every element lives in a container that relates to a specific action, such as activating a link, filing out a form, or sharing the link.

—

Besides from all of the famous apps, I personally have some SaaS platform with the award-winning UI. For example, for [productivity apps](https://quire.io/compare/best-productivity-apps), we have [Quire](https://quire.io) and [Notion](https://notion.so). 

What's your favorite app?
Gradient View in Swift
Tags: swift, uiview
Published: 2019-09-02 04:16:32

---
title: Gradient View in Swift
published: true
description: How to manage a gradient view in Swift programmatically
tags: swift, uiview
---

Will write a really simple way to make a gradient UIView. You can specify `GradientView` in Stroyboard, then you can modify the UI settings.

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

```swift

import UIKit

@IBDesignable
class GradientView: UIView {
    
    @IBInspectable var cornerRadius: Double {
        get {
            return Double(self.layer.cornerRadius)
        }set {
            self.layer.cornerRadius = CGFloat(newValue)
        }
    }
    @IBInspectable var borderWidth: Double {
        get {
            return Double(self.layer.borderWidth)
        }
        set {
            self.layer.borderWidth = CGFloat(newValue)
        }
    }
    @IBInspectable var borderColor: UIColor? {
        get {
            return UIColor(cgColor: self.layer.borderColor!)
        }
        set {
            self.layer.borderColor = newValue?.cgColor
        }
    }
    @IBInspectable var shadowColor: UIColor? {
        get {
            return UIColor(cgColor: self.layer.shadowColor!)
        }
        set {
            self.layer.shadowColor = newValue?.cgColor
        }
    }
    @IBInspectable var shadowOpacity: Float {
        get {
            return self.layer.shadowOpacity
        }
        set {
            self.layer.shadowOpacity = newValue
        }
    }
    
    @IBInspectable var startColor:   UIColor = UIColor.black { didSet { updateColors() }}
    @IBInspectable var endColor:     UIColor = UIColor.white { didSet { updateColors() }}
    @IBInspectable var startLocation: Double =   0.05 { didSet { updateLocations() }}
    @IBInspectable var endLocation:   Double =   0.95 { didSet { updateLocations() }}
    @IBInspectable var horizontalMode:  Bool =  false { didSet { updatePoints() }}
    @IBInspectable var diagonalMode:    Bool =  false { didSet { updatePoints() }}
    
    override public class var layerClass: AnyClass { return CAGradientLayer.self }
    
    var gradientLayer: CAGradientLayer { return layer as! CAGradientLayer }
    
    func updatePoints() {
        if horizontalMode {
            gradientLayer.startPoint = diagonalMode ? CGPoint(x: 1, y: 0) : CGPoint(x: 0, y: 0.5)
            gradientLayer.endPoint   = diagonalMode ? CGPoint(x: 0, y: 1) : CGPoint(x: 1, y: 0.5)
        } else {
            gradientLayer.startPoint = diagonalMode ? CGPoint(x: 0, y: 0) : CGPoint(x: 0.5, y: 0)
            gradientLayer.endPoint   = diagonalMode ? CGPoint(x: 1, y: 1) : CGPoint(x: 0.5, y: 1)
        }
    }
    func updateLocations() {
        gradientLayer.locations = [startLocation as NSNumber, endLocation as NSNumber]
    }
    func updateColors() {
        gradientLayer.colors    = [startColor.cgColor, endColor.cgColor]
    }
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        updatePoints()
        updateLocations()
        updateColors()
    }
}

```
Creating a PHP-Slim server using OpenAPI
Tags: linux, php, slim, openapi
Published: 2019-09-02 03:35:18

---
title: Creating a PHP-Slim server using OpenAPI
published: true
description: We use the OpenAPI generator to create a stub server implementation of PHP-Slim. Then we implement the different endpoints using an SQLite backend and talk about the challenges using the database and handle CORS.
tags: Linux, PHP, Slim, OpenAPI
cover_image: https://thepracticaldev.s3.amazonaws.com/i/ae1ipg1hlcaejp0k7vk7.jpg
---

{% youtube 5cJtbIrsYkg %}

We use the OpenAPI generator to create a stub server implementation of PHP-Slim. Then we implement the different endpoints using an SQLite backend and talk about the challenges using the database and handle CORS.
Case Insensitive in D
Tags: dlang, tutorial, string
Published: 2019-09-02 03:16:02

Let me begin with the naive approach before I tell you to go with the naive approach.

```dlang
import std.string;

assert("I be Big".toLower == "i be big");
```

As I mentioned last time unicode isn't simple. Well it isn't easier with changing characters and this mostly isn't a unicode problem. The upper/lowercase of a character in one language changes in another. This is where localization comes into play. 

I'm actually not very well verse in this area so question my advice. If you're not working in data that crosses language boundaries then this change is mostly moot. 

I haven't seen a solution in D for handling this. I only briefly looked into it for this article. So continue using toLower as was recommended to me for Python.
LeetCode "4Sum"
Tags: leetcode, python
Published: 2019-09-02 03:11:56

---
title: LeetCode "4Sum"
published: true
description: 
tags: [leetcode, python]
---

[3Sum Closest](https://leetcode.com/problems/3sum-closest/) was helpful.
This code is slow😕

[4Sum](https://leetcode.com/problems/4sum/)

```python
class Solution:
    def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
        
        nums.sort()
        len_nums = len(nums)
        result = set()
        
        for i in range(len_nums - 3):
            for j in range(i + 1, len_nums - 2):
                
                left = j + 1
                right = len_nums - 1                
                while left < right:
                                        
                    sum_nums = nums[i] + nums[j] + nums[left] + nums[right]
                    if sum_nums == target:
                        result.add((nums[i], nums[j], nums[left], nums[right]))
                        left += 1
                    else:
                        if sum_nums < target:
                            left += 1
                        else:
                            right -= 1
        
        return result
```
Iframes – aren’t they bad?
Tags: javascript, html, css, xss
Published: 2019-09-02 02:20:57

When everyone starts web development for the first time, they hear iframes are terrible! Don’t use them, they’re slow and weird there’s nothing they could ever be good for!

There’s a good reason that we’re taught this. Embedding an iframe in your webpage is similar to having two different browser tabs open. The iframe has it’s own DOM and loading events that aren’t shared with the parent window, this can lead to clunky behaviours when interacting with the iframe. Scrolling on mobile is often the major concern.

#### An example of an iframe in a HTML page:
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/rm87pmqff7ayabqhftyp.png)

#### If iframes are so bad, why would I use one?
The simple answer is, when you need to run untrusted third party code in your webpage.

We most often see this today in the form of display ads. There is probably one somewhere on your webpages right now. Another use would be websites like Codepen and The Big Crunch where you can write and save HTML/CSS/Javascript code that other users on these websites can see.

Iframes can use Javascript to access elements between the two DOMs if they are hosted in the same domain, this is very dangerous if the iframe is untrusted. Which has the potential risks of malicious activity such as redirecting the user to a malicious website or stealing someone’s authentication. At The Big Crunch we run our website on earlyaccess.bigcrunch.io and serve our iframes from rur.bigcrunch.io. This separation means that users can’t write code that can escape the iframe. 

More to come on iframe sandboxing, communication between iframes, scrolling and interactions.
Why I think React Hooks are Slick
Tags: react
Published: 2019-09-02 01:59:28

---
title: Why I think React Hooks are Slick
published: true
cover_image: https://thepracticaldev.s3.amazonaws.com/i/0fjcf9mu0vbd3l7n8by6.jpg
tags: react
---

_[Cover image by John Wright, on Flickr. ](https://www.flickr.com/photos/134439929@N08/)_

Some time ago React got a new major feature called **hooks**. They are a way to add state to component functions. Things that required lifecycle methods and in turn, component classes now can be achieved with a component function that calls hook functions.

This fact on its own is already a huge boon. We write our first UI draft with component functions and then don't have to restructure anything, drop in our hooks, and be done with it.

It also eliminates deep component trees. Things that had to be done with **higher-order components** and **render props**, which were design patterns constructed with component classes and their lifecycle methods. Auth, UI state, services, internationalization, etc. everything was a component nested in a component.

Hooks add another dimension for nesting. This new dimension allows decoupling the nesting of the **visible** UI components from the nesting of the **invisible** behavior of our applications.

But I think these points aren't the main selling point of hooks.

What makes them powerful is that they offer a different way to think about the component lifecycle.

Before hooks, we would think in terms of lifecycle events.

Do I need my component to do something when its rendered for the first time? Let's put the code in `componentDidMount`!

Will the component be removed? Put it into `componentWillUnmount`!

For updates? Put it in `componentWillUpdate` or `componentWillReceiveProps` or `getDerivedStatesFromProps`... or ... well now it gets a bit complicated...

Hooks remove this problem once and for all.

With hooks, the focus is moved from the different lifecycle events we want to **hook into** to the actual state we want to **observe**.

We create the state we need to observe with `useState` and use it with `useEffect` to trigger code when it changes.

The only things we care for are the state changes and if our component gets removed from the DOM.

When we used lifecycle methods, it wasn't enough to know what we want to **observe**, we also needed to know **where at the lifecycle** it could occur. This extra step could lead to UI bugs.

For example, React would re-use a component that was already rendered, change the props and `componentDidMount` wouldn't be called again. The `useEffect` hook would recognize the changed props and rerun its code.

This sounds like a pretty dull change in thinking about component behavior, but I think it's a brilliant one that eases the creation of component-based UIs tremendously.
Tindev
Tags: javascript, react, reactnative
Published: 2019-09-02 01:54:18

My fisrt application with Node Js, React and React Native.

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

- What is this about?

- Tindev is to find other devs that you like to start a new project and code together!

https://github.com/marioalvesx/Tindev
Fastest way to optimize your images for the web
Tags: html, performance, webdev, productivity
Published: 2019-09-02 01:34:43

---
title: Fastest way to optimize your images for the web
published: true
description: Ever wonder what's the fastest way to optimize your images on the web?
tags: html, performance, webdev, productivity
---

Ever wonder what's the fastest way to optimize your images on the web?

What if you don't have to manually create optimized images for every screen size and screen density? What if you can optimize images on the fly? What if you can provide advanced image formats like WEBP? What if you can just pass a single URL and get a list of optimized image urls back?

If you are using Filestack, then check out [filestack-adaptive](https://github.com/filestack/adaptive). It allows you to pass in an unoptimized image URL like this:

```
https://cdn.filestackcontent.com/5aYkEQJSQCmYShsoCnZN
```

And get a list of optimized image URLs that you can use in a picture element:

```
https://cdn.filestackcontent.com/resize=width:180/5aYkEQJSQCmYShsoCnZN 180w, 
https://cdn.filestackcontent.com/resize=width:360/5aYkEQJSQCmYShsoCnZN 360w, 
https://cdn.filestackcontent.com/resize=width:540/5aYkEQJSQCmYShsoCnZN 540w, 
https://cdn.filestackcontent.com/resize=width:720/5aYkEQJSQCmYShsoCnZN 720w, 
https://cdn.filestackcontent.com/resize=width:900/5aYkEQJSQCmYShsoCnZN 900w, 
https://cdn.filestackcontent.com/resize=width:1080/5aYkEQJSQCmYShsoCnZN 1080w, 
https://cdn.filestackcontent.com/resize=width:1296/5aYkEQJSQCmYShsoCnZN 1296w, 
https://cdn.filestackcontent.com/resize=width:1512/5aYkEQJSQCmYShsoCnZN 1512w, 
https://cdn.filestackcontent.com/resize=width:1728/5aYkEQJSQCmYShsoCnZN 1728w, 
https://cdn.filestackcontent.com/resize=width:1944/5aYkEQJSQCmYShsoCnZN 1944w, 
https://cdn.filestackcontent.com/resize=width:2160/5aYkEQJSQCmYShsoCnZN 2160w, 
https://cdn.filestackcontent.com/resize=width:2376/5aYkEQJSQCmYShsoCnZN 2376w, 
https://cdn.filestackcontent.com/resize=width:2592/5aYkEQJSQCmYShsoCnZN 2592w,
https://cdn.filestackcontent.com/resize=width:2808/5aYkEQJSQCmYShsoCnZN 2808w, 
https://cdn.filestackcontent.com/resize=width:3024/5aYkEQJSQCmYShsoCnZN 3024w" 
```

So the next time you find yourself manually optimizing images for the web, check out filestack-adaptive.
Windows XP is back!!!
Tags: windows, windowsxp, concept
Published: 2019-09-02 01:18:01

---
title: Windows XP is back!!!
published: true
description: A new XP 2019 concept looks amazing 
tags: Windows, Windows XP, concept
---

I have to make my apologies because this article's title is not completely true. 

This is just a concept created by Kamer Kaan Avdan who using new UI concepts with all the features that we love about XP shows a possible version of this operative system. 


![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/drmb9hrd5n84g2952ygm.jpg)


Check the video out!


{% youtube i_T80ZVD7e8 %}
Perform an action every time Django starts
Tags: python, django
Published: 2019-09-02 00:14:26

---
title: Perform an action every time Django starts
published: true
description: 
tags: python, django
---

Recently, I was building [`django-single-instance-model`](https://matix.io/django-single-instance-model/). The package ensures that at all times there is exactly one instance of a model. 

One of the tasks for building this package was ensuring that an instance of the model existed.

I wanted to run this code as early as possible, once the database connection had been made. 

**How did I do it?**

In the `__init__.py` of the main app, I hooked into the `connection_created` signal. Here's how:

```python
from django.dispatch import receiver
from django.db.backends.signals import connection_created


@receiver(connection_created)
def my_receiver(connection, **kwargs):
	with connection.cursor() as cursor:
            pass # your startup code here
```

---

Hope this helps you in the future!  Follow me for more Django / Python tips!
Why graphql and how it helps you
Tags: webdev, graphql, showdev, rest
Published: 2019-10-04 04:52:35

---
title: Why graphql and how it helps you
published: true
tags: ['webdev', 'graphql', 'showdev', 'REST']
series: Awesome talks curated by Param
canonical_url: https://learnwithparam.com/tech-talks/why-graphql-and-how-it-helps-you/
description: Brooks talk about Optimizing your API using GraphQL and make your API closer to how it is consumed by the consumers.
---

One of the best talk on, why and how graphql works. It was bit old, but the content is relevant and gold. You will enjoy and understand GraphQL and how it shines.

Brooks talk about Optimizing your API using GraphQL and make your API closer to how it is consumed by the consumers.

{% youtube broQmxQAMjM %}