Top 10 Angular Tutorials and Courses for Web Developers

Hello guys, if you are interested in learning the Angular framework, one of the best and most popular JavaScript frameworks for developing component-based Web GUI and looking for some awesome courses then you have come to the right place. In this article, I am going to share some of the best resources e.g. books, tutorials, and courses to learn the Angular framework, formerly known as Angular JS and now famous as simply Angular. It’s backed by Google, hence you should not worry about it being out-dated and lose relevance in a couple of years. Any investment you made in learning Angular will pay you rich dividends in the coming years. As per StackOverflow’s 2018 Survey, Angular is the second most popular framework after Node.js and one of the main reasons behind JavaScirpt’s popularity among web developers.

Link: https://dzone.com/articles/top-10-angular-tutorials-and-courses-for-web-devel?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

How to Create a Mall Map with Real-time Data Using WRLD

As a web developer, you sometimes find yourself in a position where you are required to implement a map. Your first choice is to use Google Maps, right?

This looks okay. However, you may be required to overlay additional information over the map with the help of markers. You can use this method, or you can find a better solution that allows you to create markers inside an indoor 3D map! How cool is that? With indoor markers, you can provide unique experiences for users where they will be able to access information and interact with UIs right inside the map.

In this tutorial, we’ll create two demos illustrating the power of WRLD maps. You’ll learn how to create custom apps that can overlay real-time information over a 3D map. In the first demo, we’ll add interactive markers to an existing indoor map of a mall. In the second demo, we’ll place colored polygons over parking areas, indicating capacity.
You can find the completed project for both demos in this GitHub repository.
Prerequisites
For this article, you only need to have a fundamental understanding of the following topics:

JavaScript DOM
ES6 Syntax
ES6 Modules

I’ll assume this is your first time using WRLD maps. However, I do recommend you at least have a quick read of the article:

Building Dynamic 3D Maps

You’ll also need a recent version of Node.js and npm installed on your system (at the time of writing, 8.10 LTS is the latest stable version). For Windows users, I highly recommend you use Git Bash or any other terminal capable of handling basic Linux commands.
This tutorial will use yarn for package installation. If you prefer to use npm, please refer to this guide if you are unfamiliar with yarn commands.
Acquire an API Key
Before you get started, you’ll need to create a free account on WRLD. Once you’ve logged in and verified your email address, you’ll need to acquire an API key. For detailed instructions on how to acquire one, please check out the Getting Started section on Building Dynamic 3D Maps where it’s well documented.
Approach to Building the Map
The creation of WRLD maps is a major technological achievement with great potential benefits for many industries. There are two main ways of expanding the platform’s capabilities:

Using built-in tools, e.g. Map Designer and Places Designer
Building a custom app

Let me break down how each method can be used to achieve the desired results.
1. Using Map Designer and Places Designer
For our first demo, we can use Places Designer to create Store Cards. This will require us to create a Collection Set where all Point of Interest markers will be held. This set can be accessed both within the WRLD ecosystem, and externally via the API key. We can pass this data to a custom map created using the Map Designer. With this tool, we can share the map with others using its generated link. If you would like to learn more about the process, please watch the video tutorials on this YouTube playlist.

The beauty of this method is that no coding is required. However, in our case, it does have limitations:

Restrictive UI design – we can only use the UI that comes with Places Designer
Restrictive data set – we can’t display additional information beyond what is provided

