text:
Module 11: Automating
Integration with Azure Resources

Lab: Automating the Creation of a Test Environment using PowerShell
-------------------------------------------------------------------

Objectives

After you complete this lab, you will be able to:

Install the Azure PowerShell modules.

Authenticate to Azure by using Windows PowerShell.

Create a Website instance by using Windows PowerShell.

Remove a Website instance by using Windows PowerShell.

Create a resource group from a template by using Windows PowerShell.

Remove a resource group by using Windows PowerShell.

Lab Setup

Estimated Time: 45 minutes

For this lab, you will use the available host machine. Before you begin
this lab, you must complete the following steps:

Prior to starting this lab, you must have completed the lab in **Module
2**.

1.  On the host computer, click **Start**, type **Remote**, and then
    click **Remote Desktop Connection**.

In Remote Desktop Connection, provide the name of your virtual machine
in the **Computer** box by using the following format:

**vm20532[*Your Name Here*].cloudapp.net:[*Your VM RDP Port*]**

>  **Note:** The name and port for your virtual
> machine might be saved in the Computer drop-down list. If this is the
> case, use this value instead of typing it in manually. If you are
> unsure about your virtual machine's RDP port, use either of the Azure
> portals to find your virtual machine's endpoints. The endpoint with
> the name **Remote Desktop** is the correct port for RDP. This port is
> randomized to protect your virtual machine from unauthorized access.

In Remote Desktop Connection, click **Connect**. Wait until the RDP
client accesses the virtual machine.

If necessary, sign in by using the following credentials:

> User name: **Student**
>
> Password: **AzurePa\$\$w0rd**

Verify that you received the credentials to sign in to the Azure portal
from your training provider. You will use these credentials and the
Azure account throughout the labs in this course.

### Exercise 1: Preparing the Azure PowerShell Environment

Scenario

In this exercise, you will:

Install the Azure PowerShell modules and cmdlets.

Authenticate to Azure in Windows PowerShell by using a Publish Settings
file.

View the account details by using Windows PowerShell

The main tasks for this exercise are as follows:

1\. Open the Azure PowerShell Console.

2\. Import your Azure subscription by using a Publish Settings file.

####   Task 1: Open the Azure PowerShell Console {#task-1-open-the-azure-powershell-console .ProcedureHeading}

Open the **Microsoft Azure PowerShell** console window.

####   Task 2: Import your Azure subscription by using a Publish Settings file {#task-2-import-your-azure-subscription-by-using-a-publish-settings-file .ProcedureHeading}

1.  Authenticate to Azure by downloading and saving the Publish Settings
    file by using the following command and details:

Get-AzurePublishSettingsFile

> File name: **20532**
>
> Save as type: **PUBLISHSETTINGS file**
>
> Directory: **(F):\\Mod11\\Labfiles**

Authenticate to Azure by importing the saved Publish Settings file:

Import-AzurePublishSettingsFile
F:\\Mod11\\Labfiles\\20532.publishsettings

View your active account details:

Get-AzureAccount

>  **Note:** If you have multiple Azure
> subscriptions, you can use **Select-AzureSubscription** to select the
> appropriate subscription. If your Azure subscription is provided by a
> Learning Partner, it might be an auto-generated account without any
> details. In such a case, this command will return an empty result.

**Results**: After completing this exercise, you will have set up a
development environment to use Windows PowerShell for Azure service
automation.

### Exercise 2: Using Windows PowerShell to create and access a Website instance

Scenario

In this exercise, you will:

View a list of Websites by using Windows PowerShell.

Create a Website by using Windows PowerShell.

Delete a Website by using Windows PowerShell.

The main tasks for this exercise are as follows:

1\. Create a new Website instance by using Windows PowerShell.

2\. Remove a Website instance by using Windows PowerShell.

####   Task 1: Create a new Website instance by using Windows PowerShell {#task-1-create-a-new-website-instance-by-using-windows-powershell .ProcedureHeading}

1.  Create a new Website by using a unique name:

New-AzureWebsite [Unique Name]

View the list of Websites for your subscription by using the following
command:

Get-AzureWebsite

View the details for your newly created Website by using the following
command:

Get-AzureWebsite –Name [Unique Name]

Record the **hostname** value from your new Website's details.

View the newly created Website by using the following command:

explorer "http://[Host Name]"

Close Internet Explorer.

Switch to the **Microsoft Azure PowerShell** console window.

####   Task 2: Remove a Website instance by using Windows PowerShell {#task-2-remove-a-website-instance-by-using-windows-powershell .ProcedureHeading}

1.  Stop your newly created Website instance by using the following
    command:

Stop-AzureWebsite –Name [Unique Name]

View the list of Websites for your subscription by using the following
command:

Get-AzureWebsite

Remove your newly created Website instance by using the following
command:

Remove-AzureWebsite –Name [Unique Name]

View the details for your recently deleted Website by using the
following command:

Get-AzureWebsite –Name [Unique Name]

**Results**: After completing this exercise, you will have used Windows
PowerShell to manage instances of an Azure service.

### Exercise 3: Using a resource template to create multiple preconfigured resources

Scenario

In this exercise, you will:

Authenticate to Azure in Windows PowerShell by using Azure Active
Directory.

Switch the Azure modules in use by using Windows PowerShell.

Create a resource group from a template by using Windows PowerShell.

Delete a resource group by using Windows PowerShell.

The main tasks for this exercise are as follows:

1\. Switch to the Azure Resource Manager PowerShell Modules.

2\. Import your Azure subscription by using Azure Active Directory.

3\. Create a resource group by using Windows PowerShell.

4\. Remove the resource group by using Windows PowerShell.

####   Task 1: Switch to the Azure Resource Manager PowerShell Modules {#task-1-switch-to-the-azure-resource-manager-powershell-modules .ProcedureHeading}

1.  Switch to the **AzureResourceManager** mode by using the following
    command:

Switch-AzureMode AzureResourceManager

####   Task 2: Import your Azure subscription by using Azure Active Directory {#task-2-import-your-azure-subscription-by-using-azure-active-directory .ProcedureHeading}

1.  Authenticate to Azure by signing in to your Azure Active Directory
    account:

Add-AzureAccount

View your active account details:

Get-AzureAccount

>  **Note:** If you have multiple Azure
> subscriptions, you can use **Select-AzureSubscription** to select the
> appropriate subscription.

####   Task 3: Create a resource group by using Windows PowerShell {#task-3-create-a-resource-group-by-using-windows-powershell .ProcedureHeading}

1.  View the description of the **Microsoft.WebSiteSQLDatabase**
    resource group template by using the following command:

Get-AzureResourceGroupGalleryTemplate -Identity
Microsoft.WebSiteSQLDatabase.0.2.0-preview

Create a new instance of the **Microsoft.WebSiteSQLDatabase** resource
group template by using following command and details:

New-AzureResourceGroup –Name rga20532 –Location "West
Us" -GalleryTemplateIdentity Microsoft.WebSiteSQLDatabase.0.2.0-preview

> siteName: **rs20532[*Your Name Here*]**
>
> hostingPlanName: **rp20532[*Your Name Here*]**
>
> siteLocation: **West US**
>
> serverName: **rv20532[*Your Name Here*]**.
>
> serverLocation: **West US**
>
> administratorLogin: **testuser**
>
> administratorLoginPassword: **TestPa\$\$w0rd**
>
> databaseName: **rd20532[*Your Name Here*]**
>
>  **Note:** Wait for the provisioning process to
> complete. Status messages will be displayed periodically and the final
> message with the details will be displayed when provisioning is
> complete.

View the details for your newly created resource group by using the
following command:

Get-AzureResourceGroup –ResourceGroupName rga20532

