teleren/devto huggingface dataset:
JavaScript Code Daily Challenge #3
Tags: challenge, javascript, codenewbie, beginners
Published: 2020-11-24 04:44:27

# **About**

This is a series of JavaScript Code Daily Challenge. Each day I show a few solutions written in JavaScript. The questions are from coding practice/contest sites such as HackerRank, LeetCode, Codeforces, Atcoder and etc.

> Arithmetic Operators
> [https://www.hackerrank.com/challenges/js10-arithmetic-operators/problem](https://www.hackerrank.com/challenges/js10-arithmetic-operators/problem)
```javascript
'use strict';

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.trim().split('\n').map(string => {
        return string.trim();
    });
    
    main();    
});

function readLine() {
    return inputString[currentLine++];
}
```
> Complete both the functions in comment
```javascript
/**
*   Calculate the area of a rectangle.
*
*   length: The length of the rectangle.
*   width: The width of the rectangle.
*   
*	Return a number denoting the rectangle's area.
**/
function getArea(length, width) {
    let area;
    // Write your code here
 
    return area;
}
```
```javascript
/**
*   Calculate the perimeter of a rectangle.
*	
*	length: The length of the rectangle.
*   width: The width of the rectangle.
*   
*	Return a number denoting the perimeter of a rectangle.
**/
function getPerimeter(length, width) {
    let perimeter;
    // Write your code here
    
    return perimeter;
}
```
```javascript
function main() {
    const length = +(readLine());
    const width = +(readLine());
    
    console.log(getArea(length, width));
    console.log(getPerimeter(length, width));
}
```
Streaming PulseAudio over RTP
Tags: audiovideo
Published: 2023-01-06 01:12:52

---
title: Streaming PulseAudio over RTP
published: true
date: 2020-11-24 04:41:41 UTC
tags: AudioVideo
canonical_url: https://brandonrozek.com/blog/pulseaudiortp/
---

With PulseAudio, we can send a RTP stream over multicast UDP. Here is the bash commands to setup a sink where anything sent to it gets broadcasted to the multicast address 224.0.0.56 at port 46416.

```
pacmd load-module module-null-sink sink_name=RTP
pacmd update-sink-proplist RTP device.description=RTP
pacmd load-module module-rtp-send \
  source=RTP.monitor \
  destination_ip=224.0.0.56 \
  port=46416

```

Then in `pavucontrol`, you can push the audio of any application to the RTP sink we just created.
The Spread operator in JavaScript
Tags: javascript, webdev, codenewbie, 100daysofcode
Published: 2020-11-24 04:26:12

My latest post on JavaScript - Spread operator fully explained is here. 

<hr>

### What does Spread Operator do?  

It expands an iterable object into the list of arguments. (Arrays, Objects, Strings )
When ...arr is used in the function call, it 'expands' an iterable object arr into the list of arguments. 

```javascript
const arr = [34, 22, 13, 3]

console.log(...arr)
  // 34 22 13 3

console.log(arr)
// [ 34, 22, 13, 3 ]
```

### When to use Spread Operator?  

Making a copy of an array object. 

```javascript
const arr = [34,22,13,3]

const newArr = [...arr]

console.log(newArr)
// [ 34, 22, 13, 3 ]

// Proff that ther are not same
console.log(arr === newArr)
// false
```

Concatenating Arrays & Combining objects

```javascript
// combining arrays

const nums = [2,5,84,3]

const newNums = [...nums, 2,865]

// Here adding 2 again does no overwrite the previous occurrence

console.log(newNums)
 // [ 2,  5, 84, 3, 2, 865 ]
```
<hr>

```javascript
 // combining objects
 const user = {
     name = "Rahul"
     age = "16"
     gender = "male"
}

const Alex= {
       ...user,
       isAthelete: true, 
       name: "Alex"
}

// Providing the name key again overwrites the previous value of the name

console.log(Alex)

// {
//     name: "Alex"
//     age: "16"
//     gender: "male"
//      isAthelete: true, 
// }
```

### Finding highest number in an array of numbers. 

Passing the array into the Math.max() function doesn't work but using the spread operator spreads the array into individual elements of the array.  

```javascript
const arr = [1,2,3,4]
console.log(Math.max(arr))
// NaN

console.log(Math.max(...arr))
// 4
```

### Rest Parameter vs Spread Operator

Even though both of them have the same syntax"...". 
Both of them are the exact opposite of each other. 
The **Rest Parameter** casts a list of items into an array and the spread operator expands an iterable object into its individual elements. 

<hr>
Thanks For Reading. Anything going in your mind? Comment down below!
How Do You Pass a Method to gsub in Ruby?
Tags: help, ruby
Published: 2020-11-24 04:14:30

---
title: How Do You Pass a Method to gsub in Ruby?
published: true
description: Building off Ben's static site generator by DRY'ing it up a bit
tags: help,ruby
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/ordcyp4ylpa7rmmbmaft.jpg
---

I am building off of Ben's static site generator, and I wanted to DRY it up a bit.

{% post ben/one-thing-led-to-another-and-i-built-my-own-static-site-generator-today-5enj %}

I have a few methods:

```ruby
prod_build = ARGV[0] = "production_build"

# Read files

def page_partials(new_page_partial)
  pages = "site/#{page_partial}.html"
  new_page_partial = File.open(pages).read
end

def script_partials(new_script_partial)
  scripts = "site/#{script_partial}.js"
  new_script_partial = File.open(scripts).read
end

def style_partial(new_style_partial)
  styles = "site/#{style_partial}.css"
  new_style_partial(styles).read
end

puts page_partials()
```

I'm not a Rubyist, though I've dabbled in it. I assume these methods are correct, considering:

```ruby
build_string = base_html
  # How do you use a block in a .gsub method???
  .gsub("{{ head }}" {page_partials})
  .gsub("{{ seo }}", seo_html)
  .gsub("{{ main }}", main_css)
  .gsub("{{ dev }}", dev_html)
```

I have a bunch of `.gsub` methods that expect a file, will change the file name, and in the build string, will create the file.

What I want to know is, as a JavaScript dev, _how_ to pass these methods as parameters to the `.gsub` method in a block and _if_ you can do this.

## Shifting paradigms

I haven't looked at this code in a month as I was sick for that long. I have no idea what I was aiming for as such I am a little lost. JavaScript handles things much differently and I am trying to apply my js knowledge to Ruby and that seems to be a bad idea.

Thanks for helping, if you can.
Tracking an Instagram posts engagement in real time with instascrape
Tags: showdev, datascience, python, contributorswanted
Published: 2020-11-24 03:39:05

In this post, I'm going to track the engagement of a single Instagram post in real time using the open source Python Instagram scraping library _instascrape_ :snake:. 

{% github chris-greening/instascrape %}

For the purposes of this blog post, we'll be scraping a single post across one hour. This can easily be extended however to span more posts over longer periods of time with just a couple modifications.

# The script 

Since _instascrape_ abstracts out a lot of the tedious work, the script is relatively straightforward:

```python
import time 
import datetime 

import instascrape

def track_post(url: str):
    """
    Return a list of datetimes and a list of strings from an 
    Instagram post scraped across a one hour period.
    """ 
    times = [] 
    likes = []
    now = datetime.datetime.now()
    end_time = now + datetime.timedelta(hours=1)

    while now < end_time:
        time.sleep(60)     

        post = instascrape.Post(url) 
        post.scrape()

        now = datetime.datetime.now()
        
        times.append(now)
        likes.append(post.likes)
    return times, likes
```

Now all we have to do is pass a valid Instagram post URL to `track_post`, wait an hour, and we'll have our data! :watch:

# Collecting the data

```python
dates, likes = track_post('https://www.instagram.com/p/CH3E7omnUBj/')
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/7noczfoa3meja0dr3vlj.jpg)

Great! Now plotting our data using [_matplotlib_](https://matplotlib.org/api/pyplot_summary.html) gives us 

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

# In conclusion 

Therefore, we're able to track growth of an Instagram post using _instascrape_ very easily :raised_hands:. This was just a simple example but can have many applications. You can compare growth at different times of day, track how your posts perform over time, analyze how posts grow, etc. 

If you're interested in learning more about _instascrape_, check out some of my other blog posts 

{% link https://dev.to/chrisgreening/scraping-25-000-data-points-from-joe-biden-s-instagram-using-instascrape-1026 %}

{% link https://dev.to/chrisgreening/visualizing-instagram-engagement-with-instascrape-326h %} 

or better yet, drop the official repository a star :star: and get involved with contributions! 

{% github chris-greening/instascrape %}
Code Smell 33 - Abbreviations
Tags: oop, codenewbie, programming, tutorial
Published: 2020-11-24 03:08:14

*Abbreviating is very important so that we look smart and save memory and mind space.*

# Problems

- Coupling

- Bad Naming

- Declarativeness

- Ambiguity

- Readability

- Premature Optimization

{% post https://dev.to/mcsee/code-smell-20-premature-optimization-4moe %}

# Solutions

1. Use meaningful/[declarative](https://mcsee.hashnode.dev/what-exactly-is-a-name-part-i-the-quest) names

# Examples

- Variable naming

- Function naming

- Package naming

- Class naming

# Sample Code

## Wrong

{% gist https://gist.github.com/mcsee/946b6391e043d6abec9a3ae5976c5d8f %}

## Right

{% gist https://gist.github.com/mcsee/6b5865d3a16ed5ccccd34348070d7d62 %}

# Detection

We can't automate choosing what is a *short* name and a *declarative*.

Some "modern" and shinny languages enforce this bad practice. So we should wisely choose a good language instead.
 
# Tags

- Declarative

# Conclusion

Computer science was born from the mother of science (mathematics). In math, the assignment of single letter variables *(i, j, x, y)* is a good practice.

The concept of reference arose from the variable.

Many people wondered why mathematicians can work with such short variables, and computer scientists cannot.

For mathematicians, once entered into a formula, variables lose all semantics and become indistinguishable.

We need to care more about semantics and reading.

Our brain wastes a lot of energy figuring out what is the meaning of an abbreviation.

It is 2020, We need to write software for humans, not for compilers.

# Relations

{% post https://dev.to/mcsee/code-smell-06-too-clever-programmer-37lb %}

# More info

[Good Names](https://mcsee.hashnode.dev/what-exactly-is-a-name-part-i-the-quest)

# Credits

Photo by <a href="https://unsplash.com/@mybibimbaplife">Jessica Knowlden</a> on <a href="https://unsplash.com/s/photos/small">Unsplash</a>

* * *

> A long descriptive name is better than a short enigmatic name. A long descriptive name is better than a long descriptive comment.

_Robert Martin_
Top coding questions asked by Morgan Stanley
Tags: codenewbie, interview, codequality, programming
Published: 2020-11-24 03:07:25

Preparing for the coding interviews is another big challenge, and I have realised hw important is to stay focussed and find the right resources for practicing.

If you are preparing for Morgan Stanley, checkout all questions you need to prepare for it- 

https://geeks-terrace.blogspot.com/2020/11/list-of-questions-asked-by-morgan.html
Monetizing Blazor.help
Tags: webdev, dotnet, csharp, blazor
Published: 2020-11-24 02:53:25

So I'm an old school developer currently converting a web forms application that I've been working on for the last decade from VB to C# and then hopefully to Blazor. I bought the domain Blazor.help and would like to produce tutorial videos to monetize on the site and on YouTube so I'm interested in building a little team that would like to learn and develop something together. Google allows me to export my earnings for each web site and video so if we write video scripts together, it shouldn't be hard to keep track of who contributed what to each video and then split the earnings from there. I'd have to take a cut to make up for taxes and administration though, thinking 8%. If anyone is interested, let me know here. Thinking I'll try to use this to organize until we can code up our own little platform that is more suitable for project management. Just FYI, I'm relatively new to C# so I still have a lot to learn.
Released 1.2.5 - whoishiring
Tags: saas, jobboard, europe, startup
Published: 2020-11-24 00:37:33

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

## [1.2.5] - 2020-11-23
- Fix most popular talents carousel to display
- Translated links in unicorn API (Most popular candidates)
- Added pagination to company view limiting listings to 20 per page. 
- Updated translation files
- Minor css change on job posting to make them more readable
- More details at https://whoishiring.de and full changelog at https://whoishiring.de/changelog.md

## Why do we post this?
Keeping track of what we work on, and communicating our updates keeps us accountable, and motivated.
Parsing markdown in frontmatter for Eleventy templates, using filters
Tags: eleventy, webdev
Published: 2020-11-24 10:30:14

---
title: Parsing markdown in frontmatter for Eleventy templates, using filters
published: true
date: 2020-11-24 00:00:00 UTC
tags: Eleventy, webdev
canonical_url: https://victorcamnerin.com/articles/parsing-markdown-in-frontmatter-for-eleventy-templates-using-filters/
---

I encountered an interesting challenge the other day. I have a client project where I'm using Eleventy for my site generation. On of the collections (basically a set of pages generated during build-time from markdown files) would include multiple frontmatter values containing markdown. However, these would not be correctly parsed when added to the template file. So I thought it would be a perfect use case for a template filter.

So, first of all, I created a new file with my filter.

```js
// markdown-filter.js

const MarkdownIt = require('markdown-it');

module.exports = content => { 
  const md = new MarkdownIt({ 
    html: true 
  }); 

  return md.render(content);
};
```

```js
// .eleventy.jsconst 

markdownFilter = require('[path to your file]/markdown-filter.js');

module.exports = content => { 
  config.addFilter('markdownFilter', markdownFilter);
};
```

```html
<!-- Our template file -->
<div class="markdown-filter"> 
  {{ frontmatter-value | markdownFilter | safe }}
</div>
```

Combining it with Eleventys `safe` filter we now have a solid way of parsing markdown in values created in frontmatter.
Getting user locale with JavaScript
Published: 2022-05-09 13:56:35

---
title: Getting user locale with JavaScript
published: true
date: 2020-11-24 00:00:00 UTC
tags: 
canonical_url: https://carl-topham.com//articles/javascript-user-locale
---

To get a user's prefered locale we can query the `navigator.language`.

```
const locale = navigator.language;
console.log(locale); // => "fr"

```

> To change your language in Chrome go to `chrome://settings/languages` and add/edit the list of languages.

To get the full list of user languages we can use `navigator.languages`. This returns an array of locales in order of preference.

```
console.log(navigator.languages); // => ["fr", "en", "en-US"]

```

> Note: The locale value from `navigator.language` is just the first item from the array of locales;

If you need this value on a server side JavaScript build such as Gatsby then remember that the `node.js` environment has no concept of the `navigator` so we need to check for it and specify a fallback when it doesn't exist.

```
const locale = (navigator && navigator.language) || "en";
console.log(locale); // Client => "fr"
console.log(locale); // Server => "en"

```

We can then use this preference to format content such as dates, currency and time for users to their local preferences.
How to copy a portion of an array in JavaScript?
Tags: javascript
Published: 2020-11-24 00:00:00

---
  title: How to copy a portion of an array in JavaScript?
  published: true
  tags: JavaScript
  date: Tue Nov 24 2020 05:30:00 GMT+0530 (India Standard Time)
  canonical_url: https://melvingeorge.me/blog/copy-portion-of-array-javascript
  cover_image: https://melvingeorge.me/_next/static/images/main-a3db21088788de3f5f01e59d5eba2bfb.jpg
  ---
  [Originally posted here!](https://melvingeorge.me/blog/copy-portion-of-array-javascript)
  
To copy a portion or part (from a `start` index to an `end` index) from an array, you can use the `slice()` array method in JavaScript.

Let's say we have an array of names like this,

```js
// names array
const namesArr = ["Roy", "Aleena", "Rachael", "John", "Lily"];
```

Now let's copy the items from index `1` through index `3` using the `slice()` method by passing the start index as the first argument and the end index as the second argument to the method.

### The only thing to note is that if we provide `1` as the start index and `3` as the end index we won't get the item at index `3`, So we have to pass index `4` as the end index so that item at index `3` is included.

It can be done like this,

```js
// names array
const namesArr = ["Roy", "Aleena", "Rachael", "John", "Lily"];

// copy items from index 1 to index 3
// using the slice() array method
// by passing 1 as the start index
// and 4 as the end index
// here item at index 4 is not included
const newArr = namesArr.slice(1, 4);

console.log(newArr); // ["Aleena", "Rachael", "John"]
```

- The method returns a new array with copied contents.

See this example live in [JSBin](https://jsbin.com/yidomokuke/2/edit?js,console).

### Feel free to share if you found this useful 😃.

---
New Twitch Recap: EV Routing Part 2!
Tags: techtalks, wecoded, javascript, codenewbie
Published: 2020-11-23 23:46:54

In our longest stream ever, Jose and I showed off what goes into incorporating EV chargers along a route, and plotting your journey with charging stops! Find the full stream [here](https://www.twitch.tv/videos/813475275), and a clip of the final routing process [here](https://www.twitch.tv/videos/813497822).

Modeling an Audi E-Tron, we started by finding the car's specs, and starting with pre-set battery levels. At this point, we wanted to know things like the battery capacity, how much charge we want to start with, reach each stop with, and arrive with. In "regular" car terms, there's a difference between pulling into the gas station with 1/4 tank left and running on fumes! Choosing one method might lead to fewer road trip stops.

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

An important part of this episode included accounting for each of our potential chargers on the road, knowing how fast they can charge our model of car, our car's specs, and then pulling that information all together to see which available chargers are along our route.

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

Taken around the 18 minute mark, we explain this in laymen's terms a bit more as we chat.

This episode involved a lot of real-world debugging, and finally gave us a color-segmented route with markers to indicate each charging station. 

From this, we could even add charging info to each stop, so we can know how long we would have to stay charging, and help us add up the grand total time of our road trip.

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

Follow us on Twitch for our next episode on building a small service delivery app, and happy mapping!
18 basic git commands you don't want to miss
Tags: git, cli
Published: 2020-11-23 23:25:56

I do use some GUI to run git, but for most basic and simple actions I prefer using cli as it is way faster. Here is a summary of my most used git commands.


Create a new branch and tracking remote branch

```
git checkout -b branch_name origin/branch_name
```

   
See status
```
git status
```



Stage a file
```
git add file_name
```

Unstage a single file
```
git reset file_name
```


Stage all files
```
git add .
```


Unstage all files
```
git reset
```


Discard un-staged changes of a single file
``` 
git checkout file_name
```


Discard all un-staged/staged changes
``` 
git reset --hard
```

Commit staged changes
``` 
git commit -m 'commit message'
```

Add and commit all changes in one step
``` 
git commit -am 'message'
```

Diff between un-staged files and staged files
``` 
git diff
```

Diff between staged files and HEAD
```
git diff --cached
```

See commits
```
git log
```

Diff between HEAD and its previous commit
``` 
git diff @^ @
```

Diff between any commit and its previous commit
```
git diff commit_hash^ commit_hash
```

Reset to a commit and keep the changes un-staged
```
git reset commit_hash
```

Reset to a commit and discard the changes
``` 
git reset commit_hash --hard
```


As always: bonus

Add change to the previous commit but without having a new commit
```
git commit --amend --no-edit
```


That's it. Hope you enjoy it!
Strangler except serverless with OpenJS Architect
Tags: aws, serverless, architect
Published: 2020-11-23 23:24:01

---
title: Strangler except serverless with OpenJS Architect
published: true
description: Proxy any website from your new website!
tags: aws,serverless,architect
//cover_image: https://direct_url_to_image.jpg
---

The [strangler pattern](https://martinfowler.com/bliki/StranglerFigApplication.html) is a technique for refactoring an application with new functionality by wrapping the old logic in new logic. In the modern era of web apps this technique has been adapted to intercept HTTP traffic in new application code, use feature flags to turn on and off new functionality and otherwise proxy everything back to the original domain. A few years back [Ceej](https://twitter.com/ceejbot) pulled off an impressive [migration from monolith to microservices](https://www.youtube.com/watch?v=OuhnwqbefVQ) using this technique at npm Inc. 

## Strangler but serverlessly

By using AWS API Gateway we can do the same thing and even better setting this up takes roughly 30 seconds total. This enables your dev team to pick off routes one by one and make them stateless functions. Or maybe we want to host a static app elsewhere and build the dynamic backend with Lambda. 

Whatever the use case OpenJS Architect makes configuring this setup completely painless. Create an `app.arc` file with the following configuration:

```
@app
myapp

@proxy
testing https://testing.brian.io
staging https://staging.brian.io
production https://brian.io

@http
post /graphql
```

And run `arc init` to generate the app. You can deploy it to your own AWS account with `arc deploy` or setup [Begin](http://begin.com) for CI/CD. This app will proxy all traffic to my brian.io domain except `post /graphql` for my backend code. Eventually I will probably want to move the static assets onto S3 and manage my own CloudFront too …but this can now happen at any time!