teleren/devto huggingface dataset:
AutoInvoke (Runtime method resolving and invoking)
Tags: csharp, showdev
Published: 2019-12-29 09:25:33

During my years of programming I often run into the issue of dynamically (during runtime) deciding which function to call.

This may happen while developing a CLI tool where you need to call a different method based on some command line parameter or when building a command processing/routing module for some backend system.

Typically I would just solve this issue per case, but I decided to build a library for that.

I present to you **AutoInvoke** it is a static class and its usage is as simple as:

```csharp
    var list = new List<int>();
    AutoInvoke.Invoke(list, "add", 10);
```

or for resolving overloaded methods

```csharp
public class PayloadHandler
{
    public int AHandledCount { get; set; } = 0;
    public int BHandledCount { get; set; } = 0;
    public void Handle(APayload payload) { AHandledCount++; }
    public void Handle(BPayload payload) { BHandledCount++; }
}

public void Invoke_WithSpecificType()
{
    var _handler = new PayloadHandler();
    
    AutoInvoke.Invoke(_handler, "Handle", new APayload());
    Assert.Equal(1, _handler.AHandledCount);

    AutoInvoke.Invoke(_handler, "Handle", new BPayload());
    AutoInvoke.Invoke(_handler, "Handle", new BPayload());
    Assert.Equal(1, _handler.AHandledCount);
    Assert.Equal(2, _handler.BHandledCount);
}
```


It is in alpha stage but the basic functionality is there.

The main open issues are
- Cannot handle extension methods
- Cannot await async methods (will return Task<T>)