View the details for your newly created Website in your resource group
by using the following command:

Get-AzureResource -Name rs20532[Your Name Here] -ResourceGroupName
rga20532 -ResourceType "Microsoft.Web/sites" -ApiVersion 2014-04-01

Record the single value in the **hostNames** array from your new
Website's details.

View the newly created Website by using the following command:

explorer "http://[Host Name]"

Close Internet Explorer.

Switch to the **Microsoft Azure PowerShell** console window.

####   Task 4: Remove the resource group by using Windows PowerShell {#task-4-remove-the-resource-group-by-using-windows-powershell .ProcedureHeading}

Remove your newly created resource group by using the following command:

Remove-AzureResourceGroup –Name rga20532

>  **Note:** Because removing a resource group
> involves removing multiple resources, this process can take 5 to 15
> minutes on average.

**Results**: After completing this exercise, you will have used Azure to
interact with the Resource Manager, resource groups, and resource group
templates.

©2014 Microsoft Corporation. All rights reserved.  The text in this
document is available under the [Creative Commons Attribution 3.0
License](https://creativecommons.org/licenses/by/3.0/legalcode),
additional terms may apply.  All other content contained in this
document (including, without limitation, trademarks, logos, images,
etc.) are ***not*** included within the Creative Commons license grant.
This document does not provide you with any legal rights to any
intellectual property in any Microsoft product. You may copy and use
this document for your internal, reference purposes.

This document is provided "as-is." Information and views expressed in
this document, including URL and other Internet Web site references, may
change without notice. You bear the risk of using it. Some examples are
for illustration only and are fictitious. No real association is
intended or inferred. Microsoft makes no warranties, express or implied,
with respect to the information provided here.


text:
import module = require("p5");
// import * as p5Global from "p5/global";

export = module;
export as namespace p5;
declare global {
  interface Window {
    p5: typeof module;
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Microsoft.Azure.Management.Logic
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Collections;
    using System.Collections.Generic;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// IntegrationAccountCertificatesOperations operations.
    /// </summary>
    public partial interface IIntegrationAccountCertificatesOperations
    {
        /// <summary>
        /// Gets a list of integration account certificates.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The resource group name.
        /// </param>
        /// <param name='integrationAccountName'>
        /// The integration account name.
        /// </param>
        /// <param name='top'>
        /// The number of items to be included in the result.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<IntegrationAccountCertificate>>> ListWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, int? top = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets an integration account certificate.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The resource group name.
        /// </param>
        /// <param name='integrationAccountName'>
        /// The integration account name.
        /// </param>
        /// <param name='certificateName'>
        /// The integration account certificate name.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IntegrationAccountCertificate>> GetWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Creates or updates an integration account certificate.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The resource group name.
        /// </param>
        /// <param name='integrationAccountName'>
        /// The integration account name.
        /// </param>
        /// <param name='certificateName'>
        /// The integration account certificate name.
        /// </param>
        /// <param name='certificate'>
        /// The integration account certificate.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IntegrationAccountCertificate>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, IntegrationAccountCertificate certificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Deletes an integration account certificate.
        /// </summary>
        /// <param name='resourceGroupName'>
        /// The resource group name.
        /// </param>
        /// <param name='integrationAccountName'>
        /// The integration account name.
        /// </param>
        /// <param name='certificateName'>
        /// The integration account certificate name.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string integrationAccountName, string certificateName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
        /// <summary>
        /// Gets a list of integration account certificates.
        /// </summary>
        /// <param name='nextPageLink'>
        /// The NextLink from the previous successful call to List operation.
        /// </param>
        /// <param name='customHeaders'>
        /// The headers that will be added to request.
        /// </param>
        /// <param name='cancellationToken'>
        /// The cancellation token.
        /// </param>
        /// <exception cref="ErrorResponseException">
        /// Thrown when the operation returned an invalid status code
        /// </exception>
        /// <exception cref="Microsoft.Rest.SerializationException">
        /// Thrown when unable to deserialize the response
        /// </exception>
        /// <exception cref="Microsoft.Rest.ValidationException">
        /// Thrown when a required parameter is null
        /// </exception>
        Task<AzureOperationResponse<IPage<IntegrationAccountCertificate>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:context=".activities.AddConnectionActivity"
    android:layout_weight="1"
    >

    <Space
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:visibility="invisible"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="7"
        android:orientation="vertical">

        <EditText
            android:id="@+id/connectionName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:hint="@string/label_connection_name" />

        <EditText
            android:id="@+id/url"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:inputType="textUri"
            android:hint="@string/label_url" />

        <EditText
            android:id="@+id/userName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:hint="@string/label_user" />

        <EditText
            android:id="@+id/userPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:ems="10"
            android:hint="@string/label_password"
            android:maxLines="1"
            android:inputType="textPassword" />

        <Button
            android:id="@+id/button_create"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/create_connection"
            android:visibility="invisible" />
    </LinearLayout>

</LinearLayout>


text:
(function (factory) {
    if ( typeof define === 'function' && define.amd ) {
        define([
            'uijet_dir/uijet',
            'uijet_dir/widgets/Base',
            'uijet_dir/mixins/Submitted'
        ], function (uijet) {
            return factory(uijet);
        });
    } else {
        factory(uijet);
    }
}(function (uijet) {
    var boolean_type_re = /checkbox|radio/i;

    /**
     * Form widget class.
     *
     * @class Form
     * @category Widget
     * @extends BaseWidget
     * @mixes Submitted
     */
    uijet.Widget('Form', {
        /**
         * @member {Object} Form#options
         */
        options         : {
            type_class  : 'uijet_form',
            /**
             * Default form serializer.
             * Returns an `Object` that maps `name`s of children
             * elements to their `value`s.
             * `disabled` inputs and `checkbox` and `radio` inputs that are not checked are ignored.
             * If a `name` appears more then once, e.g. `radio` elements, then
             * the corresponding value on the returned serialized object will be an
             * `Array` of the values, ordered according to the elements' order in
             * the document.
             *
             * @function Form#options.serializer
             * @param {Object} [extra_data] - extra data to add to the serialized result.
             * @param {boolean} [as_defaults] - if `true` then `extra_data` object will be used as defaults and not override form data.
             * @returns {Object} - serialized form data.
             */
            serializer  : function (extra_data, as_defaults) {
                var $fields = this.$element.find('[name]'),
                    data = {}, args;
                $fields.each(function (i, field) {
                    if ( field.disabled ) return;
                    var name = field.name;
                    // if it's a checkbox or a radio field and not checked then ignore
                    if ( boolean_type_re.test(field.type) && ! field.checked ) return;
                    // if this key already exists
                    if ( name in data ) {
                        // if it's corresponding value is not an `Array`
                        if ( ! uijet.utils.isArr(data[name]) ) {
                            // wrap it in an `Array`
                            data[name] = [data[name]];
                        }
                        // push the new value to the list
                        data[name].push(field.value);
                    }
                    else {
                        // otherwise just set this value
                        data[name] = field.value;
                    }
                });
                if ( uijet.utils.isObj(extra_data) ) {
                    args = [extra_data];
                    args[as_defaults ? 'push' : 'unshift'](data);
                    uijet.utils.extend.apply(uijet.utils, args);
                }
                return data;
            },
            /**
             * @member {Object} Form#options.dom_events
             */
            dom_events  : {
                /**
                 * Delegates `change` event from value changes of child field elements
                 * to an app event publishing.
                 *
                 * #### Related options:
                 *
                 * * `change_exclude`: list of `name`s, or a function that returns it, of fields to exclude from `change` event delegation.
                 *
                 * #### App Events:
                 *
                 * * `<this.id>_<name>.changed`: published when the field with name `name` fires `change` event.
                 * Takes `Object` with `event` obejct and `value`.
                 *
                 * @member {function} Form#options.dom_events.change
                 * @param {Object} e - `change` event object.
                 */
                change  : function (e) {
                    var target = e.target,
                        // name is the `name` attribute and falls back to `id`
                        name = target.name || target.id,
                        // the published value either the `value` property or `false` if it's a checkbox and not checked
                        value = boolean_type_re.test(target.type) && ! target.checked ? false : uijet.$(target).val(),
                        excluded = uijet.utils.returnOf(this.options.change_exclude, this);
                    // if there aren't any excluded fields or this field is not in the excluded list then publish the changed event
                    (!excluded || !~ excluded.indexOf(name)) &&
                        uijet.publish(this.id + '_' + name + '.changed', {
                            event   : e,
                            value   : value
                        });
                }
            }
        },
        /**
         * Binds {@link Form#submit} to the `submit` event of the instance's
         * element, unless the `submit_handled` option of `uijet` is set to
         * `true`.
         *
         * @memberOf Form
         * @instance
         * @returns {Form}
         */
        register        : function () {
            this._super();
            // check if there's no one else handling the form submit event, e.g. Sammy.js
            if ( ! uijet.options.submit_handled ) {
                this.bind('submit', function (e) {
                    // stop and prevent it
                    e.preventDefault();
                    e.stopPropagation();
                    // instead call `submit`
                    this.submit();
                }.bind(this));
            }
            return this;
        },
        /**
         * Triggers `focus` event on the first input, ones the instance
         * appears, unless `dont_focus` option is set to `true`.
         *
         * #### Related options:
         *
         * * `dont_focus`: tells the instance not to focus its first input on appearing.
         *
         * @memberOf Form
         * @instance
         * @returns {Form}
         */
        appear          : function () {
            var $inputs;
            this._super();
            // on iOS devices the element.focus() method is broken
            // if `dont_focus` option is not set to `true`
            if ( ! this.options.dont_focus ) {
                // find first `<input>` and focus on it
                $inputs = this.$element.find('input');
                $inputs.length && $inputs.get(0).focus();
            }
            return this;
        },
        /**
         * Finds all child elements that match the `error_selector` option,
         * or `.error` as default, and empties them.
         *
         * #### Related options:
         *
         * * `error_selector`: query selector for finding elements containing error messages and emptying them.
         *
         * @memberOf Form
         * @instance
         * @returns {Form}
         */
        clearErrors     : function () {
            (this.$wrapper || this.$element).find(this.options.error_selector || '.error').empty();
            return this;
        }
    }, ['Submitted']);
}));


text:
/**
 * @param operator String {And, Or}
 * @param comparator String {=,<>,>=,<=,<,>}
 * @param condition String the value being compared with the comparator
 */
Constraint = function( operator, comparator, condition ) {
	this.operator = operator;
	this.comparator = comparator;
	this.condition = condition;
}


text:
package me.tipi.kiosk.util;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Base64;
import android.view.Display;
import android.view.WindowManager;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import me.tipi.kiosk.R;
import timber.log.Timber;

public class ImageUtility {

  public static String convertBitmapToString(Bitmap bitmap) {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

    return Base64.encodeToString(out.toByteArray(), Base64.DEFAULT);
  }

  public static byte[] convertBitmapStringToByteArray(String bitmapByteString) {
    return Base64.decode(bitmapByteString, Base64.DEFAULT);
  }

  public static Bitmap rotatePicture(Context context, int rotation, byte[] data) {
    Bitmap bitmap = decodeSampledBitmapFromByte(context, data);

    if (rotation != 0) {
      Bitmap oldBitmap = bitmap;

      Matrix matrix = new Matrix();
      matrix.postRotate(rotation);

      bitmap = Bitmap.createBitmap(
          oldBitmap, 0, 0, oldBitmap.getWidth(), oldBitmap.getHeight(), matrix, false
      );

      oldBitmap.recycle();
    }

    return bitmap;
  }

  public static Uri savePassportPicture(Context context, Bitmap bitmap) {
    File mediaStorageDir = new File(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
        context.getString(R.string.app_name)
    );

    if (!mediaStorageDir.exists()) {
      if (!mediaStorageDir.mkdirs()) {
        return null;
      }
    }

    Timber.w("Picture directory available");
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile = new File(
        mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"
    );

    Timber.w("file created with path: %s", mediaFile.getPath());

    // Saving the bitmap
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

      FileOutputStream stream = new FileOutputStream(mediaFile);
      stream.write(out.toByteArray());
      Timber.w("Bitmap written on file");
      stream.close();

    } catch (IOException exception) {
      Timber.w("Error writing bitmap on file, exception is: %s", exception.getMessage());
      exception.printStackTrace();
    }

    // Mediascanner need to scan for the image saved
    Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri fileContentUri = Uri.fromFile(mediaFile);
    mediaScannerIntent.setData(fileContentUri);
    context.sendBroadcast(mediaScannerIntent);

    Timber.w("File scanned to be readable, path is: %s", fileContentUri.getPath());
    return fileContentUri;
  }

  public static Uri savePicture(Context context, Bitmap bitmap) {

    File mediaStorageDir = new File(
        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
        context.getString(R.string.app_name)
    );

    if (!mediaStorageDir.exists()) {
      if (!mediaStorageDir.mkdirs()) {
        return null;
      }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile = new File(
        mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg"
    );

    // Saving the bitmap
    try {
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      bitmap.compress(Bitmap.CompressFormat.JPEG, 85, out);

      FileOutputStream stream = new FileOutputStream(mediaFile);
      stream.write(out.toByteArray());
      stream.close();

    } catch (IOException exception) {
      exception.printStackTrace();
    }

    // Mediascanner need to scan for the image saved
    Intent mediaScannerIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
    Uri fileContentUri = Uri.fromFile(mediaFile);
    mediaScannerIntent.setData(fileContentUri);
    context.sendBroadcast(mediaScannerIntent);

    return fileContentUri;
  }

  public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth, int reqHeight) {
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    options.inMutable = true;
    options.inBitmap = BitmapFactory.decodeFile(path, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inScaled = true;
    options.inDensity = options.outWidth;
    options.inTargetDensity = reqWidth * options.inSampleSize;

    options.inJustDecodeBounds = false;
    options.inPurgeable = true;
    options.inInputShareable = true;

    return BitmapFactory.decodeFile(path, options);
  }

  /**
   * Decode and sample down a bitmap from a byte stream
   */
  public static Bitmap decodeSampledBitmapFromByte(Context context, byte[] bitmapBytes) {
    Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();

    int reqWidth, reqHeight;
    Point point = new Point();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
      display.getSize(point);
      reqWidth = point.x;
      reqHeight = point.y;
    } else {
      reqWidth = display.getWidth();
      reqHeight = display.getHeight();
    }

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    options.inMutable = true;
    options.inBitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);

    // Calculate inSampleSize
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    // Load & resize the image to be 1/inSampleSize dimensions
    // Use when you do not want to scale the image with a inSampleSize that is a power of 2
    options.inScaled = true;
    options.inDensity = options.outWidth;
    options.inTargetDensity = reqWidth * options.inSampleSize;

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false; // If set to true, the decoder will return null (no bitmap), but the out... fields will still be set, allowing the caller to query the bitmap without having to allocate the memory for its pixels.
    options.inPurgeable = true;         // Tell to gc that whether it needs free memory, the Bitmap can be cleared
    options.inInputShareable = true;    // Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future

    return BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
  }

  /**
   * Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding
   * bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates
   * the closest inSampleSize that is a power of 2 and will result in the final decoded bitmap
   * having a width and height equal to or larger than the requested width and height
   * <p>
   * The function rounds up the sample size to a power of 2 or multiple
   * of 8 because BitmapFactory only honors sample size this way.
   * For example, BitmapFactory downsamples an image by 2 even though the
   * request is 3. So we round up the sample size to avoid OOM.
   */
  public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    int initialInSampleSize = computeInitialSampleSize(options, reqWidth, reqHeight);

    int roundedInSampleSize;
    if (initialInSampleSize <= 8) {
      roundedInSampleSize = 1;
      while (roundedInSampleSize < initialInSampleSize) {
        // Shift one bit to left
        roundedInSampleSize <<= 1;
      }
    } else {
      roundedInSampleSize = (initialInSampleSize + 7) / 8 * 8;
    }

    return roundedInSampleSize;
  }

  private static int computeInitialSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final double height = options.outHeight;
    final double width = options.outWidth;

    final long maxNumOfPixels = reqWidth * reqHeight;
    final int minSideLength = Math.min(reqHeight, reqWidth);

    int lowerBound = (maxNumOfPixels < 0) ? 1 :
        (int) Math.ceil(Math.sqrt(width * height / maxNumOfPixels));
    int upperBound = (minSideLength < 0) ? 128 :
        (int) Math.min(Math.floor(width / minSideLength),
            Math.floor(height / minSideLength));

    if (upperBound < lowerBound) {
      // return the larger one when there is no overlapping zone.
      return lowerBound;
    }

    if (maxNumOfPixels < 0 && minSideLength < 0) {
      return 1;
    } else if (minSideLength < 0) {
      return lowerBound;
    } else {
      return upperBound;
    }
  }

  public static Bitmap decodeJPEGfromBuffer(Context context, byte[] data) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeByteArray(data, 0, data.length, options);

    Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE))
        .getDefaultDisplay();
    int mDisplayWidth = display.getHeight();
    int mDisplayHeight = display.getWidth();

    float widthScale = (float) options.outWidth / (float) mDisplayWidth;
    float heightScale = (float) options.outHeight / (float) mDisplayHeight;
    float scale = widthScale > heightScale ? widthScale : heightScale;
    float imageRatio = (float) options.outWidth / (float) options.outHeight;
    float displayRatio = (float) mDisplayWidth / (float) mDisplayHeight;

    Bitmap bitmap = null;

    if (scale >= 8)
    {
      options.inSampleSize = 8;
    } else if (scale >= 4)
    {
      options.inSampleSize = 4;
    } else if (scale >= 2)
    {
      options.inSampleSize = 2;
    } else
    {
      options.inSampleSize = 1;
    }

    options.inJustDecodeBounds = false;

    Bitmap tempBitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);

    if (imageRatio > displayRatio)
    {
      bitmap = Bitmap.createScaledBitmap(tempBitmap, mDisplayWidth, (int) (mDisplayWidth / displayRatio), true);
    } else
    {
      bitmap = Bitmap.createScaledBitmap(tempBitmap, (int) (mDisplayHeight * imageRatio), mDisplayHeight, true);
    }

    if (bitmap != tempBitmap)
      tempBitmap.recycle();
    return bitmap;
  }

}


