How Blockchain Can Help Re-invent Healthcare

This article was originally published on Blockchain Review. Thank you for supporting the partners who make SitePoint possible.

Ever wondered about blockchain applications in healthcare? This post will give you a well-rounded introduction to the transformative potential of blockchain and set out the complex interrelated issues that stand in the way of change.

As an important step in becoming a doctor, graduating medical school students swear to some form of the Hippocratic Oath.

One of the vows within that oath is “first, do no harm” or “primum nonnocere.”

While most medical professionals live up to this promise on a daily basis, the same cannot be said for the healthcare systems within which they operate.

Despite significant leaps in the medical field, from devices and wearables to genome sequencing and regenerative medicine, individual improvements have not created the fundamental transformation that national healthcare systems require. [1]

Health management and administrative systems remain relatively untouched by technology and regulatory reform and stand ill-equipped to serve the current and future needs of their target populations.

Demographic Stresses

The world is getting older, especially in developed countries, which is placing a significant strain on healthcare systems. According to a 2015 report by the United Nations Department of Economic & Social Affairs [2]:

  • Between 2015 and 2030, the group of over-60s will grow by 56%
  • In 2015, one in eight people worldwide were aged 60 or over. By 2030, seniors are projected to account for one in six people globally.
  • The aging process is most advanced in Europe and Northern America, where more than one in five people are aged 60 or over as of 2015.
  • By 2030, the elderly are expected to account for more than 25% of the populations in Europe and Northern America, 20% in Oceania, 17% in Asia and Latin America and the Caribbean, and 6% in Africa.

In the developing world, particularly Sub-Saharan Africa and Asia, future challenges in healthcare will stem from population increases and economic factors rather than aging.

High population growth coupled with a trickle down of innovations is driving a growing middle-class.

With growth coming almost exclusively from emerging nations, the world’s middle class is expected to expand by another three billion over the next two decades. [3]

Delivering efficient, sustainable and affordable healthcare to the world’s aging population and emerging middle class will become more difficult without profound and substantive changes to national healthcare systems.

While problems are complex, systemic and by no means easily fixed, the vast majority of constraints experienced by healthcare systems can be traced to a single, yet highly corrosive root cause.

Myopic, Outdated & Restrictive Compliance Regulations

The costs, risks and societal sensitivities surrounding healthcare are profound. Due to the sensitive and central role healthcare plays in society, fearful government officials have been scared to make the deep regulatory changes required to reform healthcare.

Officials know they will be punished by the public and politicians more for underregulating — approving a harmful drug, say — than for tightening the approval process, even if doing so delays a useful innovation. – Regina E. Herzlinger

Remember the Obamacare Saga?

Sure you do. It’s still going on today, many years later.

The divisive public and congressional debates. The multitude of vested interests and the tangle of regulations. It’s not hard to understand why the implementation of far-reaching regulatory reforms have been unattainable and generally avoided by politicians.

Data sharing and privacy laws have resulted in gross inefficiencies, industry-wide fragmentation, and the prevention of real innovation in healthcare. HIPAA, for example, the US Health Insurance Portability and Accountability Act, designed to protect health information, imposes strict rules on healthcare providers.

Despite the Act’s noble intention to keep patient data secure and private, it remains a large impediment to efficient patient care mainly because of the difficulties in accessing patient information and restrictions on electronic communications.

Many physicians may be reluctant to embrace EHRs because of malpractice concerns. They may believe that they are better protected against malpractice lawsuits by the handwritten chart system. Furthermore, HIPAA has raised many new issues about data handling. There are also international legal issues about sharing health information. Many unresolved legal concerns surround legal liability in the event of medical errors that are byproducts of health analysis software or EHR data encoding. – A Robust Health Data Infrastructure

Government regulations like HIPAA have caused a host of flow-on problems.

Healthcare management systems designed to adhere to such restrictive regulations are antiquated and fragmented. Bloated systems that run on paper and siloed record-keeping practices have created healthcare management systems that are inefficient, fragmented, isolated and opaque.