[nuget](https://www.nuget.org/packages/Greekdev.AutoInvoke/)
[repository](https://gitlab.com/greekdev/greekdev.autoinvoke)
Practice with AWS Access analyzer
Tags: security, aws
Published: 2019-12-29 10:25:23

### Hey there!
   Have you ever asked yourself who has access to my AWS resources? or who outside of my account has access? Honestly, the second one most important, because nobody wants to be a subject of news about a new data breach :). AWS made a tool for us to figure it out. It is called __*IAM Access analyzer*__. You can find it in the IAM Service. 
### Short overview 
   In a few words, what it does, it evaluates your resource policies and finds all external principal that __has access to resources in your account__. It takes your account as the __*zone of trust*__ and informs you about everything outside of the zone, but has access to the zone.
Other important things worth to mention:
* Access analyzer is region-specific, so __you have to enable it__ for each region, where you want to use it. 
* Access analyzer currently supports __a limited list of resource [types](https://docs.aws.amazon.com/IAM/latest/UserGuide/access-analyzer-resources.html)__
  
Ok, enough for theory, time to practice.
### Practice 
   You can find the Access analyzer in IAM. For creating a new Analyzer just press create and provide a name or use default one.
____
![Creating](https://github.com/NuclearBreath/SecurityBlog.Cloud/raw/master/Practice_with_AWS_Access_Analyzer/img/AccessAnalyzer0.gif)
____
   Once the scan is done, you may see all the findings. Yes, it is such simple. At first, __you have to go through all findings__ and either archive or resolve them. Archiving means that __access is intended__, once you archive a finding it will not appear till resource policy will be changed again. The resolve status appears only after you fix __unintended access__ and it obviously means that found access does not exist anymore.
   After you are done, you probably would like to receive notification about new findings.  You can do it via `CloudWatch Events`. Just create a new rule and define necessary action for new findings. I've used SNS topic to send an email once new findings appear. 
____
![Notification](https://github.com/NuclearBreath/SecurityBlog.Cloud/raw/master/Practice_with_AWS_Access_Analyzer/img/AccessAnalyzer1.gif)
____
   If you want to white-list some resources or external principal you can use archive rules for it. Go to `Archive rules` click add and define a condition.
____
![Archive rules] (https://github.com/NuclearBreath/SecurityBlog.Cloud/raw/master/Practice_with_AWS_Access_Analyzer/img/AccessAnalyzer2.gif)
____
   Access analyzer is fast to implement and simple to use tool that you definitely need to check out. 
### Links
[Official Documentation](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html)
Proxy in Typescript
Tags: typescript, proxy
Published: 2019-12-29 10:25:12

Proxy is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object.

The proxy pattern is useful when the real subject does something expensive.
In web applications, one of the most expensive operations you can do is a network request, so it makes sense to combine HTTP requests as much as possible.

Real Example as:

You have a list of videos on the page. When the user clicks a video title, the area below the title expands to show more information about the video and also enables the video to be played. 

The detailed video information and the URL of the video are not part of the page; they need to be retrieved by making a web service call.

The web service can accept multiple video IDs, so we can speed up the application by making fewer HTTP requests whenever possible and retrieving data for several videos at one time.

The videos object doesn't call the HTTP service directly but calls the proxy instead. 

The proxy then waits before forwarding the request. If other calls from videos come in the 50ms waiting period, they will be merged into one. 

A delay of 50ms is pretty much imperceptible for the user but can help combine requests and speed up the experience when clicking “toggle” and expanding more than one video at once. 

It also reduces the server load significantly since the web server has to handle a smaller number of requests.


Request process without proxy
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/5twkmec5btbuxt09lfjt.jpg)


Request process with proxy
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/p5vasvcv59xaecjzu5as.jpg)
Cloud Run vs App Engine
Tags: devops, googlecloud, webdev
Published: 2019-12-29 09:56:49

#### Should you use Google’s Cloud Run or Google’s App Engine for your next project?

![clouds](https://miro.medium.com/max/3894/1*JmOLbF0JtZ-BucPeiGonSw.jpeg)

# What is Cloud Run?

In a nutshell, you give Google’s Cloud Run a Docker container containing a webserver. Google will run this container and create an HTTP endpoint.

To deploy to the Google Cloud you should build a Docker container image on your local machine. Then, you should upload this container to Google Cloud.

```
gcloud auth configure-docker
docker push grc.io/PROJECT-ID/IMAGE
```

And finally, you can deploy the pushed container with the following command.

```
gcloud run deploy --image gcr.io/PROJECT-ID/IMAGE

```

All the scaling is automatically done for you by Google. If there is a lot of traffic it will add more containers containing the webserver.

Sounds great, but there’s a catch.

Cloud Run depends on the fact that your application should be stateless. If you want to host a traditional web application this means that you should divide it up into a stateless API and a frontend app.


# What is App Engine?

With Google’s App Engine you tell Google how your app should be run. The App Engine will create and run a container from these instructions.

For example, to host a Node project on Google’s App Engine, I can simply create the following `app.yml` file.

```
runtime: nodejs12
entrypoint: node build/server.js

```

To deploy it to the App Engine I can run the following command.

```
gcloud app deploy
```

The App Engine will build a Docker Image with the `nodejs12` environment and run the entrypoint command.

All the scaling is automatically done for you. And as a bonus, you can even store state information on the server.


This means that if you want to host an existing web application to the Google Cloud, the App Engine is probably your best bet.

# Which service should you use?

If you have an application that is not stateless then you should go for the App Engine.

Also, deploying with App Engine is super easy. You simply fill out an `app.yml` file and Google handles everything for you.

However, with Cloud Run, you have more control. You can go crazy and build a ridiculous custom Docker image, no problem!

In my opinion Cloud Run is made for devops engineers, App Engine is made for developers.
Two Sum solved in javascript
Tags: javascript, leetcode, tutorial, algorithms
Published: 2019-12-29 08:05:14


# Two Sum : Javascript

#### Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

#### Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

### Code:

```javascript
 var twoSum = function(nums, target) {
    //hash table
    var hash = {};

    for(let i=0; i<=nums.length; i++){
      //current number
        var currentNumber = nums[i];
        //difference in the target and current number
        var requiredNumber = target - currentNumber;
        // find the difference number from hashTable
        const index2 = hash[requiredNumber];
        
        // if number found, return index 
        // it will return undefined if not found
        if(index2 != undefined) {
            return [index2, i]
        } else {
           // if not number found, we add the number into the hashTable
            hash[currentNumber] = i;
            
        }
    }
};

```
### In detail:

- Declare a empty hash table
- Loop through the array
- Store the current number in a variable 
- Find the difference between the the target number and the current number
- Search for the difference number from the hash table
- If number found, return the index of the first number and the search number
- If not found, add the number into the hash table and continues for loop checking.

### Conclusion: 

Hashmap is the optimal solution as the average search time complexity is O(1)  

| Runtime     | Memory      | 
| ----------- | ----------- |
| 84 ms       | 35.5 MB     |
How does the DEV feed algorithm work?
Published: 2019-12-29 07:02:40

I cannot understand how the dev algorithm ranks the posts. 
I created an article yesterday, but even when I look for it under the tags I specified I cannot find the post.

Here is the [post]( https://dev.to/karansinghgit/react-for-absolute-noobs-a-7-day-guide-4hn0)
If I look under #react or #javascript, I cannot find it.

I also haven't even come across my post once on my main feed, while articles which are just 20-30mins old have started to appear.

What's the secret?
Udemy: Automated Software Testing with Python
Tags: review, education, testing, python
Published: 2019-12-29 06:57:07

It appears to be an excellent overview of modern software testing techniques. Besides that, it contains a sufficient introduction to Python and Flask.

# For beginners:
It teaches the basics of software testing. Unit, integration and end-to-end tests are covered. The author guides students through a whole creation of a simple server application. Moreover, It introduces the audience to many good practices.

# For experienced:
It might be a good enough starting point to Python and Flask for a developer with some understanding of OOP and prior experience in backend development.

[Course is available here](https://www.udemy.com/course/automated-software-testing-with-python/)
Services in Angular
Published: 2019-12-29 06:43:49

A ‘Service’ in Angular is a class intended to perform a specific task. Generally, we create services in Angular based on our objective. Each and every objective will have its own service.

Let’s take an example of a simple mathematical operation: Sum of two values should be logged in the output.

In order to perform this, we need to write the logic to do the arithmetic operation and based on the logic, we can see the result in the output.

But,

The location where are we writing this logic i.e. in which file makes a considerable difference as explained below.

In general, we write the code inside the ‘component’ and it works fine. But, the actual purpose of a component is to aid in providing the methods and properties to data binding in the process of mediating between the ‘application logic’ and ‘view’.

So, to make the component’s job easy, we divide the tasks and create separate ‘services’ in Angular for individual tasks. In addition to this, we can even use these services in multiple components when required, by which we can eliminate the code duplication.

How do we use services in Angular?
To share the data across multiple components.
To implement application logic.
For external interactions like connecting to a database.
Now, How to use a service inside a component?

As we are creating multiple services in Angular based on our objectives, we should integrate such services with the component. That means we make the service available for the component to interact with it.

To see the example of service creation and it's integration check my article [Services in Angular] (https://www.madhantutorials.com/services-in-angular/)
F# Tip 1: Don't use classes
Tags: fsharp, dotnet, design, functional
Published: 2019-12-29 06:37:45

If you're coming to F# from an object-oriented language like C#, you might be tempted to continue encapsulating data and methods in classes. It's true that F# supports classes just fine, but you're really better off not using them unless you really need to (e.g. for interop with C#).

For one thing, it's tempting to make classes mutable, which is a sure path back to the dark side. But on top of that, classes come with a lot of complexity that is usually not needed: constructors, interfaces, properties, fields, methods, virtual, static, protected, private, internal... Ugh. Free up all that mental space so you can instead use it to learn cool stuff like [workflows](https://fsharpforfunandprofit.com/posts/computation-expressions-intro/) and [type providers](https://medium.com/@maximcus/magic-of-f-type-providers-225b1169c7a0).

Don't worry, you can continue to encapsulate your data and functions in a single file, like this:

```fsharp
// Car.fs
namespace Tip

type Color = Red | White | Black

type Car =
    {
        Mileage : int
        Color : Color
    }

module Car =

    let create color =
        { Mileage = 0; Color = color }

    let drive miles car =
        { car with Mileage = car.Mileage + miles }

    let paint color car =
        { car with Color = color }
```

First we define an immutable record type called `Car`. Then we define a module that contains `Car`-based functions. You can `create` a new car in any color, `drive` it down the road for a few miles, and even change its `paint` job. If you compare this code to the corresponding C# or F# class, I think you'll agree that it's simpler and just as effective.
🎨 Colors Palette Released!
Tags: html, css, javascript, jquery
Published: 2019-12-29 06:27:33

---
title: 🎨 Colors Palette Released!
published: true
description: Project to store colors I frequently use
tags: html, css, javascript, jquery
cover_image: https://thepracticaldev.s3.amazonaws.com/i/6ms2qu86g87h4q2hj0rz.png
---
# About
I released this project as a way to store hex color codes I use frequently. Feel free to use is for your own reference whenever you need the hex values of common color palettes like Bootstrap's or Material Design's palettes. 😀

# Links
- [Colors Palette](https://davinaleong.github.io/proj-color-palette/) 🎨
- [GitHub](https://github.com/davinaleong/proj-color-palette)
A big trap in data science education is:
Tags: datascience, algorithms, deeplearning
Published: 2019-12-29 05:48:09

● learning DS  libraries b4 learning coding basics
● learning ML algorithms b4 learning how to preprocess your data
● learning DL  b4 machine learning
● learning data viz B4 understanding the basics of statistical inference

https://twitter.com/VictorOmondi197/status/1211159816535728128?s=19
I'm a professional React developer, and here's how I create React-powered Microservices using GraphQL and Node.js. #8
Tags: react, node, webdev, javascript
Published: 2019-12-29 04:55:27

**Update:** [Part 9 is out!](https://dev.to/bettercodingacademy/i-m-a-professional-react-developer-and-here-s-how-i-create-graphql-microservices-using-react-node-js-docker-and-mysql-9-59c)

**About Me:** I've been a professional web developer for just over 10 years now. I'm currently the lead web development instructor at [Better Coding Academy](https://codebetter.com.au), and as part of what I do, I post videos on our YouTube channel at [https://www.youtube.com/c/BetterCodingAcademy](https://www.youtube.com/c/BetterCodingAcademy).

_(Subscribe for awesome web development content!)_

This is part 8 in a full tutorial on how to set up a GraphQL Microservices-powered React app. ([Here's part 7!](https://dev.to/bettercodingacademy/full-tutorial-microservices-using-graphql-react-node-js-sequelize-and-mysql-7-1ocd))

In this video, I fully implemented authentication in the frontend React app, hooking it up to the microservice architecture via the API Gateway.

I hope you enjoy!

{% youtube 9i6c_S2MuiY %}

Happy coding!

Full source code: [https://github.com/parkroolucas/microservices-demo](https://github.com/parkroolucas/microservices-demo)
Read-once variable - R1V, ROV, ... - in C#
Tags: help, csharp
Published: 2019-12-29 03:37:07

So I want a variable that I can assign a value to then, later on, read it but have the read be destructive, that is, once I've retrieved the value I want to be unable to read it again.

I wrote something to do that some years ago and I'm still using it but I'm not exactly happy with it and am trying to think of a better, more generic, implementation.
```csharp
    public class R1V
    {
        private int _count;
        private readonly string _value;

        public R1V(string value)
        {
            _count = 1;
            _value = value;
        }

        public string Get()
        {
            switch (_count)
            {
                case 1:
                    _count = 0;
                    return _value;
                default:
                    return null;
            }
        }
    }
```
is what it is at the moment. It currently works only with strings. I want it to work with anything. Currently it doesn't forget the value it has stored, it just stops you getting access to it. That should change too. 

In another object I have
```csharp
LastMessage = new R1V(fullMsg);
```
and then elsewhere I can execute `LastMessage.Get()` and know, if it's null, that there's nothing new from the object that exposes LastMessage.

Any ideas?
Material Colors Palette
Tags: materialcolors
Published: 2019-12-29 03:10:35

---
title: Material Colors Palette
published: true
description: Material Colors Palette
tags: material-colors
cover_image: https://thepracticaldev.s3.amazonaws.com/i/j68il0mliaeq1bf52csj.png
---
# About
Just sharing a resource I use on a regular basis. Here is a list of all colors from the Material's Design palette. Click on the color **tabs** to reveal the hex values of the tints.

# Links
- [Material Colors Palette](https://www.materialpalette.com/colors)
Pokemon-Teams App Template Released!
Tags: css, sass, cssgrid, flexbox
Published: 2019-12-29 02:58:46

---
title: Pokemon-Teams App Template Released!
published: true
description: Template of Pokemon Teams App
tags: css, sass, css-grid, flexbox
cover_image: https://thepracticaldev.s3.amazonaws.com/i/02qw8dgamnekjrxni9kn.png
---
# About
This template is the first part of a *3-part project*. The second part is to build a React App, and part-3 is a CMS to update the Pokemon teams. I've always enjoyed playing the main Pokemon games like Pokemon Sun & Moon and Pokemon Sword & Shield. I've been playing them since Pokemon Red & Blue. I can get quite fanatical about battle strategies. Currently I store my own teams on Google Docs. Now finally confident enough in my development skills, I've decided to build an app to house all these teams I made.

# Tech Stack
This is a pure `CSS` template built in `SASS`, using the [Materials Colors](https://www.materialpalette.com/colors) palette. I also took advantage of the opportunity to also explore **CSS Grid**. For example, CSS Grid is used to layout the sidebar and main content. **Flexbox** is used to layout the team-cards.

# Links
- [Demo](https://davinaleong.github.io/proj-pokemon-teams-template/)
- [Repo](https://github.com/davinaleong/proj-pokemon-teams-template)
- [Materials Colors Palette](https://www.materialpalette.com/colors)
Striving for my AWS Solutions Architect Certification 
Tags: aws, beginners, codenewbie
Published: 2019-12-29 01:52:00

I have many questions for fellow solutions architects! 

What motivated you to become AWS certified?

What were you doing prior to what you are doing now?

Is the money good in being an AWS SA?

How hard was it landing that first job? 

I am struggling being motivated to finish up but hearing your responses will greatly push me to go through and take the exam myself.
Parcelize in Android using kotlin-android-extensions
Tags: android, kotlin, parcelize
Published: 2019-12-29 01:04:34

With `kotlin-android-extensions` we can implement `Parcelable` in much simpler way using `@Parcelize` and `Parcelable`.

#### Enable android extensions in `app` gradle file
Android extensions are not considered production-ready yet, so we need to turn `experimental` mode on in app's `build.gradle` file
```groovy
androidExtensions {
  experimental = true
}
```
#### Parcelize simple `class` or `data class`
For this we need to annotate the class with `@Parcelize` and implement `Parcelable`. `@Parcelize` annotation requires all serializable properties be declared in the `primary constructor`.
e.g.
```kotlin
@Parcelize
class Book(val author: String, val price: Int): Parcelable

@Parcelize
data class User(val name: String, val age: Int): Parcelable
```
More advanced serialization logic can be written inside a companion object:
```kotlin
@Parcelize
data class Book(val author: String, val price: Int) : Parcelable {
  private companion object: Parceler<Book> {
    override fun Book.write(parcel: Parcel, flags: Int) {
      // add custom write here
    }
    override fun create(parcel: Parcel): Book {
      // add custom read here
    }
  }
}
```
#### Parcelize enums
`Enum` can also be parcelized starting `kotlin-version:1.2.60`. This is similar to parcelizing the data classes.
```kotlin
@Parcelize
enum class BookType: Parcelable { HISTORY, DRAMA, FICTION, BIO }
```
#### Parcelize sealed classes
`sealed` and `abstract` classes can also be parcelized. For this, the `parent` class needs to implement `Parcelable` and all the `child` classes need to be annotated with `@Parcelize`. e.g.
```kotlin
sealed class Result : Parcelable {

  @Parcelize
  object Failure : Result
  
  @Parcelize
  object Error : Result

  @Parcelize
  class Success : Result
}
```
Please leave feedback in the comments.
Use `file` to get file types - Linux Tips
Tags: shell, linux
Published: 2019-12-29 00:43:42

You might heard "Everything is a file" in Linux. Using the `file` shell command, you can get a file's type:

First let's create some files:

```bash
# create plain text file
$ echo "" > abc.txt

# create a folder
$ mkdir Music

# create a symbolic link
$ ln -s /media/pi/WDHD ./Cloud

# create a FIFO
$ mkfifo /tmp/myfifo

# list tty devices under /dev
$ ls /dev/tty*
/dev/tty
/dev/tty0
...
/dev/tty13
...
```

Now we use `file` command to get those file types:

```bash
$ file abc.txt
abc.txt: ASCII text

$ file Music
Music: directory

$ file Cloud
Cloud: symbolic link to /media/pi/WDHD

$ file /tmp/myfifo
/tmp/myfifo: fifo (named pipe)

$ file /dev/tty13
/dev/tty13: character special
```