text:
//
//  BBView.m
//  Basketball
//
//  Created by Allen on 3/18/16.
//  Copyright © 2016 wgl. All rights reserved.
//

#import "BBView.h"

@implementation BBView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
package com.seleritycorp.common.base.http.client;

/**
 * Exception for unexpected requests/responses.
 */
public class HttpException extends Exception {
  public HttpException(String message) {
    super(message);
  }

  public HttpException(String message, Exception cause) {
    super(message, cause);
  }

  private static final long serialVersionUID = -110690644817686766L;

}


text:
'use strict';

module.exports = function (app) {
  // Root routing
  var storage = require('../controllers/storage.server.controller');

  app.route('/backend/storage/list').post(storage.list);
  app.route('/backend/storage/update_name').post(storage.updateName);
  app.route('/backend/storage/add').post(storage.add);
  app.route('/backend/storage/delete').post(storage.delete);
  app.route('/backend/storage/latest').post(storage.latest);

  app.route('/api/:apiKey/storages').get(storage.apiGet);
  app.route('/api/:apiKey/storages/:id').get(storage.apiGetById);
};


text:
// -----------------------------------------------------------------------
// <copyright file="NumberExtensionsTest.cs" company="">
// Copyright 2012 Marcel Valdez
// </copyright>
// -----------------------------------------------------------------------
namespace NVerify.Tests
{
  using NUnit.Framework;
  using NVerify.Core;