The shift towards electronic health records (EHR) has done little to improve the splintered nature of healthcare. A severe lack of interoperability within organizations and at the inter-organizational level means that coordination remains minimal. EHR’s are fragmented across hospitals, private practices, labs, pharmacies and many other industry players. [6]

On average, Americans visit 16 different doctors in their lifetime. While both the HITECH and the Affordable Care Act’s now enable and in some cases mandate that data from your doctor’s visits be stored digitally, medical records and results from different facilities and physicians are often stored in incompatible databases. – Brian Forde

Real-world Implications for Patient Health

The inability to exchange and make use of electronic health records serves as a major impediment to the development of a robust data infrastructure. [8] As you can imagine, when hospitals, clinics, insurers, governments and doctor’s offices are unable to share information, this has negative outcomes for patient health.

Einer Elhauge, Founding Director of the Petrie-Flom Center for Health Law Policy, Biotechnology & Bioethics at Harvard writes:

Just as too many cooks can spoil the broth, too many decision makers can spoil health care. Individual decision makers responsible for only one fragment of a relevant set of health care decisions may fail to understand the full picture, may lack the power to take all the appropriate actions given what they know, or may even have affirmative incentives to shift costs onto others. All these forms of fragmentation can lead to bad health care decisions. [9]

Take a look at this example scenario.

A patient seeks medical advice to find a remedy for his constant fatigue and muscle aches.

He/she visits a number of doctors, each a specialist in their respective areas and even visits the hospital on one occasion.

He/she receives a battery of tests from each doctor as well as the hospital and is prescribed a range of drugs.

The patient’s condition proceeds to deteriorate, so he/she decides to visit a new doctor who continues a new testing and treatment regime. Throughout the process, the medical professionals treating the patient have little communication and share minimal information on the patient’s medical history.

Even though the doctors who treated the patient in this fictitious, albeit credible real-world example may have followed the right medical procedures to treat the problems they were trained to handle, the fragmented nature of the healthcare system resulted in no co-ordination and ultimately substandard patient care.

The incapacity to share vital information led doctors to be unable to see the patient’s bigger picture which could have shed further light on the health condition. Information sharing between doctors would likely have resulted in better treatment and a reduction in patient, doctor and insurer costs that accompanied needless treatments.

Information sharing between doctors would likely have resulted in better treatment and a reduction in patient, doctor and insurer costs that accompanied needless treatments.

The corrosive impact of government regulations doesn’t end here.

Fragmented, siloed record-keeping practices and systems that lack basic levels of interoperability are responsible for other major problems in healthcare.

There is now a severe lack of advanced data available for clinical and scientific research and economic, behavioral and infrastructure purposes. With little meaningful data, it’s difficult for governments and the healthcare industry to see the bigger picture and make informed decisions to improve the quality of patient care.

There is also insufficient insurable data for the most at-risk and underserved citizens and the tracking of population health trends. [10]

Perhaps the most destructive impact of fragmentation and the inability to share information is that it has caused deep inefficiencies. Healthcare costs, in the United States, for example, have spiraled out of control.

According to the CDC, health expenditures as a percentage of GDP have risen some 4.5% since the year 2000. [11]

Health expenditures % of GDP:

  • 2000: 13.3%
  • 2009: 17.3%
  • 2014: 17.4%
  • 2015: 17.8%

High costs have contributed to insurance companies’ reluctance to insure the population and provide an adequate range of services.

Many national healthcare systems are so inefficient they have become unable to deliver any form of care to the most vulnerable and at-risk members of society. Many are even failing to deliver adequate care to those that can afford it.

As demographic shifts take place, these inefficiencies will worsen. The reinvention of the national healthcare systems is now required.

Blockchain technology is a key tool to achieve healthcare objectives for developing and “re-developing” nations.

One of the fundamental goals that governments and industry seek to achieve is to provide improved quality of healthcare at lower healthcare costs. [12] Making this goal a reality will require governments and industry to play different, but equally important roles.

