teleren/devto huggingface dataset:
Why did I rewrite Momentjs format method using RegExp?
Tags: javascript, webdev, webperf, productivity
Published: 2020-07-11 12:24:51

The popular library momentjs is widely used to any date related calculations. For 10 lines of utility code, we end up using 18kb or 72.5kb `gz` format minified momentjs file. It's not just download time, it also about the memory that it consumes to operate.

Here is an effort to replace that momentjs format code with the RegExp functions with a very few lines.

_If you wish to learn about regEx, visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions_

###Format date in RegExp

```javascript
var months = ['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec'];

//listing all the possible keys to regular exp
Date.regExMap = {
  MMM: new RegExp("\\" + months.join("|"), "gi"),
  dddd: /\b\w+/,
  dd: /\d{2}/,
  YYYY: /\d{4}/,
  hh: /\d{2}(?=:\d{2}:\d{2})/,
  mm: /\d{2}(?=:\d{2}\s)/,
  ss: /\d{2}(?=.[A-Z]{3})/
};

//creating regular exp to query the string
Date.regExKeys = new RegExp("\\"+Object.keys(Date.regExMap).join("|"),"gi");

//adding it to Date default object & having an optional date param
Date.prototype.tinyDateFormat = function(str,date) {
  //validations
  if(str === null || str === undefined || str.length <= 0) throw "invalid string";
  if(date === undefined || date === null) date = this;
  if(!(date instanceof Date)) throw "invalid date";
  
  let newStr = str;
  //extracting the matchable words & looping through
  str.match(Date.regExKeys).forEach((regEx) => {
    if (Date.regExMap[regEx]) {
      newStr = newStr.replace(regEx,date.toString().match(Date.regExMap[regEx]));
      //arr.push(this.toString().match(Date.regExMap[regEx]));
     }
  });
  return newStr;
};
```
###Usage
```javascript
// var date1 = new Date().tinyDateFormat("MMM dd YYYY, hh:mm:ss");
var date = new Date().tinyDateFormat("I am coding on MMM dd YYYY at hh hours & mm minutes");
document.body.innerHTML = date;
```

##Why did I write this?

The companies do interview the people for library/framework knowledge. But if the preference of interview changes to basics or core concepts, everyone would start to get more stability and strength in basics or core. This does helps in the application quality. 

For this momentjs format method, it takes the same amount of time to learn the syntax by library as it takes to write the utility using `RegExp` and get the job done.

The above example may not be covering all the use-cases of momentjs format function. It's not to copy & use it as a small library. But to learn it and to write it again. 

In other than date format cases also, try to take time and write your utility functions on your own. Anyway we do spend time on algorithms. The same time can be spent in writing such a utility functions.

__It is not considered as re-inventing the wheel but it can be marked as "efficient in writing the code using core concepts for the sake of efficient app".__

Heard of `tip of ice-berg` problem? For a few lines from library, we end up using the entire bundle.

_To be efficient may be more beneficial than being knowledgeable. Thanks for reading!_
Daily Developer Jokes - Saturday, Jul 11, 2020
Tags: jokes, dailydeveloperjokes
Published: 2020-07-11 12:00:07

---
title: "Daily Developer Jokes - Saturday, Jul 11, 2020"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
cover_image: "https://private.xtrp.io/projects/DailyDeveloperJokes/thumbnail_generator/?date=Saturday%2C%20Jul%2011%2C%202020"
published: true
tags: #jokes, #dailydeveloperjokes
---