  /// <summary>
  /// Has all the tests for the number extensions.
  /// </summary>
  public class NumberExtensionsTest
  {
    // IsLess
    /// <summary>
    /// Tests if it can check less than.
    /// </summary>
    /// <param name="targetNumber">The target number.</param>
    /// <param name="comparedNumber">The compared number.</param>
    /// <param name="fail">if set to <c>true</c> it should [fail].</param>
    [TestCase(-1, 0, false)]
    [TestCase(0, 1, false)]
    // IsEqual
    [TestCase(0, 0, true)]
    // IsGreater
    [TestCase(1, 0, true)]
    public void TestIfItCanCheckLessThan(int targetNumber, int comparedNumber, bool fail)
    {
      // Arrange
      IAssertion<int> target = Verify.That(targetNumber);

      // Act
      IVerifiable<int> actual = NumberExtensions.IsLessThan(target, comparedNumber);

      // Assert
      AssertNumberComparison(fail, actual);
    }

    /// <summary>
    /// Tests if it can check less than or equal.
    /// </summary>
    /// <param name="targetNumber">The target number.</param>
    /// <param name="comparedNumber">The compared number.</param>
    /// <param name="fail">if set to <c>true</c> it should [fail].</param>
    // IsLess
    [TestCase(-1, 0, false)]
    [TestCase(0, 1, false)]
    // IsEqual
    [TestCase(0, 0, false)]
    // IsGreater
    [TestCase(1, 0, true)]
    public void TestIfItCanCheckLessThanOrEqual(int targetNumber, int comparedNumber, bool fail)
    {
      // Arrange
      IAssertion<int> target = Verify.That(targetNumber);

      // Act
      IVerifiable<int> actual = NumberExtensions.IsLessThanOrEqual(target, comparedNumber);

      // Assert
      AssertNumberComparison(fail, actual);
    }

    /// <summary>
    /// Tests if it can check greater than.
    /// </summary>
    /// <param name="targetNumber">The target number.</param>
    /// <param name="comparedNumber">The compared number.</param>
    /// <param name="fail">if set to <c>true</c> it should [fail].</param>
    // IsLess
    [TestCase(-1, 0, true)]
    [TestCase(0, 1, true)]
    // IsEqual
    [TestCase(0, 0, true)]
    // IsGreater
    [TestCase(1, 0, false)]
    public void TestIfItCanCheckGreaterThan(int targetNumber, int comparedNumber, bool fail)
    {
      // Arrange
      IAssertion<int> target = Verify.That(targetNumber);

      // Act
      IVerifiable<int> actual = NumberExtensions.IsGreaterThan(target, comparedNumber);

      AssertNumberComparison(fail, actual);
    }

    // IsLess
    /// <summary>
    /// Tests if it can check greater than or equal.
    /// </summary>
    /// <param name="targetNumber">The target number.</param>
    /// <param name="comparedNumber">The compared number.</param>
    /// <param name="shouldFail">if set to <c>true</c> it should [fail].</param>
    [TestCase(-1, 0, true)]
    [TestCase(0, 1, true)]
    // IsEqual
    [TestCase(0, 0, false)]
    // IsGreater
    [TestCase(1, 0, false)]
    public void TestIfItCanCheckGreaterThanOrEqual(int targetNumber, int comparedNumber, bool shouldFail)
    {
      // Arrange
      IAssertion<int> target = Verify.That(targetNumber);

      // Act
      IVerifiable<int> actual = NumberExtensions.IsGreaterThanOrEqual(target, comparedNumber);

      // Assert
      AssertNumberComparison(shouldFail, actual);
    }