Governments: must lead change through regulatory reforms that incorporate technological advances and foster an environment designed around competitive collaboration and innovation amongst insurers, healthcare providers, and regulators. It’s equally imperative for governments to participate in technological innovation programs and R&D to support the development of a robust health data infrastructure.

It’s equally imperative for governments to participate in technological innovation programs and R&D to support the development of a robust health data infrastructure.

Industry: Transforming the

Continue reading %How Blockchain Can Help Re-invent Healthcare%


Source: Sitepoint

Monthly Web Development Update 2/2018: The Grown-Up Web, Branding Details, And Browser Fast Forward

Every profession is a wide field where many people find their very own, custom niches. So are design and web development today. I started building my first website with framesets and HTML4.0, images and a super limited set of CSS, and — oh so fancy — GIFs and inline JavaScript (remember the onclick=”” attribute?) about one and a half decades ago. It took me four days to learn the initial, necessary skills for that.
Source: Smashing Magazine

Creating a Blogging App Using Angular & MongoDB: Edit Post

In the previous part of this tutorial series you learnt how to create the add post component to add new blog posts. You learnt how to create the REST API endpoint to add a new post to the MongoDB database.

In this part of the tutorial series, you’ll learn how to implement the functionality to edit an existing blog post from the blog post list.

Getting Started

Let’s get started by cloning the source code from the last part of the tutorial series.

Navigate to the project directory and install the required dependencies.

Once you have the dependencies installed, restart the client and server application.

Point your browser to http://localhost:4200 and you will have the application running.

Adding the Edit Post View

In the ShowPostComponent, you’ll add two icons for editing and deleting the blog post. You’ll make use of Font Awesome to display the edit and delete icons.

Download and include the font awesome folder in the assets folder.

Font Awesome In Assets Folder

In the src/app/index.html page, include a reference to the font awesome CSS style.

Now modify the show-post/show-post.component.html file to include the HTML for the edit and delete icons.

Here is how the show-post.component.html file looks:

Save the above changes and restart the client application. Log into the application and you will be able to view the edit and delete icons corresponding to each listed blog post.

Angular Blog App - Edit And Delete Icon

Populating the Edit Detail in a Popup

When the user clicks the edit icon corresponding to any blog post, you need to populate the blog post details in the add post popup for updating.

Add a click method to the edit icon.

Inside the CommonService, you need to define an observable to keep track of when the edit button is clicked. Define the observable as shown:

Define another variable to keep track of the post to be edited.

Whenever the edit button is clicked, you’ll keep the post to be edited in the CommonService and trigger the observable to notify of post edit. Define two methods to set the post to be edited and to notify post edit.

Inside the click method, you’ll call the setPostToEdit method from CommonService. Here is how the editPost method looks:

You will have the post detail in the common service when the user clicks the edit button. To show the add post popup for updating, you need to click the add post button programmatically.

Inside the home/home.component.html file, add a # identifier to the add post button.

Import ViewChild and ElementRef inside the home.component.ts file.

Define a reference to the add button inside the home.component.ts file.

Inside the HomeComponent constructor, subscribe to the postEdit_Observable from CommonService. On calling the postEdit_Observable subscription callback, invoke the add button click to show the popup. Here is how the home.component.ts file looks:

You need to subscribe to postEdit_Observable in the add-post.component.ts file to set the post to be edited on the post variable. Here is how the ngOnInit method in add-post.component.ts looks:

Save the above changes and restart the client server. Log into the application and click on the edit button against any blog post. You will be able to view the post details populated in the add post popup.

Angular Blog App - Update Post

Creating the Update Post REST API

Inside server/app.js, let’s define another REST API endpoint to update post details based on the ID of the post. Here is how it looks:

Let’s first use Mongoose to connect to the MongoDB database.

Once the connection is established, you make use of the update method on the Post model.

You’ll be updating the post based on the ID of the post passed. As seen in the above code, you have specified the post _id to be updated. In the second option, you have specified the fields to be updated, which are title and description.