In order to overcome these limitations, we need to approach our mall map challenge using the second method.
2. Building a Custom App
Building custom apps is the most flexible option. Although it takes some coding effort, it does allow us to comprehensively tap into the wealth of potential provided by the WRLD platform. By building a custom app, we can create our own UI, add more fields and access external databases in real-time. This is the method that we’ll use for this tutorial.
Building the App
Let’s first create a basic map, to which we’ll add more functionality later. Head over to your workspace directory and create a new folder for your project. Let’s call it mall-map.
Open the mall-map folder in your code editor. If you have VSCode, access the terminal using Ctrl + ` and execute the following commands inside the project directory:
# Initialize package.json
npm init -f

# Create project directories
mkdir src
mkdir src/js src/css

# Create project files
touch src/index.html
touch src/js/app.js
touch src/css/app.css
touch env.js

This is how your project structure should look:

Now that we have our project structure in place, we can begin writing code. We’ll start with index.html. Insert this code:

<html lang=”en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./css/app.css" />
<title>Shopping Mall</title>
</head>
<body>
<div id="map"></div>
<script src="js/app.js"></script>
</body>
</html>

Next, let’s work on css/app.css. I’m providing the complete styling for the entire project so that we don’t have to revisit this file again. In due time you’ll understand the contents as you progress with the tutorial.
@import "https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet.css";
@import "https://cdn-webgl.wrld3d.com/wrldjs/addons/resources/latest/css/wrld.css";
@import "https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.css";

html,
body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}

#map {
width: 100%;
height: 100%;
background-color: #000000;
}

/* ——– POPUP CONTENT ——– */
.main-wrapper > .segment {
padding: 0px;
width: 300px;
}

.contacts > span {
display: block;
padding-top: 5px;
}

Now we need to start writing code for app.js. However, we need a couple of node dependencies:
yarn add wrld.js axios

As mentioned earlier, we’ll be taking advantage of modern JavaScript syntax to write our code. Hence, we need to use babel to compile our modern code to a format compatible with most browsers. This requires installing babel dependencies and configuring them via a .babelrc file. Make sure to install them as dev-dependencies.
yarn add babel-core babel-plugin-transform-runtime babel-runtime –dev
touch .babelrc

Copy this code to the .babelrc file:
{
"plugins": [
[
"transform-runtime",
{
"polyfill": false,
"regenerator": true
}
]
]
}

We’ll also need the following packages to run our project:

Parcel bundler – it’s like a simplified version of webpack with almost zero configuration
JSON Server – for creating a dummy API server

Install the packages globally like this:
yarn global add parcel-bundler json-server

# Alternative command for npm users
npm install -g parcel-bundler json-server

That’s all the node dependencies we need for our project. Let’s now write some JavaScript code. First, supply your WRLD API key in env.js:
module.exports = {
WRLD_KEY: ‘<put api key here>’,
};

Then open js/app.js and copy this code:
const Wrld = require(‘wrld.js’);
const env = require(‘../../env’);

const keys = {
wrld: env.WRLD_KEY,
};

window.addEventListener(‘load’, async () => {
const map = await Wrld.map(‘map’, keys.wrld, {
center: [56.459733, -2.973371],
zoom: 17,
indoorsEnabled: true,
});
});

The first three statements are pretty obvious. We’ve put all our code inside the window.addEventListener function. This is to ensure our code is executed after the JavaScript dependencies, that we’ll specify later in index.html, have loaded. Inside this function, we’ve initialized the map by passing several parameters:

map – the ID of the div container we specified in index.html
keys.wrld – API key
center – latitude and longitude of the Overgate Mall located in Dundee, Scotland
zoom – elevation
indoorsEnabled – allow users to access indoor maps

Let’s fire up our project. Go to your terminal and execute:
parcel src/index.html

Wait for a few seconds for the project to finish bundling. When it’s done, open your browser and access localhost:1234. Depending on your Internet speed, the map shouldn’t take too long to load.

Beautiful, isn’t it? Feel free to click the blue icon. It will take you indoors. Navigate around to see the different stores. However, you’ll soon realize that you can’t access other floors. There’s also no button for exiting the indoor map. Let’s fix that in the next chapter.
Create Indoor Controls
To allow users to switch between different floors, we’ll provide them with a control widget that will allow them to do this. Simply add the following scripts to the head section of the public/index.html file:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdn-webgl.wrld3d.com/wrldjs/addons/indoor_control/latest/indoor_control.js"></script>

Still within the html file, add this div in the body section, right before the #map div:
<div id="widget-container" class="wrld-widget-container"></div>

Now let’s update js/app.js to initialize the widget. Place this code right after the map initialization section:
const indoorControl = new WrldIndoorControl(‘widget-container’, map);

Now refresh the page, and click the ‘Enter Indoors’ icon. You should have a control widget that will allow you to switch between floors. Just drag the control up and down to fluidly move between floors.

Amazing, isn’t it? Now let’s see how we can make our map a little bit more convenient for our users.
Enter Indoors Automatically
Don’t you find it a bit annoying that every time we need to test our map, we need to click the ‘Indoors’ icon? Users may start navigating to other locations which is not the intention of this app. To fix this, we need to navigate indoors automatically when the app starts without any user interaction. First, we require the indoor map id to implement this feature. We can find this information from the indoormapenter event. You can find all Indoor related methods here.
Add the following code in the js/app.js file.

// Place this code right after the Wrld.map() statement
map.indoors.on(‘indoormapenter’, async (event) => {
console.log(event.indoorMap.getIndoorMapId());
});

Refresh the page then check out your console. You should get this ID printed out: EIM-e16a94b1-f64f-41ed-a3c6-8397d9cfe607. Let’s now write the code that will perform the actual navigation:
const indoorMapId = ‘EIM-e16a94b1-f64f-41ed-a3c6-8397d9cfe607’;

map.on(‘initialstreamingcomplete’, () => {
map.indoors.enter(indoorMapId);
});

After saving the file, refresh the page and see what happens.
The indoor mall map should navigate automatically. Next, we’ll look at how we can create cards for each store. But first, we need to determine where to source our data.
Mall Map Planning
To create store cards for our map, we need several items:

Exact Longitude/Latitude coordinates of a store
Store contact information and opening hours
Design template for the store card

Store Card Coordinates
To acquire Longitude/Latitude coordinates, we need to access maps.wrld3d.com. Wait for the map to finish loading then enter the address 56.459733, -2.973371 in the search box. Press enter and the map will quickly navigate to Overgate Mall. Click the blue indoor icon for Overgate Mall and you should be taken to the mall’s indoor map. Once it’s loaded, locate the ‘Next’ store and right-click to open the context menu. Click the ‘What is this place? option. The coordinate popup should appear.

Click the ‘Copy Coordinate’ button. This will give you the exact longitude/latitude coordinates of the store. Save this location address somewhere temporarily.
Store Card Information
You’ll also need to gather contact information from each store which includes:

image
description
phone
email
web
Twitter
opening times

You can source most of this information from Google. Luckily, I’ve already collected the data for you. For this tutorial, we’ll only deal with four stores on the ground floor. To access the information, just create a folder at the root of the project and call it data. Next save this file from GitHub in the data folder. Make sure to save it as db.json. Here is a sample of the data we’ll be using:
{
"id":1,
"title": "JD Sports",
"lat": 56.4593425,
"long": -2.9741433,
"floor_id": 0,
"image_url": "https://cdn-03.belfasttelegraph.co.uk/business/news/…image.jpg",
"description":"Retail chain specialising in training shoes, sportswear & accessories.",
"phone": "+44 138 221 4545",
"email": "customercare@jdsports.co.uk",
"web": "https://www.jdsports.co.uk/",
"twitter": "@jdhelpteam",
"tags": "sports shopping",
"open_time":[
{ "day": "Mon",
"time": "9:30am – 6:00pm"
},]
}

The data is stored in an array labeled ‘pois’. POI stands for Places of Interest. Now that we have the data available, we can easily make it accessible via an API REST point by running the JSON server. Just open a new terminal and execute the command:
json-server –watch data/db.json

It should take a few seconds for the API to start. Once it’s fully loaded, you can test it with your browser at localhost:3000/pois. You can also fetch a single POI using this syntax:
– localhost:3000/pois/{id}
For example, localhost:3000/pois/3 should return a poi record with ID 3 in JSON format.
Store Card Design
We’ll use a clean elegant theme to neatly display contact information and opening times using a couple of tabs. We’ll create markers that will display a popup when clicked. This popup will have the following UI.

The code for this HTML design is a bit long to put here. You can view and download the file from this link. The design only has three dependencies:

Semantic UI CSS
jQuery
Semantic UI JS

Now that we have the data required and the design, we should be ready to start working on our indoor map.
Implementing Store Cards in Indoor Map
First let’s create a service that will allow us to access data from the JSON REST APIs. This data will be used for populating the Store Cards with the necessary information. Create the file js/api-service.js and copy this code:
const axios = require(‘axios’);

const client = axios.create({
baseURL: ‘http://127.0.0.1:3000’,
timeout: 1000,
});

module.exports = {
getPOIs: async () => {
try {
const response = await client.get(‘/pois’);
return response.data;
} catch (error) {
console.error(error);
}
return [];
},
getPOI: async (id) => {
try {
const response = await client.get(`/pois/${id}`);
return response.data;
} catch (error) {
console.error(error);
}
return {};
},
}

Here we are making use of the library axios to request data from the JSON server.
Next, we’ll convert our static HTML design for the Store Card to a format that will allow us to render data. We’ll be using JsRender for this. We’ll break down our static design into three templates:

Base Template – has containers for menu, info and time tabs.
Info Template – tab for store contact information.
Time Template – tab for store opening hours.

First, open index.html and add these scripts to the head section, right after the jQuery and indoor control scripts:
<head>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jsrender/0.9.90/jsrender.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.3.0/semantic.min.js"></script>

</head>

Next, copy this section of code right before the widget-container div:

<!– Menu Tabs UI –>
<script id="baseTemplate" type="text/x-jsrender">
<div class="main-wrapper">
<div class="ui compact basic segment">
<div class="ui menu tabular"> </div>
<div id="infoTab" class="ui tab active" data-tab="Info"></div>
<div id="timeTab" class="ui tab" data-tab="Time"></div>
</div>
</div>
</script>

<!– Info Data Tab –>
<script id="infoTemplate" type="text/x-jsrender">
<div class="ui card">
<div class="image">
<img src=>
</div>
<div class="content">
<div class="header"></div>
<div class="description">

</div>
</div>
<div class="extra content contacts">
<span>
<i class="globe icon"></i>
<a href="" target="_blank"></a>
</span>
<span>
<i class="mail icon"></i>

</span>
<span>
<i class="phone icon"></i>

</span>
</div>
</div>
</script>

<!– Opening Times Data Tab –>
<script id="timeTemplate" type="text/x-jsrender">
<table class="ui celled table">
<thead>
<tr>
<th>Day</th>
<th>Time</th>
</tr>
</thead>
<tbody>

<tr>
<td></td>
<td></td>
</tr>

</tbody>
</table>
</script>

This is how the full code for index.html should look.
Next, let’s create another service that will manage the creation of Popups. Create the file js/popup-service.js and copy this code:
const Wrld = require(‘wrld.js’);
const { getPOI } = require(‘./api-service’);

const baseTemplate = $.templates(‘#baseTemplate’);
const infoTemplate = $.templates(‘#infoTemplate’);
const timeTemplate = $.templates(‘#timeTemplate’);

const popupOptions = {
indoorMapId: ‘EIM-e16a94b1-f64f-41ed-a3c6-8397d9cfe607’,
indoorMapFloorIndex: 0,
autoClose: true,
closeOnClick: true,
elevation: 5,
};

Let me explain each block step by step:

Block 1: WRLD is required for creating the Popup, getPOI function is required for fetching data
Block 2: The templates that we discussed earlier are loaded using jsrender
Block 3: Parameters that will be passed during Popup instantiation. Here is the reference documentation.

Next, let’s add tab menus that will be used for switching tabs. Simply add this code to js/popup-service.js:
const createMenuLink = (linkName, iconClass) => {
const link = document.createElement(‘a’);
link.className = ‘item’;
const icon = document.createElement(‘i’);
icon.className = `${iconClass} icon`;
link.appendChild(icon);
link.appendChild(document.createTextNode(` ${linkName}`));
link.setAttribute(‘data-tab’, linkName);
link.addEventListener(‘click’, () => {
$.tab(‘change tab’, linkName);
$(‘.item’).toggleClass(‘active’);
});
return link;
};

const createMenu = (menuParent) => {
const infoLink = createMenuLink(‘Info’, ‘info circle’);
infoLink.className += ‘ active’;
menuParent.appendChild(infoLink);
const timeLink = createMenuLink(‘Time’, ‘clock’);
menuParent.appendChild(timeLink);
};

You might be wondering why we are using a complicated method of creating menu links. Ideally, we should be able to create them using HTML, then add a small JavaScript script to activate the tabs. Unfortunately, this doesn’t work within the context of a Popup. Instead, we need to create clickable elements using DOM manipulation methods.
The post How to Create a Mall Map with Real-time Data Using WRLD appeared first on SitePoint.

Link: https://www.sitepoint.com/how-to-create-a-mall-map-with-real-time-data-using-wrld/

3 Common Redux Bugs (and How to Fix Them)

Web developers hate bugs because they lead to malfunctioning applications. Bugs make an application to behave in undesirable ways, something which affects the experience of users.
Redux developers hate bugs, too. Because the JavaScript library is mainly used to manage state in applications, any occurrence of bugs often leads to inconsistencies and unnecessary breakages.

Link: https://dzone.com/articles/3-common-redux-bugs-and-how-to-fix-them?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

7 Performance Tips for Jank-free JavaScript Animations

The role of web animation has evolved from mere decorative fluff to serving concrete purposes in the context of user experience — such as providing visual feedback as users interact with your app, directing users’ attention to fulfill your app’s goals, offering visual cues that help users make sense of your app’s interface, and so on.
To ensure web animation is up to such crucial tasks, it’s important that motion takes place at the right time in a fluid and smooth fashion, so that users perceive it as aiding them, rather than as getting in the way of whatever action they’re trying to pursue on your app.
One dreaded effect of ill-conceived animation is jank, which is explained on jankfree.org like this:

Modern browsers try to refresh the content on screen in sync with a device’s refresh rate. For most devices today, the screen will refresh 60 times a second, or 60Hz. If there is some motion on screen (such as scrolling, transitions, or animations) a browser should create 60 frames per second to match the refresh rate. Jank is any stuttering, juddering or just plain halting that users see when a site or app isn’t keeping up with the refresh rate.

If animations are janky, users will eventually interact less and less with your app, thereby negatively impacting on its success. Obviously, nobody wants that.
In this article, I’ve gathered a few performance tips to help you solve issues with JavaScript animations and make it easier to meet the 60fps (frame per second) target for achieving smooth motion on the web.
#1 Avoid Animating Expensive CSS Properties
Whether you plan on animating CSS properties using CSS Transitions/CSS keyframes or JavaScript, it’s important to know which properties bring about a change in the geometry of the page (layout) — meaning that the position of other elements on the page will have to be recalculated, or that painting operations will be involved. Both layout and painting tasks are very expensive for browsers to process, especially if you have several elements on your page. As a consequence, you’ll see animation performance improve significantly if you avoid animating CSS properties that trigger layout or paint operations and stick to properties like transforms and opacity, because modern browsers do an excellent job of optimizing them.
On CSS Triggers you’ll find an up-to-date list of CSS properties with information about the work they trigger in each modern browser, both on the first change and on subsequent changes.

Changing CSS properties that only trigger composite operations is both an easy and effective step you can take to optimize your web animations for performance.
#2 Promote Elements You Want to Animate to Their Own Layer (with Caution)
If the element you want to animate is on its own compositor layer, some modern browsers leverage hardware acceleration by offloading the work to the GPU. If used judiciously, this move can have a positive effect on the performance of your animations.
To have the element on its own layer, you need to promote it. One way you can do so is by using the CSS will-change property. This property allows developers to warn the browser about some changes they want to make on an element, so that the browser can make the required optimizations ahead of time.
However, it’s not advised that you promote too many elements on their own layer or that you do so with exaggeration. In fact, every layer the browser creates requires memory and management, which can be expensive.
You can learn the details of how to use will-change, its benefits and downsides, in An Introduction to the CSS will-change Property by Nick Salloum.
#3 Replace setTimeOut/setInterval with requestAnimationFrame
JavaScript animations have commonly been coded using either setInterval() or setTimeout().
The code would look something like this:
var timer;
function animateElement() {
timer = setInterval( function() {
// animation code goes here
} , 2000 );
}

// To stop the animation, use clearInterval
function stopAnimation() {
clearInterval(timer);
}

Although this works, the risk of jank is high, because the callback function runs at some point in the frame, perhaps at the very end, which can result in one or more frames being missed. Today, you can use a native JavaScript method which is tailored for smooth web animation (DOM animation, canvas, etc.), called requestAnimationFrame().
requestAnimationFrame() executes your animation code at the most appropriate time for the browser, usually at the beginning of the frame.
Your code could look something like this:
function makeChange( time ) {
// Animation logic here

// Call requestAnimationFrame recursively inside the callback function
requestAnimationFrame( makeChange ):
}

// Call requestAnimationFrame again outside the callback function
requestAnimationFrame( makeChange );

Performance with requestAnimationFrame by Tim Evko here on SitePoint offers a great video introduction to coding with requestAnimationFrame().
The post 7 Performance Tips for Jank-free JavaScript Animations appeared first on SitePoint.

Link: https://www.sitepoint.com/7-performance-tips-jank-free-javascript-animations/

What’s New in ES2018

In this article, I’ll cover the new features of JavaScript introduced via ES2018 (ES9), with examples of what they’re for and how to use them.
JavaScript (ECMAScript) is an ever-evolving standard implemented by many vendors across multiple platforms. ES6 (ECMAScript 2015) was a large release which took six years to finalize. A new annual release process has been formulated to streamline the process and add features quicker. ES9 (ES2018) is the latest iteration at the time of writing.
Technical Committee 39 (TC39) consists of parties including browser vendors who meet to push JavaScript proposals along a strict progression path:
Stage 0: strawman –
The initial submission of ideas.
Stage 1: proposal –
A formal proposal document championed by at least once member of TC39 which includes API examples.
Stage 2: draft –
An initial version of the feature specification with two experimental implementations.
Stage 3: candidate –
The proposal specification is reviewed and feedback is gathered from vendors.
Stage 4: finished –
The proposal is ready for inclusion in ECMAScript but may take longer to ship in browsers and Node.js.
ES2016
ES2016 proved the standardization process by adding just two small features:

The array includes() method, which returns true or false when a value is contained in an array, and
The a ** b exponentiation operator, which is identical to Math.pow(a, b).

ES2017
ES2017 provided a larger range of new features:

Async functions for a clearer Promise syntax
Object.values() to extract an array of values from an object containing name–value pairs
Object.entries(), which returns an array of sub-arrays containing the names and values in an object
Object.getOwnPropertyDescriptors() to return an object defining property descriptors for own properties of another object (.value, .writable, .get, .set, .configurable, .enumerable)
padStart() and padEnd(), both elements of string padding
trailing commas on object definitions, array declarations and function parameter lists
SharedArrayBuffer and Atomics for reading from and writing to shared memory locations (disabled in response to the Spectre vulnerability).

Refer to What’s New in ES2017 for more information.
ES2018
ECMAScript 2018 (or ES9 if you prefer the old notation) is now available. The following features have reached stage 4, although working implementations will be patchy across browsers and runtimes at the time of writing.
Asynchronous Iteration
At some point in your async/await journey, you’ll attempt to call an asynchronous function inside a synchronous loop. For example:
async function process(array) {
for (let i of array) {
await doSomething(i);
}
}

It won’t work. Neither will this:
async function process(array) {
array.forEach(async i => {
await doSomething(i);
});
}

The loops themselves remain synchronous and will always complete before their inner asynchronous operations.
ES2018 introduces asynchronous iterators, which are just like regular iterators except the next() method returns a Promise. Therefore, the await keyword can be used with for … of loops to run asynchronous operations in series. For example:
async function process(array) {
for await (let i of array) {
doSomething(i);
}
}

The post What’s New in ES2018 appeared first on SitePoint.

Link: https://www.sitepoint.com/es2018-whats-new/

JSON Schema Validation & Expressive Query Syntax in MongoDB 3.6

This article was originally published on MongoDB. Thank you for supporting the partners who make SitePoint possible.
One of MongoDB’s key strengths has always been developer empowerment: by relying on a flexible schema architecture, MongoDB makes it easier and faster for applications to move through the development stages from proof-of-concept to production and iterate over update cycles as requirements evolve.
However, as applications mature and scale, they tend to reach a stable stage where frequent schema changes are no longer critical or must be rolled out in a more controlled fashion, to prevent undesirable data from being inserted into the database. These controls are especially important when multiple applications write into the same database, or when analytics processes rely on predefined data structures to be accurate and useful.
MongoDB 3.2 was the first release to introduce Document Validation, one of the features that developers and DBAs who are accustomed to relational databases kept demanding. As MongoDB’s CTO, Eliot Horowitz, highlighted in Document Validation and What Dynamic Schemas Means:

Along with the rest of the 3.2 “schema when you need it" features, document validation gives MongoDB a new, powerful way to keep data clean. These are definitely not the final set of tools we will provide, but is rather an important step in how MongoDB handles schema.

Announcing JSON Schema Validation Support
Building upon MongoDB 3.2’s Document Validation functionality, MongoDB 3.6 introduces a more powerful way of enforcing schemas in the database, with its support of JSON Schema Validation, a specification which is part of IETF’s emerging JSON Schema standard.
JSON Schema Validation extends Document Validation in many different ways, including the ability to enforce schemas inside arrays and prevent unapproved attributes from being added. These are the new features we will focus on in this blog post, as well as the ability to build business validation rules.
Starting with MongoDB 3.6, JSON Schema is the recommended way of enforcing Schema Validation. The next section highlights the features and benefits of using JSON Schema Validation.
Switching from Document Validation to JSON Schema Validation
We will start by creating an orders collection (based on an example we published in the Document Validation tutorial blog post):
db.createCollection("orders", {
validator: {
item: { $type: "string" },
price: { $type: "decimal" }
}
});

With this document validation configuration, we not only make sure that both the item and price attributes are present in any order document, but also that item is a string and price a decimal (which is the recommended type for all currency and percentage values). Therefore, the following element cannot be inserted (because of the "rogue" price attribute):
db.orders.insert({
"_id": 6666,
"item": "jkl",
"price": "rogue",
"quantity": 1 });

However, the following document could be inserted (notice the misspelled "pryce" attribute):
db.orders.insert({
"_id": 6667,
"item": "jkl",
"price": NumberDecimal("15.5"),
"pryce": "rogue" });

Prior to MongoDB 3.6, you could not prevent the addition of misspelled or unauthorized attributes. Let’s see how JSON Schema Validation can prevent this behavior. To do so, we will use a new operator, $jsonSchema:
db.runCommand({
collMod: "orders",
validator: {
$jsonSchema: {
bsonType: "object",
required: ["item", "price"],
properties: {

item: {
bsonType: "string"
},
price: {
bsonType: "decimal"
}
}
}
}
});

The JSON Schema above is the exact equivalent of the document validation rule we previously set above on the orders collection. Let’s check that our schema has indeed been updated to use the new $jsonSchema operator by using the db.getCollectionInfos() method in the Mongo shell:
db.getCollectionInfos({name:"orders"})

This command prints out a wealth of information about the orders collection. For the sake of readability, below is the section that includes the JSON Schema:

"options" : {
"validator" : {
"$jsonSchema" : {
"bsonType" : "object",
"required" : [
"item",
"price"
],
"properties" : {
"item" : {
"bsonType" : "string"
},
"price" : {
"bsonType" : "decimal"
}
}
}
},
"validationLevel" : "strict",
"validationAction" : "error"
}

Now, let’s enrich our JSON schema a bit to make better use of its powerful features:
db.runCommand({
collMod: "orders",
validator: {
$jsonSchema: {
bsonType: "object",
additionalProperties: false</strong>,
required: ["item", "price"],
properties: {
<strong>_id: {}</strong>,
item: {
bsonType: "string",
description: "’item’ must be a string and is required"
},
price: {
bsonType: "decimal",
description: "’price’ must be a decimal and is required"
},
quantity: {
<strong>bsonType: ["int", "long"]</strong>,
minimum: 1,
maximum: 100,
exclusiveMaximum: true,
description:
"’quantity’ must be short or long integer between 1 and 99"
}
}
}
}
});

Let’s go through the additions we made to our schema:

First, note the use of the additionalProperties:false attribute: it prevents us from adding any attribute other than those mentioned in the properties section. For example, it will no longer be possible to insert data containing a misspelled pryce attribute. As a result, the use of additionalProperties:false at the root level of the document also makes the declaration of the _id property mandatory: whether our insert code explicitly sets it or not, it is a field MongoDB requires and would automatically create, if not present. Thus, we must include it explicitly in the properties section of our schema.
Second, we have chosen to declare the quantity attribute as either a short or long integer between 1 and 99 (using the minimum, maximum and exclusiveMaximum attributes). Of course, because our schema only allows integers lower than 100, we could simply have set the bsonType property to int. But adding long as a valid type makes application code more flexible, especially if there might be plans to lift the maximum restriction.
Finally, note that the description attribute (present in the item, price, and quantity attribute declarations) is entirely optional and has no effect on the schema aside from documenting the schema for the reader.

With the schema above, the following documents can be inserted into our orders collection:
db.orders.insert({
"item": "jkl",
"price": NumberDecimal(15.50),
"quantity": NumberInt(99)
});

db.orders.insert({
"item": "jklm",
"price": NumberDecimal(15.50),
"quantity": NumberLong(99)
});

However, the following documents are no longer considered valid:
db.orders.insert({
"item": "jkl",
"price": NumberDecimal(15.50),
<strong>"quantity": NumberInt(100)</strong>
});
db.orders.insert({
"item": "jkl",
"price": NumberDecimal(15.50),
<strong>"quantity": "98"</strong>
});
db.orders.insert({
"item": "jkl",
<strong>"pryce": NumberDecimal(15.50),</strong>
"quantity": NumberInt(99)
});

You probably noticed that our orders above are seemingly odd: they only contain one single item. More realistically, an order consists of multiple items and a possible JSON structure might be as follows:
{
_id: 10000,
total: NumberDecimal(141),
VAT: 0.20,
totalWithVAT: NumberDecimal(169),
lineitems: [
{
sku: "MDBTS001",
name: "MongoDB Stitch T-shirt",
quantity: NumberInt(10),
unit_price:NumberDecimal(9)
},
{
sku: "MDBTS002",
quantity: NumberInt(5),
unit_price: NumberDecimal(10)
}
]
}

With MongoDB 3.6, we can now control the structure of the lineitems array, for instance with the following JSON Schema:
The post JSON Schema Validation & Expressive Query Syntax in MongoDB 3.6 appeared first on SitePoint.

Link: https://www.sitepoint.com/json-schema-validation-expressive-query-syntax-in-mongodb-3-6/

How to Add jQuery to WordPress

If you search online for how to add jQuery scripts to WordPress, you will get a plethora of results. But, if you are not a programmer or not that familiar with WordPress, you may find the online resources a bit hard to understand. This is where we come in. In today’s article, we will show how to add jQuery Scripts to WordPress. However, before we start, let’s take a look at jQuery and WordPress.
jQuery
The popularity of jQuery is phenomenal. And, why not? It gives developers an extra edge when developing their application for the web. It is also one of the most popular libraries for JavaScript. It is a smaller library and also cuts down the load time. In short, to speed up WordPress, you need to use jQuery.

Link: https://dzone.com/articles/how-to-add-jquery-scripts-to-wordpress?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Understanding the Almighty Reducer

I was reently mentoring someone who had trouble with the .reduce() method in JavaScript. Namely, how you get from this:
const nums = [1, 2, 3]
let value = 0
for (let i = 0; i < nums.length; i++) { value += nums[i] } ...to this: const nums = [1, 2, 3] const value = nums.reduce((ac, next) => ac + next, 0)
They are functionally equivalent and they both sum up all the numbers in the array, but there is …
The post Understanding the Almighty Reducer appeared first on CSS-Tricks.

Link: https://css-tricks.com/understanding-the-almighty-reducer/

Interactive Data Visualization with Modern JavaScript and D3

In this article, I want to take you through an example project that I built recently — a totally original type of visualization using the D3 library, which showcases how each of these components add up to make D3 a great library to learn.
D3 stands for Data Driven Documents. It’s a JavaScript library that can be used to make all sorts of wonderful data visualizations and charts.
If you’ve ever seen any of the fabulous interactive stories from the New York Times, you’ll already have seen D3 in action. You can also see some cool examples of great projects that have been built with D3 here.
The learning curve is pretty steep for getting started with the library, since D3 has a few special quirks that you probably won’t have seen before. However, if you can get past the first phase of learning enough D3 to be dangerous, then you’ll soon be able to build some really cool stuff for yourself.
There are three main factors that really make D3 stand out from any other libraries out there:

Flexibility. D3 lets you take any kind of data, and directly associate it with shapes in the browser window. This data can be absolutely anything, allowing for a huge array of interesting use cases to create completely original visualizations.
Elegance. It’s easy to add interactive elements with smooth transitions between updates. The library is written beautifully, and once you get the hang of the syntax, it’s easy to keep your code clean and tidy.
Community. There’s a vast ecosystem of fantastic developers using D3 already, who readily share their code online. You can use sites like bl.ocks.org and blockbuilder.org to quickly find pre-written code by others, and copy these snippets directly into your own projects.

The Project
As an economics major in college, I had always been interested in income inequality. I took a few classes on the subject, and it struck me as something that wasn’t fully understood to the degree that it should be.
I started exploring income inequality using Google’s Public Data Explorer …

When you adjust for inflation, household income has stayed pretty much constant for the bottom 40% of society, although per-worker productivity has been skyrocketing. It’s only really been the top 20% that have reaped more of the benefits (and within that bracket, the difference is even more shocking if you look at the top 5%).
Here was a message that I wanted to get across in a convincing way, which provided a perfect opportunity to use some D3.js, so I started sketching up a few ideas.
Sketching
Because we’re working with D3, I could more or less just start sketching out absolutely anything that I could think of. Making a simple line graph, bar chart, or bubble chart would have been easy enough, but I wanted to make something different.
I find that the most common analogy that people tended to use as a counterargument to concerns about inequality is that “if the pie gets bigger, then there’s more to go around”. The intuition is that, if the total share of GDP manages to increase by a large extent, then even if some people are getting a thinner slice of pie, then they’ll still be better off. However, as we can see, it’s totally possible for the pie to get bigger and for people to be getting less of it overall.
My first idea for visualizing this data looked something like this:

The idea would be that we’d have this pulsating pie chart, with each slice representing a fifth of the US income distribution. The area of each pie slice would relate to how much income that segment of the population is taking in, and the total area of the chart would represent its total GDP.
However, I soon came across a bit of a problem. It turns out that the human brain is exceptionally poor at distinguishing between the size of different areas. When I mapped this out more concretely, the message wasn’t anywhere near as obvious as it should have been:

Here, it actually looks like the poorest Americans are getting richer over time, which confirms what seems to be intuitively true. I thought about this problem some more, and my solution involved keeping the angle of each arc constant, with the radius of each arc changing dynamically.

Here’s how this ended up looking in practice:

I want to point out that this image still tends to understate the effect here. The effect would have been more obvious if we used a simple bar chart:

However, I was committed to making a unique visualization, and I wanted to hammer home this message that the pie can get bigger, whilst a share of it can get smaller. Now that I had my idea, it was time to build it with D3.
Borrowing Code
So, now that I know what I’m going to build, it’s time to get into the real meat of this project, and start writing some code.
You might think that I’d start by writing my first few lines of code from scratch, but you’d be wrong. This is D3, and since we’re working with D3, we can always find some pre-written code from the community to start us off.
We’re creating something completely new, but it has a lot in common with a regular pie chart, so I took a quick look on bl.ocks.org, and I decided to go with this classic implementation by Mike Bostock, one of the creators of D3. This file has probably been copied thousands of times already, and the guy who wrote it is a real wizard with JavaScript, so we can be sure that we’re starting with a nice block of code already.
This file is written in D3 V3, which is now two versions out of date, since version 5 was finally released last month. A big change in D3 V4 was that the library switched to using a flat namespace, so that scale functions like d3.scale.ordinal() are written like d3.scaleOrdinal() instead. In version 5, the biggest change was that data loading functions are now structured as Promises, which makes it easier to handle multiple datasets at once.
To avoid confusion, I’ve already gone through the trouble of creating an updated V5 version of this code, which I’ve saved on blockbuilder.org. I’ve also converted the syntax to fit with ES6 conventions, such as switching ES5 anonymous functions to arrow functions.
Here’s what we’re starting off with already:

I then copied these files into my working directory, and made sure that I could replicate everything on my own machine. If you want to follow along with this tutorial yourself, then you can clone this project from our GitHub repo. You can start with the code in the file starter.html. Please note that you will need a server (such as this one) to run this code, as under the hood it relies on the Fetch API to retrieve the data.
Let me give you a quick rundown of how this code is working.
The post Interactive Data Visualization with Modern JavaScript and D3 appeared first on SitePoint.

Link: https://www.sitepoint.com/interactive-data-visualization-javascript-d3/

Use Parcel to Bundle a Hyperapp App & Deploy to GitHub Pages

In a previous post we met Hyperapp, a tiny library that can be used to build dynamic, single-page web apps in a similar way to React or Vue.
In this post we’re going to turn things up a notch. We’re going to create the app locally (we were working on CodePen previously), learn how to bundle it using Parcel (a module bundler similar to webpack or Rollup) and deploy it to the web using GitHub Pages.
Don’t worry if you didn’t complete the project from the first post. All the code is provided here (although I won’t go into detail explaining what it does) and the principles outlined can be applied to most other JavaScript projects.
If you’d like to see what we’ll be ending up with, you can view the finished project here, or download the code from our GitHub repo.
Basic Setup
In order to follow along, you’ll need to have both Node.js and npm installed (they come packaged together). I’d recommend using a version manager such as nvm to manage your Node installation (here’s how), and if you’d like some help getting to grips with npm, then check out our beginner-friendly npm tutorial.
We’ll be using the terminal commands to create files and folders, but feel free to do it by just pointing and clicking instead if that’s your thing.
To get started, create a new folder called hyperlist:
mkdir hyperlist

Now change to that directory and initialize a new project using npm:
cd hyperlist/
npm init

This will prompt you to answer some questions about the app. It’s fine to just press enter to accept the default for any of these, but feel free to add in your name as the author and to add a description of the app.
This should create a file called package.json inside the hyperlist directory that looks similar to the following:
{
“name": "hyperlist",
"version": "1.0.0",
"description": "A To-do List made with Hyperapp",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "DAZ",
"license": "MIT"
}

Now we need to install the Hyperapp library. This is done using npm along with the –save flag, which means that the package.json file will be updated to include it as a dependency:
npm install –save hyperapp

This might give some warnings about not having a repository field. Don’t worry about this, as we’ll be fixing it later. It should update the package.json file to include the following entry (there might be a slight difference in version number):
"dependencies": {
"hyperapp": "^1.2.5"
}

It will also create a directory called node_modules where all the Hyperapp files are stored, as well as a file called package-lock.json. This is used to keep track of the dependency tree for all the packages that have been installed using npm.
Now we’re ready to start creating the app!
Folder Structure
It’s a common convention to put all of your source code into a folder called src. Within this folder, we’re going to put all of our JavaScript files into a directory called js. Let’s create both of those now:
mkdir -p src/js

In the previous post we learned that apps are built in Hyperapp using three main parts: state, actions and view. In the interests of code organization, we’re going to place the code for each part in a separate file, so we need to create these files inside the js directory:
cd src/js
touch state.js actions.js view.js

Don’t worry that they’re all empty. We’ll add the code soon!
Last of all, we’ll go back into the src directory and create our “entry point” files. These are the files that will link to all the others. The first is index.html, which will contain some basic HTML, and the other is index.js, which will link to all our other JavaScript files and also our SCSS files:
cd ..
touch index.html index.js

Now that our folder structure is all in place, we can go ahead and start adding some code and wiring all the files together. Onward!
Some Basic HTML
We’ll start by adding some basic HTML code to the index.html file. Hyperapp takes care of creating the HTML and can render it directly into the tag. This means that we only have to set up the meta information contained in the <head> tag. Except for the <title> tag’s value, you can get away with using the same index.html file for every project. Open up index.html in your favorite text editor and add the following code:
<!doctype html>
<html lang=’en’>
<head>
<meta charset=’utf-8’>
<meta name=’viewport’ content=’width=device-width, initial-scale=1’>
<title>HyperList</title>
</head>
<body>
<script src=’index.js’></script>
</body>
</html>

Now it’s time to add some JavaScript code!
ES6 Modules
Native JavaScript modules were introduced in ES6 (aka ES2015). Unfortunately, browsers have been slow to adopt the use of ES6 modules natively, although things are now starting to improve. Luckily, we can still use them to organize our code, and Parcel will sort out piecing them all together.
Let’s start by adding the code for the initial state inside the state.js file:
const state = {
items: [],
input: ”,
placeholder: ‘Make a list..’
};

export default state;

This is the same as the object we used in the previous article, but with the export declaration at the end. This will make the object available to any other file that imports it. By making it the default export, we don’t have to explicitly name it when we import it later.
Next we’ll add the actions to actions.js:
const actions = {
add: () => state => ({
input: ”,
items: state.items.concat({
value: state.input,
completed: false,
id: Date.now()
})
}),
input: ({ value }) => ({ input: value }),
toggle: id => state => ({
items: state.items.map(item => (
id === item.id ? Object.assign({}, item, { completed: !item.completed }) : item
))
}),
destroy: id => state => ({
items: state.items.filter(item => item.id !== id)
}),
clearAllCompleted: ({ items }) => ({
items: items.filter(item => !item.completed)
})
};

export default actions;

Again, this is the same as the object we used in the previous article, with the addition of the export declaration at the end.
Last of all we’ll add the view code to view.js:
import { h } from ‘hyperapp’

const AddItem = ({ add, input, value, placeholder }) => (
<div class=’flex’>
<input
type="text"
onkeyup={e => (e.keyCode === 13 ? add() : null)}
oninput={e => input({ value: e.target.value })}
value={value}
placeholder={placeholder}
/>
<button onclick={add}>+</button>
</div>
);

const ListItem = ({ value, id, completed, toggle, destroy }) => (
<li class={completed && "completed"} id={id} key={id} onclick={e => toggle(id)}>
{value} <button onclick={ () => destroy(id) }>x</button>
</li>
);

const view = (state, actions) => (
<div>
<h1><strong>Hyper</strong>List</h1>
<AddItem
add={actions.add}
input={actions.input}
value={state.input}
placeholder={state.placeholder}
/>
<ul id=’list’>
{state.items.map(item => (
<ListItem
id={item.id}
value={item.value}
completed={item.completed}
toggle={actions.toggle}
destroy={actions.destroy}
/>
))}
</ul>
<button onclick={() => actions.clearAllCompleted({ items: state.items }) }>
Clear completed items
</button>
</div>s
);

export default view;

First of all, this file uses the import declaration to import the h module from the Hyperapp library that we installed using npm earlier. This is the function that Hyperapp uses to create the Virtual DOM nodes that make up the view.
This file contains two components: AddItem and ListItem. These are just functions that return JSX code and are used to abstract different parts of the view into separate building blocks. If you find that you’re using a large number of components, it might be worth moving them into a separate components.js file and then importing them into the view.js file.
Notice that only the view function is exported at the end of the file. This means that only this function can be imported by other files, rather than the separate components.
Now we’ve added all our JavaScript code, we just need to piece it all together in the index.js file. This is done using the import directive. Add the following code to index.js:
import { app } from ‘hyperapp’

import state from ‘./js/state.js’
import actions from ‘./js/actions.js’
import view from ‘./js/view.js’

const main = app(state, actions, view, document.body);

This imports the app function from the Hyperapp library, then imports the three JavaScript files that we just created. The object or function that was exported from each of these files is assigned to the variables state,actions and view respectively, so they can be referenced in this file.
The last line of code calls the app function, which starts the app running. It uses each of the variables created from our imported files as the first three arguments. The last argument is the HTML element where the app will be rendered — which, by convention, is document.body.
The post Use Parcel to Bundle a Hyperapp App & Deploy to GitHub Pages appeared first on SitePoint.

Link: https://www.sitepoint.com/parcel-hyperapp-github-pages/