    /// <summary>
    /// Asserts that the number comparison throws (or not) an AssertionException.
    /// </summary>
    /// <param name="shouldThrow">if set to <c>true</c> if it should throw an AssertionException.</param>
    /// <param name="verification">The verification to assert for an exception.</param>
    private static void AssertNumberComparison(bool shouldThrow, IVerifiable<int> verification)
    {
      // Assert
      if (shouldThrow)
      {
        Assert.Throws<AssertionException>(() => verification.Now());
      }
      else
      {
        Assert.DoesNotThrow(() => verification.Now());
      }
    }
  }
}


text:
package com.dev4free.devbuy.devbuyWeb.mapper;

import com.dev4free.devbuy.devbuyWeb.po.City;

public interface CityMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(City record);

    int insertSelective(City record);

    City selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(City record);

    int updateByPrimaryKey(City record);
}


text:
module HTTParty
  module StubResponse
    def stub_http_response_with(filename)
      format = filename.split('.').last.intern
      data = file_fixture(filename)

      response = Net::HTTPOK.new("1.1", 200, "Content for you")
      allow(response).to receive(:body).and_return(data)

      http_request = HTTParty::Request.new(Net::HTTP::Get, 'http://localhost', format: format)
      allow(http_request).to receive_message_chain(:http, :request).and_return(response)

      expect(HTTParty::Request).to receive(:new).and_return(http_request)
    end

    def stub_chunked_http_response_with(chunks, options = {format: "html"})
      response = Net::HTTPResponse.new("1.1", 200, nil)
      allow(response).to receive(:chunked_data).and_return(chunks)
      def response.read_body(&block)
        @body || chunked_data.each(&block)
      end

      http_request = HTTParty::Request.new(Net::HTTP::Get, 'http://localhost', options)
      allow(http_request).to receive_message_chain(:http, :request).and_yield(response).and_return(response)

      expect(HTTParty::Request).to receive(:new).and_return(http_request)
    end

    def stub_response(body, code = '200')
      code = code.to_s
      @request.options[:base_uri] ||= 'http://localhost'
      unless defined?(@http) && @http
        @http = Net::HTTP.new('localhost', 80)
        allow(@request).to receive(:http).and_return(@http)
      end

      # CODE_TO_OBJ currently missing 308
      if code == '308'
        response = Net::HTTPRedirection.new("1.1", code, body)
      else
        response = Net::HTTPResponse::CODE_TO_OBJ[code].new("1.1", code, body)
      end
      allow(response).to receive(:body).and_return(body)

      allow(@http).to receive(:request).and_return(response)
      response
    end
  end
end


text:
require "spec_helper"

describe EveOnline::ESI::Models::Planets do
  it { should be_a(EveOnline::ESI::Models::Base) }

  let(:options) { double }

  subject { described_class.new(options) }

  describe "#initialize" do
    its(:options) { should eq(options) }
  end

  describe "#planets" do
    # TODO: one more spec for case when options is not array
    let(:planet_short) { instance_double(EveOnline::ESI::Models::PlanetShort) }

    let(:option) { double }

    let(:options) { [option] }

    before { expect(EveOnline::ESI::Models::PlanetShort).to receive(:new).with(option).and_return(planet_short) }

    before { expect(subject.planets).to eq([planet_short]) }
  end
end


text:
'''Classes used for encoding and decoding :class:`stdnet.odm.Field` values.

.. autoclass:: Encoder
   :members:
   :member-order: bysource

These are all available :class:`Encoder`:

.. autoclass:: NoEncoder

.. autoclass:: Default

.. autoclass:: NumericDefault

.. autoclass:: Bytes

.. autoclass:: Json

.. autoclass:: PythonPickle

.. autoclass:: DateTimeConverter

.. autoclass:: DateConverter
'''
import json
import logging

from datetime import datetime, date
from struct import pack, unpack

from stdnet.utils import (JSONDateDecimalEncoder, pickle,
                          JSONDateDecimalEncoder, DefaultJSONHook,
                          ispy3k, date2timestamp, timestamp2date,
                          string_type)

nan = float('nan')

LOGGER = logging.getLogger('stdnet.encoders')

class Encoder(object):
    '''Virtaul class for encoding data in
:ref:`data structures <model-structures>`. It exposes two methods
for encoding and decoding data to and from the data server.

.. attribute:: type

    The type of data once loaded into python
'''
    type = None

    def dumps(self, x):
        '''Serialize data for database'''
        raise NotImplementedError()

    def loads(self, x):
        '''Unserialize data from database'''
        raise NotImplementedError()

    def require_session(self):
        '''``True`` if this :class:`Encoder` requires a
:class:`stdnet.odm.Session`.'''
        return False

    def load_iterable(self, iterable, session=None):
        '''Load an ``iterable``.

        By default it returns a generator of data loaded via the
        :meth:`loads` method.

        :param iterable: an iterable over data to load.
        :param session: Optional :class:`stdnet.odm.Session`.
        :return: an iterable over decoded data.
        '''
        data = []
        load = self.loads
        for v in iterable:
            data.append(load(v))
        return data

class Default(Encoder):
    '''The default unicode encoder. It converts bytes to unicode when loading
data from the server. Viceversa when sending data.'''
    type = string_type

    def __init__(self, charset='utf-8', encoding_errors='strict'):
        self.charset = charset
        self.encoding_errors = encoding_errors

    if ispy3k:
        def dumps(self, x):
            if isinstance(x, bytes):
                return x
            else:
                return str(x).encode(self.charset, self.encoding_errors)

        def loads(self, x):
            if isinstance(x, bytes):
                return x.decode(self.charset, self.encoding_errors)
            elif x is not None:
                return str(x)

    else:  # pragma nocover
        def dumps(self, x):
            if not isinstance(x, unicode):
                x = str(x)
            return x.encode(self.charset, self.encoding_errors)

        def loads(self, x):
            if not isinstance(x, unicode) and x is not None:
                x = str(x)
                return x.decode(self.charset, self.encoding_errors)
            else:
                return x

def safe_number(v):
    try:
        v = float(v)
        vi = int(v)
        return vi if vi == v else v
    except Exception:
        return v

class NumericDefault(Default):
    '''It decodes values into unicode unless they are numeric, in which case
they are decoded as such.'''
    def loads(self, x):
        x = super(NumericDefault, self).loads(x)
        return safe_number(x)

class Double(Encoder):
    '''It decodes values into doubles. If the decoding fails it decodes the
value into ``nan`` (not a number).'''
    type = float

    def loads(self, x):
        try:
            return float(x)
        except (ValueError, TypeError):
            return nan
    dumps = loads

class Bytes(Encoder):
    '''The binary encoder'''
    type = bytes

    def __init__(self, charset='utf-8', encoding_errors='strict'):
        self.charset = charset
        self.encoding_errors = encoding_errors

    def dumps(self, x):
        if not isinstance(x, bytes):
            x = x.encode(self.charset, self.encoding_errors)
        return x

    loads = dumps

class NoEncoder(Encoder):
    '''A dummy encoder class'''
    def dumps(self, x):
        return x

    def loads(self, x):
        return x