Once the details get updated, you’ll return the status along with the number of rows affected during the update. Here is how the REST API endpoint for the post update looks:

Making the REST API Call to Update

The ID returned for each post from the MongoDB is _id, so you need to modify the id of our model src/app/models/post.model.ts. Here is how it looks:

When you click the add post button, the method called will be addPost. Inside the addPost method in add-post.component.ts, you’ll check if the post object has an _id. If an _id is present then you need to call the update method from the service, else you’ll call the add post service method.

Create a method called updatePost inside the add-post.service.ts file.

Here is how the modified addPost method from the add-post.component.ts file looks:

Save the above changes and restart both Angular and Node server. Log into the application and try editing a post. You will have a popup displayed to edit the details on clicking the edit button. Click the add button and the details will be updated and displayed in the blog post list.

Wrapping It Up

In this tutorial, you implemented the functionality to update the existing blog post details. You created the back-end REST API endpoint to update the blog post details based on the blog post ID. You made use of the Mongoose client to update the details of the blog post in the MongoDB database.

In the next part, you’ll implement the delete post and log out functionality.

How was your experience so far? Do let us know your thoughts, suggestions, or any corrections in the comments below.

Source code from this tutorial is available on GitHub


Source: Nettuts Web Development

Designing For User Interfaces: Icons As Visual Elements For Screen Design

(This is a sponsored article.) Icons are everywhere. They have been around for a long time, and it’s difficult to imagine a world without icons or symbols today. Only designers will know how much effort and time is needed to not only make them helpful but also simple and expressive.
What makes icons particularly special is perhaps the fact that their meaning can be understood without having to add any text or further details.
Source: Smashing Magazine

Animating Bootstrap Carousels with GSAP’s Animation Library

In a previous post, I covered the process of converting a Bootstrap carousel into a full-screen carousel with a random initial image. In this article, I’ll build on that and cover the art of animating Bootstrap carousels, drawing on the assistance of GSAP (GreenSock Animation Platform), a popular JavaScript library.

Animating Bootstrap carousels: a carousel horse wearing the GSAP cape

Before going any further, let’s look at what we’ll be building.

Building the Carousel

Be sure to include Bootstrap and jQuery (Bootstrap’s JavaScript components require it) in your page — for example, from a CDN:

<!DOCTYPE HTML>
<html>
  <head>
    <meta charset="utf-8">
    <title>Using GSAP to Animate Bootstrap Carousels</title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  </head>
  <body>
    ...
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  </body>
</html>

The basic structure of our carousel looks like this:

<div id="mycarousel" class="carousel slide" data-ride="carousel">
  <ol class="carousel-indicators">
    <li data-target="#mycarousel" data-slide-to="0" class="active"></li>
    <li data-target="#mycarousel" data-slide-to="1"></li>
  </ol>

  <div class="carousel-inner">

    <!-- first slide -->
    <div class="carousel-item first active" id="1">
      <!-- content here -->
    </div>

    <!-- second slide -->
    <div class="carousel-item second" id="2">
      <!-- content here -->
    </div>

  </div><!-- /carousel-inner -->

</div>

As you can see, it contains two slides. The first slide has a class of first and an ID of 1, while the second one has a class of second and an ID of 2.

Regarding their styles:

  • we set their height equal to the viewport height
  • we give them different background colors.

The associated CSS rules:

.item {
  height: 100vh;
}

.first {
  background: #D98F4F; /*orange*/
}

.second {
  background: #2c9cae; /*lightblue*/
}

This should be enough to give us a working carousel.

Building the First Slide

Next, we take advantage of Bootstrap’s helper classes (e.g. grid classes) to set up the contents for our slides.

The markup for the first slide is the following:

<div class="carousel-item first active" id="1">
  <div class="carousel-caption">
    <div class="container">
      <div class="row justify-content-md-center">

        <div class="col">
          <h2 class="title">
            <!-- content here -->
          </h2>
          <p class="desc">
            <!-- content here -->
          </p>
          <ul class="list">
            <!-- list items here -->
          </ul>
        </div>

        <div class="col">
          <div class="pc-wrapper">
            <img class="pc" src="IMG_PATH" alt="" width="" height="">
            <div class="price">
              <!-- content here -->
            </div><!-- /price -->
          </div><!-- /pc-wrapper -->
          <img class="keyboard" src="IMG_PATH" alt="" width="" height="">
          <button type="button" class="btn btn-danger btn-lg">
            <!-- content here -->
          </button>
        </div>

      </div><!-- /row -->
    </div><!-- /container -->
  </div><!-- /carousel-caption -->
</div><!-- /carousel-item -->

If you’re following along, be sure to replace IMG_PATH with something sensible.

Here’s what the result looks like:

Animating Bootstrap Carousels: the first slide of the carousel

Building the Second Slide

In the same way, here’s the markup for the second slide:

<div class="carousel-item second" id="2">
  <div class="carousel-caption">
    <div class="container">

      <h2 class="title">
        <span>
          <!-- content here -->
        </span>
      </h2>

      <div class="row justify-content-md-center">

        <div class="col cms-wrapper">
          <div class="cms">
            <div class="front">
              <!-- content here -->
            </div>
            <div class="back">
              <img class="img-fluid" src="IMG_PATH" alt="">
            </div><!-- /back -->
          </div><!-- /cms -->
          <p class="info">
            <!-- content here -->
          </p>
        </div><!-- /cms-wrapper -->

        <!-- two more columns here -->

      </div><!-- /row -->

      <div class="source">
        <!-- content here -->
      </div><!-- /source -->

    </div><!-- /container -->
  </div><!-- /carousel-caption -->
</div><!-- /carousel-item -->

And its visualization:

Animating Bootstrap Carousels: the second slide of the carousel

Note: For simplicity, we won’t extensively cover the styles for the inner parts of our slides. We’ll only refer to the styles that are important for the animations.

Initializing the Carousel

Next we initialize the carousel and disable default autoplay by passing interval:false to the configuration object:

var $carousel = $("#mycarousel");

$carousel.carousel({
  interval: false
});

Adding Keyboard Navigation

By default, Bootstrap carousel isn’t compliant with accessibility standards. In our case, though, let’s make the carousel a bit more accessible by adding keyboard navigation.

Here’s the required code:

$(document).keyup(function(e) {
  // right arrow
  if(e.which === 39) {
    $carousel.carousel("next");
  // left arrow
  } else if(e.which === 37) {
    $carousel.carousel("prev");
  }
});

So far, we’ve built a basic carousel which supports keyboard navigation.

Animating Bootstrap Carousels: First Animations

At this point, let’s try to make the carousel more appealing by adding some animations. To achieve this, we’ll take advantage of GSAP, one of the most powerful JavaScript animation libraries out there. If you’re looking for a thorough introduction to GreenSock, check out GreenSock for Beginners: a Web Animation Tutorial (Part 1).

Getting Started With GSAP

To incorporate GSAP into our projects, we have to visit its site and from there click the download button, which appears in the top-right corner of the page. This will open a modal dialog with a link to the project on a CDN.

How to download GSAP

If we then select the Customize radio button, we can select the parts of the library we want to use. For our project, however, we’ll keep things simple and include just the full robust version of it.

How to include GSAP into our Codepen demo

Remember that we had to add jQuery to our project because Bootstrap’s carousel depends on it. But, keep in mind that GSAP is a pure JavaScript library, and thus it doesn’t require it.

Continue reading %Animating Bootstrap Carousels with GSAP’s Animation Library%


Source: Sitepoint

Learning Framer By Creating A Mobile App Prototype

The time of static user interfaces is long gone. Designing interactive prototypes is the best approach to expressing your ideas and explaining them to clients and stakeholders. Or, as Jerry Cao of UXPin puts it: “Nothing brings you closer to the functionality of the final product than prototyping. It is the prototype that brings to life the experience behind user experience.”
Prototyping is an important part of the modern UX design process.
Source: Smashing Magazine