Generated by Daily Developer Jokes, a project by [Fred Adams](https://xtrp.io/) ([@xtrp](https://dev.to/xtrp) on DEV)

___Read about Daily Developer Jokes on [this blog post](https://xtrp.io/blog/2020/01/12/daily-jokes-bot-release/), and check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/).___
### Today's Joke is...
![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e12591b4fccd.png)

---
*Have a joke idea for a future post? Email ___[xtrp@xtrp.io](mailto:xtrp@xtrp.io)___ with your suggestions!*

*This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit.*

<!-- 
Joke text:
___Q:___ Why don't parents teach their kids about regular expressions?

___A:___ Because they don't want them playing with matches
 -->
Best options to translate software
Tags: opensource, help
Published: 2020-07-11 10:37:53

I have been thinking about translion of the open source software didi, even just the readme.

At what stage do I start to ask for translators? Or do I look for free machine translation software?

I feel that a translation of the readme would be more inclusive and might assist with onboarding new collaborators at this early stage.

What do you think?
Quick, Shareable UIs for Machine Learning
Tags: machinelearning, opensource, python, showdev
Published: 2020-07-11 10:36:24

I started getting into ML in 2019, and I've constantly been frustrated at how terrible accessibility is. It can take so long to set up all the dependencies and debug the code just to run inference. I'm often surprised at how really popular models and repos still don't have any interfaces that just let you try out the model..

So me and a few friends built an open source python library that makes it easy to wrap a model (or any function) with a GUI so that anyone, anywhere can use it (while its running on your laptop!). Here's an interface you can create in just one line of extra code.

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

Check it out on [Github](https://github.com/gradio-app/gradio) or our website: [gradio.app](https://gradio.app) 

This is my first Python library, so would absolutely love some feedback! :)
Basic of Pandas 
Published: 2020-07-11 10:07:34

**Pandas** is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users.
```bash
pip install pandas
```
## Advantages
 - Fast and efficient for manipulating and analyzing data.
 - Data from different file objects can be loaded.
 - Easy handling of missing data (represented as NaN) in floating point as well as non-floating point data
 - Size mutability: columns can be inserted and deleted from DataFrame and higher dimensional objects
 - Data set merging and joining.
 - Flexible reshaping and pivoting of data sets
 - Provides time-series functionality.
 - Powerful group by functionality for performing split-apply-combine operations on data sets. 

## Getting Started
After the pandas has been installed into the system, you need to import the library. This module is generally imported as – 
```python
import pandas as pd
```
Pandas generally provide two data structure for manipulating data, They are:
 - **Series**
 - **DataFrame**
How to make a column non-nullable in Spark Structured Streaming
Tags: spark
Published: 2020-07-11 10:06:30

# TLDR
Like this:
```
import org.apache.spark.sql.catalyst.expressions.objects.AssertNotNull
import org.apache.spark.sql.functions.col

dataFrame
  .withColumn(columnName, new Column(AssertNotNull(col(columnName).expr)))
```

# Changing column nullability in Batch mode
For Spark in Batch mode, one way to change column nullability is by creating a new dataframe with a new schema that has the desired nullability. 

> ```
>  val schema = dataframe.schema
>  // modify [[StructField] with name `cn`
>  val newSchema = StructType(schema.map {
>    case StructField( c, t, _, m) if c.equals(cn) 
>         =>  StructField( c, t, nullable = nullable, m)
>    case y: StructField => y
>  })
>  // apply new schema
>  df.sqlContext.createDataFrame( df.rdd, newSchema )
> ```
https://stackoverflow.com/a/33195510/13532243

However, this approach isn't supported for a structured streaming dataframe, which fails with the following error.
```
Caused by: org.apache.spark.sql.AnalysisException: Queries with streaming sources must be executed with writeStream.start();
	at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$.org$apache$spark$sql$catalyst$analysis$UnsupportedOperationChecker$$throwError(UnsupportedOperationChecker.scala:389)
	at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:38)
	at org.apache.spark.sql.catalyst.analysis.UnsupportedOperationChecker$$anonfun$checkForBatch$1.apply(UnsupportedOperationChecker.scala:36)
```

# Make a column nullable in structured streaming
In the same stackoverflow thread, another answer provides a way how to make a non-nullable column nullable, which works for Structured Streaming queries.

> ```
> dataframe.withColumn("col_name", when(col("col_name").isNotNull,
>   col("col_name")).otherwise(lit(null)))
> ```
https://stackoverflow.com/a/46119565/13532243

This is a neat trick, since Spark has to account for the (hypothetical) fact that a value could be null and mark the column nullable, even though the column doesn't contain any null value in practice.

# Make a column non-nullable in structured streaming
If you know that a nullable column in fact only contains non-nullable values, you may want to make that column non-nullable. Here's the trick with `AssertNotNull` again:

```
import  org.apache.spark.sql.catalyst.expressions.objects.AssertNotNull
import org.apache.spark.sql.functions.col

dataFrame
  .withColumn(columnName, new Column(AssertNotNull(col(columnName).expr)))
```

How does it work? Looking at its implementation https://github.com/apache/spark/blob/3fdfce3120f307147244e5eaf46d61419a723d50/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/objects/objects.scala#L1591-L1628, the key is that `AssertNotNull` overrides `nullable` and always returns `false`. That's how Spark determines this column to be non-nullable. Of course, if your column unexpectedly contains null values, the query will fail with a `NullPointerException`.
How to make protected Component(not routes) in reactjs
Tags: react, npm
Published: 2020-07-11 10:01:32

I have requirement for e-commerece portal. On home page all the components works without authentication but once I logged in then in topbar I have some authenticated components. 

Same there are many other components which is available once you login. So I am looking for mechanism where we can do Protected component rendering mechanism like ProtectedRoute. If anyone has idea then do let me know.

Thank you
How to offer an innovative software to a big corporation?
Tags: discuss, healthydebate, tips
Published: 2020-07-11 09:55:34

First of all, I hope you are doing well in these weird times. 

Few months ago I had some software ideas that I wanted to offer to some big corporations and I got the first problem: **HOW?**

First I've tried cold emailing (not spamming, going through proper channels to get the email from the person I need) but then I got another obstacle "not being in the same country" so we couldn't get a live meeting (they wanted it of course :) ).

So I tried offering this software idea (as well as development of it) to some local companies and it was successful. 

Do you think that the geographical distance is crucial in offering innovative software ideas to big corporations and what would you suggest other than emailing directly? 
I can't wait to hear your thoughts and experiences in this kind of problems. 

**Stay safe!**
balalaika IT newsletter #5
Tags: react, node, java, webdev
Published: 2020-07-11 09:52:29

---
title: balalaika IT newsletter #5
published: true
description: Curated IT newsletter. From Russia with love. Issue #5.
tags: #react #node #java #webdev
cover_image: https://dev-to-uploads.s3.amazonaws.com/i/7dwkz927sf2ausnqygq3.jpg
canonical_url: https://blog.balalaikait.com/balalaika-it-newsletter-5
---

# Frontend
- Does CSS grid seem kind of complicated to you? Do you find yourself constantly fighting it, endlessly browsing web for yet another hack? Here is [a remarkable cheatsheet](https://yoksel.github.io/grid-cheatsheet/) destined to keep your sanity.
- [An outstanding overview](https://css-tricks.com/an-overview-of-scroll-technologies/) of scrolling technologies and approaches by Zach Saucier.
- Security is something frontend engineers are often not thinking about. It seems like a task for the backend team. What possibly could go wrong on the frontend? Here is [a lengthy list](https://www.simform.com/react-security-vulnerabilities-solutions/) every React developer should keep in mind.

# Node.js
- The TSC is going to have "Next 10 years of Node.js" session on July 16. Here you can find [the agenda](https://github.com/nodejs/node/issues/34260).
- What exciting things happened in the JavaScript language and the V8 engine in 2019? Shu and Leszek take [a tour](https://www.youtube.com/watch?v=TPm-UhWkiq8) of some new features and improvements.

# Java
- What may be simpler than measuring time, right? In reality, Java has multiple APIs to do the job and there are some important restrictions related to each one of those. Here is [a great deep dive](https://dzone.com/articles/java-advent-calendar-measuring-time-from-java-to-k) on the topic.
- Have you ever asked yourself a question of whether the allocation of Java objects on the heap involves any contention? By all means, it should, as multiple threads have to be coordinated during those allocations. Yet, HotSpot JVM has another tricky optimization, called Thread-Local Allocation Buffers which allows avoiding contention in most scenarios. If you want to learn more, here is [an extensive read](https://alidg.me/blog/2019/6/21/tlab-jvm).

# General
- At first glance, load balancing seems to be simple as a concept. In fact, it is extremely hard to make it right. Guys from DataStax recently implemented the Power of Two Random Choices algorithm for Apache Cassandra. It showed a sizeable improvement in high load scenarios. Learn more [here](https://www.datastax.com/blog/2020/06/improved-client-request-routing-apache-cassandratm).
- [The story](https://slack.engineering/a-terrible-horrible-no-good-very-bad-day-at-slack-dfe05b485f82) of the Slack downtime on May 12th, 2020.
- [ARM is conquering the world](https://smist08.wordpress.com/2020/06/24/exciting-days-for-arm-processors/). Soon you will find it in servers, supercomputers, and even your MacBook!
We The Bridge
Tags: webdev, ecommerce, marketing
Published: 2020-07-11 09:43:08

Want your store to make an online presence ? Want a website of your own ?
Whether you a retailer or a business man we CARE for you ! 
We make sure that the website is customised especially to cater your needs.Choose from our different packs now and get Rs. 500 off ! 
Visit Now !!
https://flipretail.in
Css position in 5 minute.
Tags: css, tutorial
Published: 2020-07-11 09:33:09

Syntax: 

Position là 1 POPERTY của css language. Được sử dụng khi chúng ta muốn định vị vị trí của các HTML ELEMENT.

Position poperty có 5 values: 
```css 
position: static; *
position: relative;
position: absolute;
position: fixed;
position: sticky;
```
Các poperty được sử dụng chung với position là 

```css
top: <length>;
left: <length>;
right: <length>;
bottom: <length>;
z-index: <number>;
```

Cách sử dụng: 

## Static *
Dấu `*` cho chúng ta biết static là giá trị mặc định. Nghĩa là phần tử ở đúng luồng thông thường của 1 html document.

Left,top,right,bottom không có tác dụng ở đây.

## Relative 
Làm thay đổi vị trí của relatived element. Mà không ảnh hưởng đến vị trí của các phần tử khác. 

Phần tử được định vị theo 1 hệ tọa độ Oxy với tâm O chính là phần tử, sử dụng poperty top,left,.. để di chuyển phần tử theo các chục.

## Absolute
Chuyển phần tử của bạn sang luồng mới. Lúc này bạn có vẻ đang chồng lên luồng ban đầu. Luồng ban đầu không biết về bạn nữa, và cái vị trí lúc đầu phần tử chiếm sẽ bị các phần tử trong luồng đó chiếm.

Để căn chỉnh absolute ta cần biết phần tử cha có position: relative gần nhất của nó. Định vị nó theo hệ tọa độ Oxyz với O là góc trên bên trái của phần tử cha ở trên. Chỉnh tọa độ theo trục z sử dụng z-index.

## Fixed
Chuyển phần tử lên luồng mới ,giống như absolute. Điểm khác biệt ở chỗ phần tử này được định vị so với màn hình do đó nó vẫn đứng im cho dù bạn có cuộn trang web lên hay xuống.

Hệ tọa độ để ta định vị phần tử bị fixed Oxyz với tâm O là góc trên bên trái của màn hình. 

## Sticky
Static là kết quả của 2 poperty hợp lại: relative và fixed.
Nó được định vị relative cho đến khi nó cách vị trí vewport 1 khoảng xác định lúc này nó chuyển sang fixed.

## Điểm quan trọng: 
Cách trình duyệt tìm width của 1 element khi nó được áp dụng absolute và fixed.

Đầu tiên trình duyệt tìm poperty width của element để lấy width.
Nếu width không được xét thì lúc này width của phần tử bằng đúng width của phần tử con bên trong nó.
DEV to Github profile assistant
Tags: javascript, svelte, github
Published: 2020-07-11 09:28:51

Github released a new feature that let's you create your resume/profile. I have made a README.MD [generator](http://github.anoram.com/) that fetches your profile's Name, bio and recent 5 articles.

Here is my profile preview
![Preview](https://dev-to-uploads.s3.amazonaws.com/i/moj1al3vf76xkdg31aqe.png)

To create a profile simply use your username as repository's name. You will be greeted with this

![Greet](https://dev-to-uploads.s3.amazonaws.com/i/ked9mbnut1me9c99k67b.png)

Go get your profile's README here http://github.anoram.com/
The Generated MD looks like this.

![Generated MD](https://dev-to-uploads.s3.amazonaws.com/i/19kb9gns2docqnjb39kl.jpg)


*Update 1:*
* Fixed a bug not able to generate MD.
* Code doesn't break if inputs are bad.
* Adds dynamic profile badge and followers badge.
What to release and when?
Tags: opensource, help
Published: 2020-07-11 09:28:07

I have a classic mono repo with some packages, I work on a given branch as a whole repository. Each time a feature or bug is worked on. The main repository is versionless because it is not actually a piece of software, it is instead an organization of source code. All distributed code atually originates from a compiled language and is output into it's respective git sub module, the outcome is a distribution of each package in its own separate distribution repository.

When I ceckout branch #64-feature-on-package-x
I bumb the version of the package or packages I have worked on.

Here's where things get tricky in my head. Do I then release this package by heading over to master and hitting publishing to npm? Because my packages are designed to work independently, for example a cli calls a library but the library can be called with a custom front end. I would imagine the library should be released first then the cli.

The result may be internally we have a nice incremtial versioning on each package but thr dist code skipping minor versions and never being released, is this okay?
What is JavaScript and writing “Hello world” Program in JavaScript.
Published: 2020-07-11 09:19:56

First, I would like to welcome to you all in this article. If you are completely new to the JavaScript, you are in the right place. 

#What is JavaScript?
JavaScript is a programming language. JavaScript was created by Brendan Eich in 1995. Initially the purpose of this language was just to “make web pages alive”. But nowadays you can use this language to make server-side, Mobile, and desktop applications using various frameworks and libraries. To run the JavaScript code, we need a JavaScript engine. The browser has an embedded engine.

###For example, 
Chrome and Opera have a V8 engine,
Firefox has spiderMonkey.

These engines read the JavaScript code and then convert it to the machine language and run the machine codes. 
We will go through what this language can do in the browser in the coming tutorials.

Writing the “Hello World” Program in JavaScript. 
You need to have at least,
   1. A Web browser 
   2. And an IDE(Notepad, visual Studio code.. ) 
to run the JavaScript code. 
The good thing is you don’t need to have the internet to run JavaScript code. 
There are many ways you can run the JavaScript codes. 

##1.Using “Script” Tag

You can insert javascript programs to any part of HTML document with the help of 
`<Script>` tag. 

For example,

```
<!DOCTYPE HTML>
<html>

<body>

  <p>Before the script...</p>

  <script>
    alert( 'Hello, world!' );
  </script>

  <p>...After the script.</p>

</body>

</html>
```
This code simply pup ups the message " Hello, world" in the browser.

Like this

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/82f3d8c2gfwbfzyqltwf.JPG)

##2. Using external Scripts.

If we have a lot of code we can put code in the separate file. we need to put the `.js` extension at the end of the javascript file.

Script files are attached to HTML with the src attribute: 

`<script src="script.js"></script>`

Here `script.js` means the javascript file name and 'src' is the attribute. which means get a script from source `script.js`.

You can have multiple script tag to attach multiple `.js` file. 


Thank you so much for reading this article. 

Best wishes to your Learning. If you have any confusion with this article you can comment on the comment box or send me a private message to cbshresthau22@gmail.com

>References

*https://javascript.info/hello-world
*https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/What_is_JavaScript
[Improve yourself] Pick a Theme!
Tags: motivation, improvement
Published: 2020-07-11 09:15:55

---
title: [Improve yourself] Pick a Theme! 
published: true
description: A theme is more powerful than a new years resolution.
tags: motivation,improvement
//cover_image: https://direct_url_to_image.jpg
---

#Introduction
At the beginning of each year we decide to commit to something to improve ourselves. Maybe to go to the gym or read one book per month. Most of the time we dont stick with it and get lost in the first half of the year.
Every january i see so many new faces in the gym but in march/april all these new faces are gone. Because poeple want to see results as fast as possible. A theme is another approach. Its more about a habit and a positive life change instead of strict numbers.

#Themes
But what is a theme?
Imagine this:
Instead of saying "This year i will go to the gym 3 times a week!" you just make this year to a theme:

**The year of fitness**
**The year of coding**
**The year of reading**

Sounds not so impressive or? But it works!
New years resolutions are a good thing but the approach is wrong. Or maybe not wrong but not as good as a theme. You will most likely stick with a theme because its by far more positive and not as strict as "I will lose 10 kg/pounds".

And if you want you can also split themes within a year. For example you pick one theme per season. 3 months are manageable and not as long as one full year.

#Resources
Here is a very good video about the topic:
https://www.youtube.com/watch?v=NVGuFdX5guE

#Summary
A theme is motivating, positive and can help you to stick with new habits. Its easy and everyone can try it out. Maybe you start with it next year or next season. I just hope that it will help you to reach your goals!
Adding navbar and footer using jquery but still error
Tags: help
Published: 2020-07-11 08:47:32

I try to use:

$(function(){ $('#navbar').load('../assets/html/navbar.html');
});

And it worked!, but for navbar only.

I also want to add footer so i try this:

$(function(){ $('#navbar').load('../assets/html/navbar.html');
$('#footer').load('../assets/html/footer.html');
});

But the only thing i see is the footer.

Can you please tell me what is the solution for this? Please...