class PythonPickle(Encoder):
    '''A safe pickle serializer. By default we use protocol 2 for compatibility
between python 2 and python 3.'''
    type = bytes

    def __init__(self, protocol=2):
        self.protocol = protocol

    def dumps(self, x):
        if x is not None:
            try:
                return pickle.dumps(x, self.protocol)
            except:
                LOGGER.exception('Could not pickle %s', x)

    def loads(self, x):
        if x is None:
            return x
        elif isinstance(x, bytes):
            try:
                return pickle.loads(x)
            except (pickle.UnpicklingError, EOFError, ValueError):
                return x.decode('utf-8', 'ignore')
        else:
            return x

class Json(Default):
    '''A JSON encoder for maintaning python types when dealing with
remote data structures.'''
    def __init__(self,
                 charset='utf-8',
                 encoding_errors='strict',
                 json_encoder=None,
                 object_hook=None):
        super(Json, self).__init__(charset, encoding_errors)
        self.json_encoder = json_encoder or JSONDateDecimalEncoder
        self.object_hook = object_hook or DefaultJSONHook

    def dumps(self, x):
        return json.dumps(x, cls=self.json_encoder)

    def loads(self, x):
        if isinstance(x, bytes):
            x = x.decode(self.charset, self.encoding_errors)
        return json.loads(x, object_hook=self.object_hook)

class DateTimeConverter(Encoder):
    '''Convert to and from python ``datetime`` objects and unix timestamps'''
    type = datetime

    def dumps(self, value):
        return date2timestamp(value)

    def loads(self, value):
        return timestamp2date(value)

class DateConverter(DateTimeConverter):
    type = date
    '''Convert to and from python ``date`` objects and unix timestamps'''

    def loads(self, value):
        return timestamp2date(value).date()

class CompactDouble(Encoder):
    type = float
    nil = b'\x00'*8
    nan = float('nan')

    def dumps(self, value):
        if value is None:
            return self.nil
        value = float(value)
        if value != value:
            return self.nil
        else:
            return pack('>d', value)

    def loads(self, value):
        if value == self.nil:
            return self.nan
        else:
            return unpack('>d', value)[0]


text:
title: A Look at Async/Await in ES2017
date: "2017-08-09T14:17:39.475Z"
path: "/articles/async-await/"
excerpt: "Writing asynchronous code in JavaScript has traditionally been a pretty messy endeavor. It usually meant writing callbacks on top of callbacks, handling errors multiple levels deep, resulting in the infamous pyramid of doom."
category:
  label: 'JavaScript'
  slug: 'javascript'
---