Creating a Blogging App Using Angular & MongoDB: Add Post

In the previous part of the Angular blog tutorial series, you learnt how to create the ShowPostComponent to display the list of blog posts on the home page. You fetched the records that were inserted from the MongoDB shell using the created REST API endpoint.

In this tutorial, you’ll be creating a new component called AddPostComponent to provide the user interface to add a new blog post to the MongoDB database.

Getting Started

Let’s get started by cloning the source code from the previous part of the tutorial series.

Navigate to the project directory and install the required dependencies.

Once you have the dependencies installed, restart the client and server application.

Point your browser to http://localhost:4200 and you should have the application running.

Creating the Add Post Component

Let’s get started by creating the AddPostComponent. Create a folder called add-post inside the src/app folder. Inside the add-post folder, create a file called add-post.component.ts and add the following code:

Create a file called add-post.component.html and the following HTML code:

You’ll be showing the add post component as a popup.

Now you need to add the AddPostComponent to the NgModule. Import the AddPostComponent in the app.module.ts file.

Add the component to the NgModule declarations list. Here is how it looks:

To trigger the add post popup, you have already added the data-target attribute to the button in home.component.html.

Save the above changes and restart the application. Log into the application and click on the Add link in the home page. You will have the AddPostComponent displayed as a popup.

Angular Blog Application - Add Post Popup

Implementing the Add Post Functionality

Add the ngModel directive to the input elements for title and description.

Add a click directive to the button for calling the method to save the blog post.

Import the Post model from src/app/models/post.model.ts in the add-post.component.ts file.

Define the post variable in the add-post.component.ts file.

Define the addPost method inside the add-post.component.ts file. From the addPost method, you’ll validate the entered title and description and make a call to the service method to call the REST API. Here is how the method looks:

Let’s create the service file for the component AddPostComponent. Create a file called add-post.service.ts and add the following code:

Inside the AddPostService, create a method called addPost to make the REST API call.

As seen in the above code, you have made use of the HttpClient to make the API call and return the Observable.

In the add-post.component.ts file inside the addPost method, you’ll subscribe to the addPost method from the add-post.service.ts file.

Here is how the add-post.component.ts file looks:

Creating the REST API for Add Post

Let’s create a REST API end point for adding the blog post to the MongoDB database. In the server/app.js file, create an API end point as shown:

First, you need to connect to the MongoDB database using the Mongoose client.

Once the connection has been established, you need to create a model object using the Post schema defined in the server/model/post.js file. 

As seen in the above code, you created the Post object using the title and description passed in from the request req object.

Call the save method on the Post object to save the entry to MongoDB.

As seen in the above code, once the save method callback is called with no error, it will return the success message along with the returned object doc.

Here is how the REST API end point finally looks:

Save the above changes and restart both Angular and Node servers. Sign in to the application and try to add a new blog post. Once you click on the Add button, check the browser console and you will have the success response logged.

When the blog post details are added to the database successfully, you need to close the popup. In order to close the popup, there is a close button which you need to click programmatically.

You’ll be using the @ViewChild decorator to access the close button.

Import ViewChild and ElementRef in AddPostComponent.

Inside the AddPostComponent, define the following variable:

Initiate the closeBtn click using the following code:

Add the above code to the success callback of the addPost method. Here is the addPost method from add-post.component.ts.

Save the changes and restart the client server. Log into the application and try adding a new blog post. Once the blog post details have been saved successfully, the popup will close.

Refreshing the Blog List

One thing to note is that the newly added blog post doesn’t show up in the blog post list. So you need to add a trigger to notify when to update the ShowPostComponent. You’ll be making use of a common service to communicate between the two components.

Create a folder called service inside the src/app folder. Create a file called common.service.ts with the following code:

As seen in the above code, you have declared a Subject called postAdded_Observable to keep track of the new blog post addition to the database. Whenever a new blog post is added to the database, you’ll call the notifyPostAddition method, which will notify the subscribers about the update.

