teleren/devto huggingface dataset:
Polymorphic Model Resource Finder in Ruby On Rails
Tags: rails, polymorphic
Published: 2020-08-24 20:30:20

---
title: Polymorphic Model Resource Finder in Ruby On Rails
published: true
description: design pattern to find a polymorphic resource in the controller  
tags: rails, polymorphic
canonical_url: https://majesticlabs.dev/polymorphic-model-resource-finder-in-ruby-on-rails/
//cover_image: https://direct_url_to_image.jpg
---

When having a polymorphic association in Rails model, you want to:

1. generate URL
2. find the parent model in the controller

See below our model structure. Let's answer those questions the Rails way.

```ruby
class Company < ActiveRecord::Base
  has_many :images
end

class Product < ActiveRecord::Base
  has_many :images
end

class Image < ActiveRecord::Base
  belongs_to :imageable, polymorphic: true
end
```

## Generating Image URL

RoR provides a simple way to generate polymorphic URLs: [polymorphic_path](https://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html)

So `polymorphic_path([parent, Image])` will generate:

```ruby
company_images_path(parent) # /companies/1/images

# or

product_images_path(parent) # /products/1/images
```

## Finding the parent model in the controller

If in Image controller, we need to have parent information in order to scope relevant data, we will use `ResourceFinder` helper.

```ruby
class ImagesController < ApplicationController
  include ResourceFinder

  def index
    @resources = parentable.images
    render json: @resources
  end
end
```

and we will create a `app/controllers/concerns/resource_finder.rb` helper

```ruby
module ResourceFinder
  def parentable
    klass, param = parentable_class
    return unless klass

    klass.find(params[param.to_sym])
  end

  private

  def parentable_class
    params.each_key do |name|
      if name.match?(/(.+)_id$/)
        model = name[/([^\/.]*)_id$/, 1]
        return model.classify.safe_constantize, name
      end
      nil
    end
  end
end
```

The `parentable_class` read the param and define the class associated with the param. In our case, if we have `/products/:product_id/images` this method will read the `product_id` params key and will try to create a class from this model. If successful, it will return the key and the class to be used in our scope.

Happy hacking!
Install Data Plane Development Kit (DPDK) and Build NDN-DPDK
Tags: actionshackathon
Published: 2020-08-24 20:15:31

### My Workflow

[Data Plane Development Kit (DPDK)](https://www.dpdk.org/) is a set of libraries to accelerate packet processing workloads, often used on 10Gbps and faster networks. [Storage Performance Development Kit (SPDK)](https://spdk.io/) is another set of libraries for writing high performance storage applications, and is often used together with DPDK.

In past few years I've been developing NDN-DPDK, a high speed packet forwarder for [Named Data Networking (NDN)](https://named-data.net), a future Internet architecture.

As a *stallion coder*, I understand the importance of **continuous integration**. Since the public release of NDN-DPDK in 2019, I was using Travis CI, but I'm facing a limitation: I want to compile the project both in Ubuntu directly and as a Docker container, but Travis CI job syntax does not have good support for that.

In this hackathon, I learned that GitHub Actions supports **multiple jobs with different steps**. This allows me to build a workflow with two separate jobs.
The first job builds and tests the project in Ubuntu:

1. Install DPDK and SPDK, using the `setup-dpdk` Action I created.
2. Install other dependencies of NDN-DPDK.
3. Compile NDN-DPDK.
4. Run unit tests.

The second job builds the Docker container, using the `docker/build-push-action@v1` Action.

### Submission Category: 

DIY Deployments

### Yaml File or Link to Code

* `setup-dpdk` action: https://github.com/yoursunny/setup-dpdk
* NDN-DPDK repository: https://github.com/usnistgov/ndn-dpdk

Considering that installing DPDK and SPDK is a reusable building block, I decide to create **a custom Action to install DPDK and SPDK**. I choose to use "composite run steps" type because it is the simplest.
DPDK is a fairly large project and takes about 10 minutes to compile, and it would be nice to have caching. However, "composite run steps" Action type does not support importing other existing Actions with `uses:` keyword. Thus, users of my Action have to configure caching in the top-level workflow.

During my attempt, I made many mistakes and learned from them:

* `$GITHUB_WORKSPACE` is not a suitable place for downloading and compiling dependencies such as DPDK, because `actions/checkout@v2` step would use this directory to checkout the codebase. Instead, I should download and compile DPDK in a directory under `$HOME`.
* DPDK uses `-march=native` compiler flag for maximum performance, but this flag also makes the compiled library only work on a particular CPU. Although GitHub-hosted runners use the same Azure machine type, there are minor differences in the CPU model. Therefore, if I use `actions/cache` on compiled DPDK and SPDK libraries, it's necessary to include CPU flags (obtained from `lscpu -J` command) as part of the cache key, to prevent libraries compiled for one CPU from being used on a different CPU.

### Additional Resources / Info
Day 6 of 100DaysOfCode
Tags: 100daysofcode, javascript, wordpress, eloquentjs
Published: 2020-08-24 19:56:43

Hey! 

Today was a busy day with school and renovation. Only had time for 30 min JavaScript session reading the chapter 5 of Eloquent JavaScript book. 

As I said yesterday: Keep coding, you can do it!

## What I did today:

### 1. Reading Chapter 5 of Eloquent JavaScript book
https://eloquentjavascript.net/05_higher_order.html
####What I learned from it:
* Introduction to abstraction
* What are higher-order functions

#### Total time: 31min
Tracked by using my [TaskTimer](https://www.arttupyykonen.com/tasktimer/) script and the [WakaTime app](https://wakatime.com/about)

####Psst

As I promised on Day 4 you can [check my solutions](https://www.arttupyykonen.com/ejs-solutions/) to EJS exercises on my website. 

You need to answer a question regarding the exercise to see my solution. This is meant to encourage you to try the problems yourself. I'll add more solutions as I go through the book. 

Adding the quizzes to my site took some time so feedback on them is much appreciated!

That's it. See you all tomorrow!
Reverse Array 
Tags: beginners, javascript, webdev, productivity
Published: 2020-08-24 19:44:14

---
title: Reverse Array 
published: true
description: Eloquent JavaScript coding problem solution
tags: #beginners #javascript #webdev #productivity
//cover_image: https://direct_url_to_image.jpg
---
### Problem:
Write two functions reverseArray and reverseArrayInPlace. The first, reverseArray, takes an array as an argument and produces a new array that has the same elements in the inverse order. The second, reverseArrayInPlace, does what the reverse method does: it modifies the array given as argument in order to reverse its elements. Neither may use the standard reverse method.

### Method 1: ReverseArray 

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

### Method 2: ReverseArrayInPlace

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/0gtnk74667zcszgk3mje.png)

### Which one is better? ReverseArrayInPlace : ReverseArray

**ReverseArrayInPlace** takes half the time and will replace two values at a time instead of looping the whole array and replacing the values one at a time.
Apple One Tap Account Upgrades from WWDC 2020
Published: 2020-08-24 19:35:31

Learn about Apple's new One Tap Account Upgrades presented at WWDC 2020. [Read more...](https://auth0.com/blog/wwdc-one-tap-account-upgrades/?utm_source=reddit&utm_medium=sc&utm_campaign=wwdc_one_tap)
Python Zero to Hero - Ep.20 - Python functional programming
Tags: python, tutorial, beginners, funcitonalprogramming
Published: 2020-08-24 19:30:55

---
title: Python Zero to Hero - Ep.20 - Python functional programming
published: true
description: Today we will explore what is functional programming. Also, we will introduce `map`, `filter` and `reduce` in Python which you can do functional programming.
tags: python, tutorial, beginner, funcitonalprogramming
---
Today we will explore what is functional programming. Also, we will introduce `map`, `filter` and `reduce` in Python which you can do functional programming. If you have any questions or any suggestions about which Python topics to cover, please leave your comment at my [Twitch channel](https://www.twitch.tv/cheukting_ho)

You can get the slide deck [here](https://slides.com/cheukting_ho) and the example code and homework form [GitHub here](https://github.com/Cheukting/python02hero). Ask questions at my [Twitch channel](https://www.twitch.tv/cheukting_ho)
Concept Visualisation for N-Queen Problem
Published: 2023-07-16 08:16:16

---
title: Concept Visualisation for N-Queen Problem
published: true
date: 2020-08-24 19:25:17 UTC
tags: 
canonical_url: https://theuigirl.hashnode.dev/concept-visualization-for-n-queen-problem-885559b055f0
---

#### VISUALIZATION-1

#### Try to place N numbers of queens on an N x N chessboard so that none of the queens attacks each other.

Lets play a simple puzzle game. Your task is to place two more Queens in of the given chessboard such that, there will no Queen attacking the others.

<iframe src="https://codesandbox.io/embed/funtj" width="1192" height="596"></iframe>

Solved it? Pretty simple, wasnt it? The above problem already had 3 queens placed. Will you be able to place all the Queens from a start?

<iframe src="https://codesandbox.io/embed/9um2b" width="1192" height="596"></iframe>

Try to place N numbers of queens on an N x N chessboard so that none of the queens attacks each other vertically, horizontally or diagonally. With every solution, you will be allowed to play the next level with the incremented number of N. Lets start with a 4x4 board. Give it a try.

<iframe src="https://codesandbox.io/embed/fx79v" width="1192" height="596"></iframe>

Are you stuck at a point and it is killing your time? But a computer can solve such puzzles faster. So how does it do that? Lets try to figure it out.

### Lets dive deep into it

The problem stated above is otherwise known as the N Queen Problem, which is a useful test problem for search algorithms. That is why, we might consider trying different search algorithms like BFS, DFS, GA(Genetic Algorithms), Backtracking etc for searching its solution. So lets dive deep into each of these to figure out the best problem-solving approach for this particular problem.

Talking about BFS first, in this approach queens will be placed in every position in each column to check whether it is a solution. Lets see how it works in an intuitive manner.

<iframe src="https://codesandbox.io/embed/kvijf" width="1192" height="596"></iframe>

As you can see most of the arrangements are not even be close to being valid. Dont you think this will lead to unnecessary wastage of time and will increase the time complexity exponentially? Well, try solving it with another intuitive visualization.

So thats it for this article. I hope you have checked out the visualization and if you liked it then do not forget to tell us your thoughts in the comment section below.

> If you want to connect with me, here I am at [Twitter](https://twitter.com/anishaswain) or [Instagram](https://www.instagram.com/anisha_swain_/)

**Announcement:** we will be ding d3.js tutorials soon so stay tuned.

Follow our community [LinkedIn group](https://www.linkedin.com/groups/13894715/), [Facebook](https://www.facebook.com/iamtheuigirl) Page and [Twitter](https://twitter.com/the_ui_girl) for more such articles and posts and meet like-minded people to collaborate.
Containers philosophy
Tags: docker, philosophy
Published: 2020-08-24 19:24:02

---
title: Containers philosophy
published: true
description: Let's talk about some basic container concepts
tags: docker, philosophy
cover_image: https://s2.best-wallpaper.net/wallpaper/3840x2160/1805/Dock-ship-container-sea_3840x2160.jpg 
---
There are a lot of posts talking about containers: how to use them, how they are implemented and so on. But nothing about the high level ideas they should follow. So, let's talk about containers philosophy. I was not able to find a good post explaining the basic rules of containers so, let's try to describe them:

* **A container is ephemeral**: A request to the container engine to run a container will produce a running instance of an image.  It is however, not guaranteed the image will run on the same container in perpetuity. For example, if using a container orchestrator,  requests may be made to execute many replicas of the same container image. If a container is stopped (because there was a crash, an error...), the orchestrator can start a new one.
* **Persistent storage should be managed in volumes, not within containers**: this is related to the previous one. If a container is ephemeral, shared persistent storage from that container should be avoided. Mount a volume to keep data when a container is created again.
* **A container should have only one mission**: An advantage to using containers is the ability to subdivide the functions of a system into smaller collaborating pieces. This is how Docker may be used to achieve a microservice architecture. Microservices offer benefits in terms of scalability and maintenance.
* **A container should minimize application dependencies**: This will reduce the resource obligations required of the host by the container and possible interactions between libraries, configurations...
* **A container should be treated like an executable**: It should maintain its own minimal dependency set so when  run, there exists no necessity for the user or administrator to maintain. The container should function as required as a “black box” within the system; which reduces administrative overhead and dependency mismatch.

Some of those rules remind me to the [SOLID principles](https://dev.to/magarcia/solid-principles-of-object-oriented-design-5gh0), don't you?
YouTube Video | CSS Animation Tutorial -4
Tags: css, html, youtube, webdev
Published: 2020-08-24 19:23:05

This video series contains CSS animation tutorial and projects. In the fourth part we will be first creating a pop-up subscription list, followed by an animated eCommerce shopping cart. At last we create a flip card rotate animation.

![Animation](https://res.cloudinary.com/dxkxvfo2o/image/upload/v1598295332/css-animation-4.1_lwef4x.gif)*Animation*

This is the fourth part of the series.

{% youtube HpfcbeJJFm0 %}

Please do like it and [Subscribe](https://www.youtube.com/channel/UCRf7mazcufqZxd2pR3oQJuQ?sub_confirmation=1) to my channel for more videos.
YouTube Video | CSS Animation Tutorial -3
Tags: css, html, youtube, webdev
Published: 2020-08-24 19:20:52

This video series contains CSS animation tutorial and projects. In the third part we will be completing our Mario Kart Animations.

![Animation](https://res.cloudinary.com/dxkxvfo2o/image/upload/v1598295332/css-animation-3_lrsz5f.gif)*Animation*

This is the third part of the series.

{% youtube gKCN83EPDJw %}

Please do like it and [Subscribe](https://www.youtube.com/channel/UCRf7mazcufqZxd2pR3oQJuQ?sub_confirmation=1) to my channel for more videos.
YouTube Video | CSS Animation Tutorial -2
Tags: css, html, youtube, webdev
Published: 2020-08-24 19:18:27

This video series contains CSS animation tutorial and projects. In the second part we will be learning about keyframes and applying them to create Mario Kart Animations.

![Animation](https://res.cloudinary.com/dxkxvfo2o/image/upload/v1598295332/css-animation-2_rp6myo.gif)*Animation*

This is the second part of the series.

{% youtube rIusjZ1dz2k %}

Please do like it and [Subscribe](https://www.youtube.com/channel/UCRf7mazcufqZxd2pR3oQJuQ?sub_confirmation=1) to my channel for more videos.
Finally Understanding JavaScript
Tags: codenewbie, javascript, beginners, books
Published: 2020-08-24 19:01:20

I can't tell you enough, how much I am starting to get JavaScript after four weeks of tutorials, reading, challenges, and games! This really was a learning experience for me. I had to figure out how my brain wanted information presented for it to stay put. 

I got so excited when I finally understood how loops work with the help of *Head First JavaScript Programming A Brain-Friendly Guide* by Eric Freeman & Elisabeth Robson. If you are having trouble diving into Javascript (like I did), I highly recommend this book if you are a visual learner. There were pictures and arrows and browser examples. I never had been so excited to read a book and try out the exercises!

I even learned how to code Happy Birthday! 
```javascript
var name = "Joe";
var i = 0;

while (i < 2) {
  document.write("Happy Birthday to you.<br>);
  i = i + 1;
}

document.write("Happy Birthday dear " + name + ",</br>");
document.write("Happy Birthday to you. </br>;
```
I also learned what pseudocode is, which was very helpful to understand the outline of what's going on before you even insert the JavaScript code. It reminds me of the fifth grade when we would brainstorm our short stories--figuring out the beginning, what will happen in the middle, and how we get to the end. I don't know why I didn't think of writing out the logic first! It makes so much sense to visually see what codes are appropriate for each action. 

My mind is blown. Functions, arguments, parameters, global and local variables . . . I'm quite enjoying JavaScript!

**Last Week's Accomplishments:**
- Attacking JavaScript at a different angle

**Check it out:**
- Books I've Started:
  - *Head First JavaScript Programming A Brain-Friendly Guide* by Eric Freeman & Elisabeth Robson

**On My Mind:**
- Who out there is a visual learner? Do you have any tips for making learning code fun? Or understandable?

Until next week!
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/59exhldxjocxu0sa4bz6.png)
YouTube Video | CSS Animation Tutorial -1
Tags: html, css, webdev, youtube
Published: 2020-08-24 19:15:34

This video series contains CSS animation tutorial and projects. In the first part we will learn about the awesome CSS property of transform.

![Animation](https://res.cloudinary.com/dxkxvfo2o/image/upload/v1598295331/css-animation-1_tne7wt.gif)*Animation*

This is the first part of the series.

{% youtube tNjEyw0bu10 %}

Please do like it and [Subscribe](https://www.youtube.com/channel/UCRf7mazcufqZxd2pR3oQJuQ?sub_confirmation=1) to my channel for more videos.
Concept Visualization for sorting of Array elements
Published: 2023-07-16 08:15:41

---
title: Concept Visualization for sorting of Array elements
published: true
date: 2020-08-24 19:10:18 UTC
tags: 
canonical_url: https://theuigirl.hashnode.dev/concept-visualization-for-sorting-of-array-elements-71a6ab5920bf
---

#### Visualization-1

#### Insertion sort is one of the simplest ways of sorting a list of elements.

In computer science, a sorting algorithm is an algorithm that puts elements of a list in a certain order. The most-used orders are numerical order and lexicographical order.

Insertion sort is one of the simplest ways of sorting a list of elements. The algorithm is based on the idea that the position of an element will be decided based on its appropriate position in a sorted array. Each element in an array is positioned in each iteration, thereby the complexity is O(n) with O(n2) comparisons.

The resultant array increases by one element in each iteration. If the current element is greater, then it leaves the element in its place and moves on to the next element else it finds its correct position in the sorted array and moves it to that position. This is done by shifting all the elements one by one, that is larger than the current element, in the sorted array to one position ahead.

### Make it more awesome
<iframe src="https://codesandbox.io/embed/8c4u6" width="700" height="350"></iframe>

Insertion Sort is simple, adaptive and stable yet less efficient as compared to Quicksort, Heapsort or Heap sort.

So thats it for this article. I hope you have checked out the visualization and if you liked it then do not forget to tell us your thoughts in the comment section below.

> If you want to connect with me, here I am at [Twitter](https://twitter.com/anishaswain) or [Instagram](https://www.instagram.com/anisha_swain_/)

**Announcement:** we will be ding d3.js tutorials soon so stay tuned.

Follow our community [LinkedIn group](https://www.linkedin.com/groups/13894715/), [Facebook](https://www.facebook.com/iamtheuigirl) Page and [Twitter](https://twitter.com/the_ui_girl) for more such articles and posts and meet like-minded people to collaborate.
A new architecture for React + Mobx
Tags: react, javascript, webdev, mobx
Published: 2020-08-24 19:08:16

At work we wanted to move away from our app that uses knockoutJS to react. After some experimentation with redux and contextAPI, we disliked how quickly things could get complicated with a large store even with a relatively simple app. So we decided to go with the most similar thing to knockoutJS, mobx. Familiarity is a powerful force.

After this decision, we started looking at architecture suggestions online and found many build apps basically the same as redux: one large store that is of many others, the component subscribes to the large store and trigger the store to make API calls. 

This felt very deja vu and something we rather want to avoid. We found that the large responsibility of the store made it necessary to code complex ways of getting data to the component. Once our use cases grew, so did the redux store and consequently the size or number of reducers and actions files. At some point we just lost the ability to come up with creative names and module organizations, and things went off the rails. The difficulty to understand code also increased as there were logic flow loops of actions, reducers, and stores. Luckily for us, the redux app has not become a money maker for the company so we can put it off to the side at ease. 

For our new app we propose something that closely follows our current knockoutJS architecture: 

1.) Use mobx for global states, such as whether the user has logged in and have what kind of permissions. Global states are important informations that needs to be shared between different features/component trees (this echos the inspiration for RecoilJs). 

2.) For states within a feature/component tree, we use state + props and contextAPI. This follows the intended use as written on the React website.

3.) For services, the components will make and consume the requests themselves. This allows the components to do whatever processing necessary for each use cases without possibly affecting others. We would happily refactor and make a new controller module for repeated use cases; this should be minimized though.

This architecture brings the following benefits:

1.) a clear division of responsibilities as problems with mobx stores will unlikely be conflated with problems with either the state/props or service layer. The vice versa will likely to be true.

2.) no part of this architecture needs to become complicated as each part is responsible for simple goals. The exceptions may be the component since it will contain most of the business logic. However, this can be remedied by abstracting the logic out into a functional controller module whenever necessary.

3.) lessen the application's tie with individual libraries. This has been a major motivation for us. The current knockoutJS app is so tied up with utilities provided by knockoutJS that it is impossible to relocate any part of the application without heavy abstraction removing the library first. The library is a liability for us.

please let me know what you think, I am very welcoming of criticism :)