Writing asynchronous code in JavaScript has traditionally been a pretty messy endeavor. It usually meant writing callbacks on top of callbacks, handling errors multiple levels deep, resulting in the infamous [pyramid of doom](https://en.wikipedia.org/wiki/Pyramid_of_doom_(programming)).

```js
fs.readdir(source, function (err, files) {
  if (err) {
    console.log('Error finding files: ' + err)
  } else {
    files.forEach(function (filename, fileIndex) {
      console.log(filename)
      gm(source + filename).size(function (err, values) {
        if (err) {
          console.log('Error identifying file size: ' + err)
        } else {
          console.log(filename + ' : ' + values)
          aspect = (values.width / values.height)
          widths.forEach(function (width, widthIndex) ]
            height = Math.round(width / aspect)
            console.log('resizing ' + filename + 'to ' + height + 'x' + height)
            this.resize(width, height).write(dest + 'w' + width + '_' + filename, function(err) {
              if (err) console.log('Error writing file: ' + err)
            })
          }.bind(this))
        }
      })
    })
  }
})
```

Ew, right? This is a sample from [callbackhell.com](http://callbackhell.com) that I think is a pretty excellent example of exactly what async functions aim to save us from.

### Overview

Async functions, a major feature in the ES2017 spec, are effectively a combination of two big ES6 features: Promises and generator functions.

When an async function is called, it returns a Promise. If you're not familiar with Promises, Axel Rauschmayer has an excellent primer on [2ality](http://2ality.com/2014/09/es6-promises-foundations.html). In short, though, a Promise is an object that represents the eventual success or failure value of an asynchronous operation.

On the other hand, we have generator functions. Generators are functions that can be exited and later re-entered, with context stored across re-entrances. In the context of async functions, generators give us the ability to pause a function, wait for an asynchronous operation to finish, then jump back in and continue execution.

In broad terms, you can think of async functions a lot like regular Promises. When you resolve a Promise, you use the `.then()` callback to continue execution. With async functions, `await` behaves a lot like `.then()`, in that it will pause the execution of your function until that Promise has been resolved.

### Cool, so how can I use async functions?

Let's start with a basic example that may look a little familiar:
```js
async function fetchJson(url) {
    try {
        const request = await fetch(url);
        const text = await request.text();
        return JSON.parse(text);
    }
    catch (error) {
        console.log(`ERROR: ${error.stack}`);
    }
}

// Can be called with:
fetchJson('https://example.com/file.json')
.then(obj => console.log(obj));
```
Here we're using an async function to fetch some JSON from a file, parse that file, and return the contents. We use await to pause while fetch goes and gets the file, then again on the next line while the `request.text()` Promise is resolved.

In async functions, errors are handled with `try...catch` blocks. In the sample above, if our Promise is rejected we just log the error to the console.

It's important to note that if your async function does not declare a `catch`, errors will be swallowed, meaning they will be silently disposed of unless explicitly handled.

`youtube:https://www.youtube.com/embed/WvJ9fK1dqlI`

### Stuff worth noting

Async functions are started synchronously, but settled asynchronously. Meaning, they're fired off in execution order, but the Promise is resolved and returned asynchronously.

As you can see in the example above, an async function is not limited to a single `await`; you can `await` the resolution of multiple asynchronous operations within the same function. Each `await` declaration will wait for the previous value to resolve before performing its own operation.

One big *gotcha* with async functions is that you cannot to use `await` within a [nested function](http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/). For example, if you have a callback within your async function that includes `await`, that `await` will not be respected.

Another interesting thing to note is that in async functions, the returned Promises are not wrapped; meaning if you return a non-Promise value then that value fulfills the Promise `p`, and if you do return a Promise, then that `p` now mirrors the state of the Promise.

```js
async function asyncFunc() {
    return Promise.resolve('abc');
}
asyncFunc()
.then(x => console.log(x)) // abc
```

If your returned Promise is rejected, then your async function will also be rejected.

```js
async function asyncFunc() {
    return Promise.reject(new Error('Oh no!'));
}
asyncFunc()
.catch(err => console.error(err)); // Error: Oh no!
```

### Start writing better async code today!

Pretty cool, right? Ready for the good news? Most browsers already have native [support](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#Browser_compatibility) for async functions... for those that don't, Babel has a [polyfill](https://babeljs.io/docs/plugins/transform-async-to-generator/).

### Further Reading

I came across a lot of helpful resources on async functions while researching this article. Here are a few of my favorites:
* [Async/await proposal](https://tc39.github.io/ecmascript-asyncawait/)
* [ExploringJS](http://exploringjs.com/es2016-es2017/ch_async-functions.html)
* [Understand Promises before you start using async/await](https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8)
* [Simplifying Asynchronous Coding with Async Functions](https://www.sitepoint.com/simplifying-asynchronous-coding-async-functions/)


text:
function [bbci,data]= bbci_calibrate_NIRS_tiny(bbci, data)
%BBCI_CALIBRATE_CSP_TINY - Calibrate NIRS data (Tiny ver.)
%
%This function is called by bbci_calibrate
%(if BBCI.calibate.fcn is set to @bbci_calibrate_NIRS_tiny).
%Via BBCI.calibrate.settings, the details can be specified, see below.
%
%Synopsis:
% [BBCI, DATA]= bbci_calibrate_NIRS_tiny(BBCI, DATA)
%
%Arguments:
%  BBCI -  the field 'calibrate.settings' holds parameters specific to
%          calibrate CSP-based BCI processing.
%  DATA -  holds the calibration data
%
%Output:
%  BBCI - Updated BBCI structure in which all necessary fields for
%     online operation are set, see bbci_apply_structures.
%  DATA - As input.
%
%BBCI.calibrate.settings may include the following parameters:
%  ival - [1x2 DOUBLE] interval which is used to calculate training features,
%     (msec), default: [4000 8000]
%  ref_ival - [1x2 DOUBLE] reference interval (msec), default [-2000 2000]
%  clab - [CELL] Labels of the channels that are used for classification,
%     default {'*'}.
%  model - [CHAR or CELL] Classification model.
%     Default {'RLDAshrink', 'gamma',0, store_means',1, 'scaling',1}.

% 09-2012 S. Fazli

default_clab=  {'*'};
default_model= {@train_RLDAshrink, 'Gamma',0, 'StoreMeans',1, 'Scaling',1};

props= {'clab'       default_clab    'CELL{CHAR}'
        'ref_ival'   [-2000 2000]    '!DOUBLE[1 2]'
        'ival'       [4000 8000]     '!DOUBLE[1 2]'
        'model'      default_model   'FUNC|CELL'
       };
opt= opt_setDefaults('bbci.calibrate.settings', props);

% make epochs:
segmentation_ival= [opt.ref_ival(1) opt.ival(2)];
fv= proc_segmentation(data.cnt, data.mrk, segmentation_ival, ...
                      'clab', opt.clab);
fv= proc_baseline(fv, opt.ref_ival);
fv= proc_jumpingMeans(fv, opt.ival);

bbci.signal.clab = data.cnt.clab;
bbci.signal.proc={};

bbci.feature.ival= [-5000 0];
bbci.feature.proc= {@proc_meanAcrossTime};

bbci.classifier.C= trainClassifier(fv, opt.model);

opt_xv= struct('SampleFcn',  {{@sample_chronKFold, 10}});
[loss,loss_std]= crossvalidation(fv, opt.model, opt_xv);
fprintf('NIRS classifier trained');
bbci_log_write(data.log.fid, 'CV loss: %2.1f +/- %2.1f%%', ...
               100*loss, 100*loss_std);

data.result.classes=fv.className;


text:
<?php

namespace Application\CalendarBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class CalendarType extends AbstractType {

    /**
* @param FormBuilderInterface $builder
* @param array $options
*
*
*
*
*
* @param \Symfony\Component\Form\FormBuilderInterface $builder
* @param array $options
*/
    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder
                ->add('title','text',array('label'=>'Titre'))
                ->add('bgColor','text',array('label'=>'Background Color'))
                ->add('fgColor','text',array('label'=>'Font Color'))
               // ->add('startDatetime','hidden')
              // ->add('endDatetime','hidden')
              /*  ->add('description', 'textarea')*/
              /*  ->add('description', 'ckeditor')*/
              /*  ->add('description', 'ckeditor', array(
                     'config_name' => 'simple_config',

                ))*/
                 ->add('description', 'ckeditor', array(
                    'config_name' => 'my_config',

                ))

                   ->add('idStatus', 'checkbox', array('label' => 'Checked','required' => false))
                ->add('cssClass','hidden')
                    ->add('endDatetime', 'datetime', array(
                    'label' => 'Date Fin',
                    'widget' => 'single_text',
                    'input' => 'datetime',
                    'format' => 'yyyy-MM-dd HH:mm',
                    'widget_addon' => array(
                        'icon' => 'time',
                        'type' => 'prepend'
                    ),
                ))
                ->add('startDatetime', 'datetime', array(
                    'label' => 'Date Debut',
                    'widget' => 'single_text',
                    'input' => 'datetime',
                    'format' => 'yyyy-MM-dd HH:mm',
                    'widget_addon' => array(
                        'icon' => 'time',
                        'type' => 'prepend'
                    ),
                    'required' => false,
                ))

                 ->add('picture', 'collection', array(
                    'type' => new CalendarDocumentsType(),
                    'allow_add' => true,
                    'by_reference' => false,
                    'allow_delete' => true,
                       'prototype' => true,
                      'label'=>false,
                   /*'attr' => array(
                'class' => 'span5'
            )*/
                   // 'prototype' => true,
                    //'prototype_name' => '__name__'
                    ))

        ;
    }

    /**
* @param OptionsResolverInterface $resolver
*/
    public function setDefaultOptions(OptionsResolverInterface $resolver) {
        $resolver->setDefaults(array(
            'data_class' => 'Application\CalendarBundle\Entity\AdesignCalendar',
            'cascade_validation' => true,
            'csrf_protection' => true,
            'csrf_field_name' => '_token',
            // a unique key to help generate the secret token
            'intention'       => 'task_item',
         // 'data_class' => 'Application\CalendarBundle\Entity\AdesignCalendar'
        ));
    }

    /**
* @return string
*/
    public function getName() {
    //    return 'adesigncal';
        return;
    }

}


text:
import IgniteChartNoDataCtrl from './controller';
import templateUrl from './template.tpl.pug';

export default {
    controller: IgniteChartNoDataCtrl,
    templateUrl,
    require: {
        igniteChart: '^igniteChart'
    },
    bindings: {
        resultDataStatus: '<',
        handleClusterInactive: '<'
    }
} as ng.IComponentOptions;


text:
<!--
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="property-accessors.html">

<script>
  (function() {
    'use strict';

    const HOST_DIR = /:host\(:dir\((ltr|rtl)\)\)/g;
    const HOST_DIR_REPLACMENT = ':host([dir="$1"])';

    const EL_DIR = /([\s\w#\.\[\]\*]*):dir\((ltr|rtl)\)/g;
    const EL_DIR_REPLACMENT = ':host([dir="$2"]) $1';

    /**
     * @type {!Array<!Polymer_DirMixin>}
     */
    const DIR_INSTANCES = [];

    /** @type {MutationObserver} */
    let observer = null;

    let DOCUMENT_DIR = '';

    function getRTL() {
      DOCUMENT_DIR = document.documentElement.getAttribute('dir');
    }

    /**
     * @param {!Polymer_DirMixin} instance Instance to set RTL status on
     */
    function setRTL(instance) {
      if (!instance.__autoDirOptOut) {
        const el = /** @type {!HTMLElement} */(instance);
        el.setAttribute('dir', DOCUMENT_DIR);
      }
    }

    function updateDirection() {
      getRTL();
      DOCUMENT_DIR = document.documentElement.getAttribute('dir');
      for (let i = 0; i < DIR_INSTANCES.length; i++) {
        setRTL(DIR_INSTANCES[i]);
      }
    }

    function takeRecords() {
      if (observer && observer.takeRecords().length) {
        updateDirection();
      }
    }

    /**
     * Element class mixin that allows elements to use the `:dir` CSS Selector to have
     * text direction specific styling.
     *
     * With this mixin, any stylesheet provided in the template will transform `:dir` into
     * `:host([dir])` and sync direction with the page via the element's `dir` attribute.
     *
     * Elements can opt out of the global page text direction by setting the `dir` attribute
     * directly in `ready()` or in HTML.
     *
     * Caveats:
     * - Applications must set `<html dir="ltr">` or `<html dir="rtl">` to sync direction
     * - Automatic left-to-right or right-to-left styling is sync'd with the `<html>` element only.
     * - Changing `dir` at runtime is supported.
     * - Opting out of the global direction styling is permanent
     *
     * @mixinFunction
     * @polymer
     * @appliesMixin Polymer.PropertyAccessors
     * @memberof Polymer
     */
    Polymer.DirMixin = Polymer.dedupingMixin((base) => {

      if (!observer) {
        getRTL();
        observer = new MutationObserver(updateDirection);
        observer.observe(document.documentElement, {attributes: true, attributeFilter: ['dir']});
      }

      /**
       * @constructor
       * @extends {base}
       * @implements {Polymer_PropertyAccessors}
       */
      const elementBase = Polymer.PropertyAccessors(base);

      /**
       * @polymer
       * @mixinClass
       * @implements {Polymer_DirMixin}
       */
      class Dir extends elementBase {

        /**
         * @override
         * @suppress {missingProperties} Interfaces in closure do not inherit statics, but classes do
         */
        static _processStyleText(is, template, baseURI) {
          let cssText = super._processStyleText(is, template, baseURI);
          cssText = this._replaceDirInCssText(cssText);
          return cssText;
        }

        /**
         * Replace `:dir` in the given CSS text
         *
         * @param {string} text CSS text to replace DIR
         * @return {string} Modified CSS
         */
        static _replaceDirInCssText(text) {
          let replacedText = text;
          replacedText = replacedText.replace(HOST_DIR, HOST_DIR_REPLACMENT);
          replacedText = replacedText.replace(EL_DIR, EL_DIR_REPLACMENT);
          if (text !== replacedText) {
            this.__activateDir = true;
          }
          return replacedText;
        }

        constructor() {
          super();
          /** @type {boolean} */
          this.__autoDirOptOut = false;
        }

        /**
         * @suppress {invalidCasts} Closure doesn't understand that `this` is an HTMLElement
         */
        ready() {
          super.ready();
          this.__autoDirOptOut = /** @type {!HTMLElement} */(this).hasAttribute('dir');
        }

        /** @suppress {missingProperties} If it exists on elementBase, it can be super'd */
        connectedCallback() {
          if (elementBase.prototype.connectedCallback) {
            super.connectedCallback();
          }
          if (this.constructor.__activateDir) {
            takeRecords();
            DIR_INSTANCES.push(this);
            setRTL(this);
          }
        }

        /** @suppress {missingProperties} If it exists on elementBase, it can be super'd */
        disconnectedCallback() {
          if (elementBase.prototype.disconnectedCallback) {
            super.disconnectedCallback();
          }
          if (this.constructor.__activateDir) {
            const idx = DIR_INSTANCES.indexOf(this);
            if (idx > -1) {
              DIR_INSTANCES.splice(idx, 1);
            }
          }
        }
      }

      Dir.__activateDir = false;

      return Dir;
    });
  })();
</script>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DialogBoxController : MonoBehaviour {
    public GameObject dialogBox;
    public Text dialog;
    public TextAsset textFile;
    public string[] textLines;
    private int currentLine;
    private int endAtLine = 3;
    private bool isTyping;
    private bool cancelTyping;
    public float typeSpeed;
    public bool isActive;
    private bool onlyOnce = true;
    private string familiar;
    // Use this for initialization
    void Start() {
        familiar = "Why does this number look so familiar?";
        currentLine = 0;
        isTyping = false;
        cancelTyping = false;
        if (textLines != null) {
            textLines = (textFile.text.Split('\n'));
        }
        if (isActive) {
            EnableDialogBox();
        }
        else {
            DisableDialogBox();
        }
    }

    // Update is called once per frame
    void Update() {
        if (!isActive) {
            return;
        }
        if (Input.GetKeyDown(KeyCode.Return) && currentLine < endAtLine ) {
            if (!isTyping) {
                currentLine++;
                if (currentLine >= endAtLine) {
                    DisableDialogBox();
                }
                else {
                    StartCoroutine(TextScroll(textLines[currentLine]));
                }
            }
            else if (isTyping && !cancelTyping) {
                cancelTyping = true;
            }
        }
    }

    private IEnumerator TextScroll(string lineOfText) {
        int letter = 0;
        dialog.text = "";
        isTyping = true;
        cancelTyping = false;
        while (isTyping && !cancelTyping && (letter < lineOfText.Length - 1)) {
            dialog.text += lineOfText[letter];
            letter++;
            yield return new WaitForSeconds(typeSpeed);
        }
        dialog.text = lineOfText;
        isTyping = false;
        cancelTyping = false;
    }

    public void EnableDialogBox() {
        dialogBox.SetActive(true);
        isActive = true;
        currentLine = 0;
        /*
        if (Movement.hasKey) {
            currentLine = endAtLine + 1;
            StartCoroutine(TextScroll(familiar));
           	dialog.text = "";
        }

        else {*/
            StartCoroutine(TextScroll(textLines[currentLine]));
        //}
    }

    public void DisableDialogBox() {
            dialogBox.SetActive(false);
            isActive = false;
            dialog.text = "";
    }

}


text:
package com.dremio.exec.store;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import org.apache.arrow.vector.ValueVector;

import com.dremio.common.expression.CompleteType;
import com.dremio.exec.expr.ExpressionEvaluationOptions;
import com.dremio.exec.record.VectorContainer;
import com.dremio.exec.store.ComplexTypeCopiers.ComplexTypeCopier;
import com.dremio.sabot.exec.context.OperatorContext;
import com.dremio.sabot.op.scan.OutputMutator;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;

/**
 * This class helps in handling coercion of nested complex type columns
 */
public class ComplexTypeReader implements AutoCloseable {
  private final SampleMutator mutator;
  private final OperatorContext context;
  private final Stopwatch javaCodeGenWatch;
  private final TypeCoercion typeCoercion;
  private final Stopwatch gandivaCodeGenWatch;

  private OutputMutator outputMutator;
  private ComplexTypeCopier[] copiers;

  public ComplexTypeReader(OperatorContext context, SampleMutator mutator, TypeCoercion typeCoercion,
                           Stopwatch javaCodeGenWatch, Stopwatch gandivaCodeGenWatch) {
    Preconditions.checkArgument(mutator != null, "Invalid argument");
    this.mutator = mutator;
    this.context = context;
    this.typeCoercion = typeCoercion;
    this.javaCodeGenWatch = javaCodeGenWatch;
    this.gandivaCodeGenWatch = gandivaCodeGenWatch;
  }

  private void createCopiers() {
    ArrayList<ValueVector> outComplexVectors = new ArrayList<>();
    ArrayList<ValueVector> inComplexVectors = new ArrayList<>();

    Preconditions.checkState(outputMutator != null, "Invalid state");
    Iterator<ValueVector> outVectorIterator = outputMutator.getVectors().iterator();
    Map<String,ValueVector> inFieldMap = mutator.getFieldVectorMap();

    // for each outvector find matching invector by doing case insensitive name search
    while (outVectorIterator.hasNext()) {
      ValueVector outV = outVectorIterator.next();
      ValueVector inV = inFieldMap.getOrDefault(outV.getField().getName().toLowerCase(), null);
      final CompleteType targetType = CompleteType.fromField(outV.getField());
      if (targetType.isComplex()) {
        inComplexVectors.add(inV);
        outComplexVectors.add(outV);
      }
    }

    copiers = ComplexTypeCopiers.createCopiers(context, inComplexVectors, outComplexVectors,
      typeCoercion, javaCodeGenWatch, gandivaCodeGenWatch);
  }

  public void setupProjector(OutputMutator output, VectorContainer incoming,
                             ExpressionEvaluationOptions projectorOptions,
                             VectorContainer projectorOutput) {
    outputMutator = output;
    createCopiers();
    for (ComplexTypeCopier copier: copiers) {
      copier.setupProjector(incoming, projectorOptions, projectorOutput);
    }
  }

  public void runProjector(int recordCount) {
    for (ComplexTypeCopier copier: copiers) {
      copier.copy(recordCount);
    }
  }

  @Override
  public void close() throws Exception {
    if (copiers != null) {
      for (ComplexTypeCopier copier : copiers) {
        copier.close();
      }
    }
  }
}