Import the CommonService in app.module.ts and include it in the NgModule provider’s list. Here is how it looks:

Import CommonService in the show-post.component.ts file and initialize it in the constructor method.

Inside the ngOnInit method, subscribe to the postAdded_Observable variable and load the getAllPost method. Here is how the ngOnInit method looks:

Import CommonService in the add-post.component.ts file and call the notifyPostAddition method once the blog post has been added. Here is how the addPost method from the AddPostComponent looks:

Save the above changes and restart the client server. Log in to the application and add a new blog post. Once added, the blog post list gets updated with the new blog post.

Wrapping It Up

In this tutorial, you created the AddPostComponent to add the blog post details to the MongoDB database. You created the REST API for saving a blog post to the MongoDB database using the Mongoose client.

In the next part of the series, you’ll implement the functionality to edit and update the blog post details.

Source code for this tutorial is available on GitHub.

How was your experience so far? Do let me know your valuable suggestions in the comments below.


Source: Nettuts Web Development

A Full-screen Bootstrap Carousel with Random Initial Image

In this article, I’m going to build two simple extensions for the Bootstrap carousel. First, I’ll create a full-screen Bootstrap Carousel slideshow, and then I’ll show you how to randomize the first slide on page load.

But before digging into those extensions, let’s start by creating a carousel based on the default styles.

To create the carousel, we’ll take advantage of the basic code for the carousel component that Bootstrap provides:

[code language=”html”]
<div id=”carouselExampleIndicators” class=”carousel slide” data-ride=”carousel”>

<!– Indicators –>
<ol class=”carousel-indicators”>
<li data-target=”#carouselExampleIndicators” data-slide-to=”0″ class=”active”></li>
<li data-target=”#carouselExampleIndicators” data-slide-to=”1″></li>
<li data-target=”#carouselExampleIndicators” data-slide-to=”2″></li>
</ol>

<!– Wrapper for slides –>
<div class=”carousel-inner”>
<div class=”carousel-item active”>
<img class=”d-block w-100″ src=”1.jpg” data-color=”lightblue” alt=”First Image”>
<div class=”carousel-caption d-none d-md-block”>
<h5>First Image</h5>
</div>
</div>
<div class=”carousel-item”>
<!– slide content –>
</div>
<div class=”carousel-item”>
<!– slide content –>
</div>

<!– more slides –>
</div>

<!– Controls –>
<a class=”carousel-control-prev” href=”#carouselExampleIndicators” role=”button” data-slide=”prev”>
<span class=”carousel-control-prev-icon” aria-hidden=”true”></span>
<span class=”sr-only”>Previous</span>
</a>
<a class=”carousel-control-next” href=”#carouselExampleIndicators” role=”button” data-slide=”next”>
<span class=”carousel-control-next-icon” aria-hidden=”true”></span>
<span class=”sr-only”>Next</span>
</a>

</div>
[/code]

Notice that each of our images contains the custom data-color attribute. Later we’ll use its value as a fallback in case the corresponding image fails to load.

The next step is to initialize the carousel via JavaScript and modify the predefined values of the interval and pause configuration properties. Take note that we choose to set the value of the pause property to false because we always want the cycling to be active:

[code language=”javascript”]
$(‘.carousel’).carousel({
interval: 6000,
pause: “false”
});
[/code]

Having followed those simple steps (and of course imported the required files), we should now be able to build the first version of the carousel. Here’s how it looks so far:

See the Pen Basic Bootstrap Carousel by SitePoint (@SitePoint) on CodePen.

Continue reading %A Full-screen Bootstrap Carousel with Random Initial Image%


Source: Sitepoint

Introduction to Mocking in Python

Mocking is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. This tutorial will discuss in detail what mocking is and how to use it in Python applications.

What Is Mocking?

Mocking is a library for testing in Python which allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.

In Python, mocking is accomplished by replacing parts of your system with mock objects using the unittest.mock module. This module contains a number of useful classes and functions, namely the patch function (as decorator and context manager) and the MagicMock class. These two components are very important in achieving mocking in Python.

A mock function call usually returns a predefined value immediately.  A mock object’s attributes and methods are defined in the test as well, without creating the real object.

Mocking also allows you to return predefined values to each function call when writing tests. This allows you to have more control when testing.

Prerequisites

Mock is available in Python 3, but if you are using a Python version below
3.3, you can still use unittest.mock by importing it as a separate library like so.

Benefits of Mocking

Some of the benefits of mocking include:

  1. Avoiding overdependence. Mocking reduces the dependence of functions. For instance, if you have a function A class that depends on a function B, you will need to write a few unit tests covering the features provided by function B. Let’s say the code grows in future and you have more functions, i.e. A depends on B, B depends on C, and C depends on D. If a fault is introduced in Z, all your unit tests will fail.
  2. Reduced overload. This applies to resource-intensive functions. A mock of that function would cut down on unnecessary resource usage during testing, therefore reducing test run time.
  3. Bypass time constraints in functions. This applies to scheduled activities. Imagine a process that has been scheduled to execute every hour. In such a situation, mocking the time source lets you actually unit test such logic so that your test doesn’t have to run for hours, waiting for the time to pass.

Usage

Usage of mock is simple as:

Here, we import the mock module, create a mock object, and specify return values. When the mock object is called, we want it to be able to return some values. In our case, we want the mock object to return a value of 10. If we call the mock object with the arguments (1, 4, foo ='bar'), the result will be the value 10, which was defined as a return value.

You can also raise exceptions inside mocks as follows:

The side_effects argument allows you to perform certain things like raising an exception when a mock is called.

Example

Consider this simple function:

This function performs an API request to the Google webpage and returns a response.

The corresponding simple test case will be as follows:

Running the above test should give an output like so:

Let’s introduce mocking to this example, and the resulting test with the Mock module will be as shown below:

Running the above test should give an output like so:

As seen above, the mocking module takes less time to make the same API call as the normal test case.

Larger Example

Let’s assume you have a script that interacts with an external API and makes calls to that API whenever a certain function is called. In this example, we are going to use the Twitter API to implement a Python script which will post to the Twitter profile page.

We don’t want to post messages on Twitter every time we test the script, and that’s where Mocking comes in.

Let’s get started. We will be using the python-twitter library, and the first thing we will do is create a folder python_mock and, inside the folder, create two files, namely tweet.py and mock_test.py.

Write the following code to the file tweet.py.

In the code above, we first import the Twitter library and then define the authentication credentials, which you can easily get from the Twitter Apps page.

The Twitter API is exposed via the twitter.Api class, so we create the class by passing our tokens and secret keys.

The post_tweet function takes in an authentication object and the message and then posts the tweet to the Twitter profile.

We then go ahead and mock the API call to Twitter so that the API doesn’t post to Twitter every time it is called. Go ahead and open the mock_test.py file and add the following code.

Running the above test should give an output like so:

Conclusion

This tutorial has covered most of the fundamentals of mocking and how to use mocking to perform external API calls. For more information, visit the official Python mocking documentation. You can also find additional resources on authentication with the Twitter API in this tutorial.

Additionally, don’t hesitate to see what we have available for sale and for study in the Envato Market, and please go ahead and ask any questions and provide your valuable feedback using the feed below.


Source: Nettuts Web Development

How To Streamline WordPress Multisite Migrations With MU-Migration

Migrating a standalone WordPress site to a site network (or “multisite”) environment is a tedious and tricky endeavor, the opposite is also true. The WordPress Importer works reasonably well for smaller, simpler sites, but leaves room for improvement. It exports content, but not site configuration data such as Widget and Customizer configurations, plugins, and site settings. The Importer also struggles to handle a large amount of content. In this article, you’ll learn how to streamline this type of migration by using MU-Migration, a WP-CLI plugin.
Source: Smashing Magazine