text:
package au.edu.uts.eng.remotelabs.schedserver.session.intf.types;

import java.io.Serializable;
import java.util.ArrayList;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;

import org.apache.axiom.om.OMConstants;
import org.apache.axiom.om.OMDataSource;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.impl.llom.OMSourcedElementImpl;
import org.apache.axis2.databinding.ADBBean;
import org.apache.axis2.databinding.ADBDataSource;
import org.apache.axis2.databinding.ADBException;
import org.apache.axis2.databinding.utils.BeanUtil;
import org.apache.axis2.databinding.utils.ConverterUtil;
import org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl;
import org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter;

/**
 * UserNSNameSequence bean class.
 */
public class UserNSNameSequence implements ADBBean
{
    /*
     * This type was generated from the piece of schema that had
     * name = UserNSNameSequence
     * Namespace URI = http://remotelabs.eng.uts.edu.au/schedserver/session
     * Namespace Prefix = ns1
     */

    private static final long serialVersionUID = -70105014983400943L;

    protected String userName;
    protected boolean userNameTracker = false;

    protected String userNamespace;
    protected boolean userNamespaceTracker = false;

    private static String generatePrefix(final String namespace)
    {
        if (namespace.equals("http://remotelabs.eng.uts.edu.au/schedserver/session"))
        {
            return "ns1";
        }
        return BeanUtil.getUniquePrefix();
    }

    public String getUserName()
    {
        return this.userName;
    }

    public void setUserName(final String param)
    {
        if (param != null)
        {
            this.userNameTracker = true;
        }
        else
        {
            this.userNameTracker = false;
        }

        this.userName = param;
    }

    public String getUserNamespace()
    {
        return this.userNamespace;
    }

    public void setUserNamespace(final String param)
    {
        if (param != null)
        {
            this.userNamespaceTracker = true;
        }
        else
        {
            this.userNamespaceTracker = false;
        }

        this.userNamespace = param;
    }

    public static boolean isReaderMTOMAware(final XMLStreamReader reader)
    {
        boolean isReaderMTOMAware = false;
        try
        {
            isReaderMTOMAware = Boolean.TRUE.equals(reader.getProperty(OMConstants.IS_DATA_HANDLERS_AWARE));
        }
        catch (final IllegalArgumentException e)
        {
            isReaderMTOMAware = false;
        }
        return isReaderMTOMAware;
    }

    public OMElement getOMElement(final QName parentQName, final OMFactory factory) throws ADBException
    {
        final OMDataSource dataSource = new ADBDataSource(this, parentQName)
        {
            @Override
            public void serialize(final MTOMAwareXMLStreamWriter xmlWriter) throws XMLStreamException
            {
                UserNSNameSequence.this.serialize(this.parentQName, factory, xmlWriter);
            }
        };
        return new OMSourcedElementImpl(parentQName, factory, dataSource);
    }

    @Override
    public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter)
            throws XMLStreamException, ADBException
    {
        this.serialize(parentQName, factory, xmlWriter, false);
    }

    @Override
    public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter,
            final boolean serializeType) throws XMLStreamException, ADBException
    {
        String prefix = null;
        String namespace = null;

        if (serializeType)
        {
            final String namespacePrefix = this.registerPrefix(xmlWriter,
                    "http://remotelabs.eng.uts.edu.au/schedserver/session");
            if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0))
            {
                this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix
                        + ":UserNSNameSequence", xmlWriter);
            }
            else
            {
                this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "UserNSNameSequence",
                        xmlWriter);
            }
        }

        if (this.userNameTracker)
        {
            namespace = "";
            if (!namespace.equals(""))
            {
                prefix = xmlWriter.getPrefix(namespace);
                if (prefix == null)
                {
                    prefix = UserNSNameSequence.generatePrefix(namespace);
                    xmlWriter.writeStartElement(prefix, "userName", namespace);
                    xmlWriter.writeNamespace(prefix, namespace);
                    xmlWriter.setPrefix(prefix, namespace);
                }
                else
                {
                    xmlWriter.writeStartElement(namespace, "userName");
                }
            }
            else
            {
                xmlWriter.writeStartElement("userName");
            }

            if (this.userName == null)
            {
                throw new ADBException("userName cannot be null!!");
            }
            else
            {
                xmlWriter.writeCharacters(this.userName);
            }

            xmlWriter.writeEndElement();
        }

        if (this.userNamespaceTracker)
        {
            namespace = "";
            if (!namespace.equals(""))
            {
                prefix = xmlWriter.getPrefix(namespace);
                if (prefix == null)
                {
                    prefix = UserNSNameSequence.generatePrefix(namespace);
                    xmlWriter.writeStartElement(prefix, "userNamespace", namespace);
                    xmlWriter.writeNamespace(prefix, namespace);
                    xmlWriter.setPrefix(prefix, namespace);
                }
                else
                {
                    xmlWriter.writeStartElement(namespace, "userNamespace");
                }
            }
            else
            {
                xmlWriter.writeStartElement("userNamespace");
            }

            if (this.userNamespace == null)
            {
                throw new ADBException("userNamespace cannot be null!!");
            }
            else
            {
                xmlWriter.writeCharacters(this.userNamespace);
            }

            xmlWriter.writeEndElement();
        }
    }

    private void writeAttribute(final String prefix, final String namespace, final String attName,
            final String attValue, final XMLStreamWriter xmlWriter) throws XMLStreamException
    {
        if (xmlWriter.getPrefix(namespace) == null)
        {
            xmlWriter.writeNamespace(prefix, namespace);
            xmlWriter.setPrefix(prefix, namespace);
        }

        xmlWriter.writeAttribute(namespace, attName, attValue);
    }

    private String registerPrefix(final XMLStreamWriter xmlWriter, final String namespace) throws XMLStreamException
    {
        String prefix = xmlWriter.getPrefix(namespace);
        if (prefix == null)
        {
            prefix = UserNSNameSequence.generatePrefix(namespace);
            while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null)
            {
                prefix = BeanUtil.getUniquePrefix();
            }

            xmlWriter.writeNamespace(prefix, namespace);
            xmlWriter.setPrefix(prefix, namespace);
        }

        return prefix;
    }

    @Override
    public XMLStreamReader getPullParser(final QName qName) throws ADBException
    {

        final ArrayList<Serializable> elementList = new ArrayList<Serializable>();

        if (this.userNameTracker)
        {
            elementList.add(new QName("", "userName"));
            if (this.userName != null)
            {
                elementList.add(ConverterUtil.convertToString(this.userName));
            }
            else
            {
                throw new ADBException("userName cannot be null!!");
            }
        }

        if (this.userNamespaceTracker)
        {
            elementList.add(new QName("", "userNamespace"));
            if (this.userNamespace != null)
            {
                elementList.add(ConverterUtil.convertToString(this.userNamespace));
            }
            else
            {
                throw new ADBException("userNamespace cannot be null!!");
            }
        }

        return new ADBXMLStreamReaderImpl(qName, elementList.toArray(), new Object[0]);
    }

    public static class Factory
    {
        public static UserNSNameSequence parse(final XMLStreamReader reader) throws Exception
        {
            final UserNSNameSequence object = new UserNSNameSequence();
            try
            {
                while (!reader.isStartElement() && !reader.isEndElement())
                {
                    reader.next();
                }

                if (reader.isStartElement() && new QName("", "userName").equals(reader.getName()))
                {
                    final String content = reader.getElementText();
                    object.setUserName(ConverterUtil.convertToString(content));
                    reader.next();
                }

                while (!reader.isStartElement() && !reader.isEndElement())
                {
                    reader.next();
                }
                if (reader.isStartElement() && new QName("", "userNamespace").equals(reader.getName()))
                {
                    final String content = reader.getElementText();
                    object.setUserNamespace(ConverterUtil.convertToString(content));
                    reader.next();
                }

                while (!reader.isStartElement() && !reader.isEndElement())
                {
                    reader.next();
                }
            }
            catch (final XMLStreamException e)
            {
                throw new Exception(e);
            }

            return object;
        }
    }
}


text:
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using Utf8Json;

namespace AzureFunctionsIntroduction
{
    public static class HttpRequestMessageExtensions
    {
        // Hack : GetQueryNameValuePairs not yet umplemented with AzureFunctions v2 default.
        public static Dictionary<string, StringValues> GetQueryNameValuePairs(this HttpRequestMessage req)
        {
            return Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(req.RequestUri.Query);
        }

        // Hack : existing CreateResponse throw exception. Issue : https://github.com/Azure/azure-webjobs-sdk/issues/1492
        /// <summary>
        /// Custom CreateResponse to for sugar syntax...
        /// </summary>
        /// <param name="res"></param>
        /// <param name="statusCode"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static HttpResponseMessage CreateResponse(this HttpRequestMessage res, HttpStatusCode statusCode, string value)
        {
            if (res == null) throw new ArgumentNullException(nameof(res));
            return new HttpResponseMessage()
            {
                StatusCode = statusCode,
                Content = new StringContent(value),
            };
        }

        /// <summary>
        /// Custom CreateResponse to for sugar syntax...
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="req"></param>
        /// <param name="statusCode"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static HttpResponseMessage CreateResponse<T>(this HttpRequestMessage req, HttpStatusCode statusCode, T value) where T : class
        {
            if (req == null) throw new ArgumentNullException(nameof(req));

            return new HttpResponseMessage()
            {
                StatusCode = statusCode,
                Content = new StringContent(JsonSerializer.ToJsonString<T>(value)),
            };
        }

        /// <summary>
        /// Custom CreateErrorResponse to for sugar syntax... no concider for HttpError
        /// </summary>
        /// <param name="req"></param>
        /// <param name="statusCode"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static HttpResponseMessage CreateErrorResponse(this HttpRequestMessage req, HttpStatusCode statusCode, string value)
        {
            if (req == null) throw new ArgumentNullException(nameof(req));

            return new HttpResponseMessage()
            {
                StatusCode = statusCode,
                Content = new StringContent(value),
            };
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
#pragma once
#include <aws/location/LocationService_EXPORTS.h>
#include <aws/location/LocationServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace LocationService
{
namespace Model
{

  /**
   */
  class AWS_LOCATIONSERVICE_API ListRouteCalculatorsRequest : public LocationServiceRequest
  {
  public:
    ListRouteCalculatorsRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "ListRouteCalculators"; }

    Aws::String SerializePayload() const override;

    /**
     *
An optional maximum number of results returned in a single call.

     *
Default Value: 100

     */
    inline int GetMaxResults() const{ return m_maxResults; }

    /**
     *
An optional maximum number of results returned in a single call.

     *
Default Value: 100

     */
    inline bool MaxResultsHasBeenSet() const { return m_maxResultsHasBeenSet; }

    /**
     *
An optional maximum number of results returned in a single call.

     *
Default Value: 100

     */
    inline void SetMaxResults(int value) { m_maxResultsHasBeenSet = true; m_maxResults = value; }

    /**
     *
An optional maximum number of results returned in a single call.

     *
Default Value: 100

     */
    inline ListRouteCalculatorsRequest& WithMaxResults(int value) { SetMaxResults(value); return *this;}

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline const Aws::String& GetNextToken() const{ return m_nextToken; }

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline bool NextTokenHasBeenSet() const { return m_nextTokenHasBeenSet; }

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = std::move(value); }

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline ListRouteCalculatorsRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline ListRouteCalculatorsRequest& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}

    /**
     *
The pagination token specifying which page of results to return in the
     * response. If no token is provided, the default page is the first page.

     *
Default Value: null

     */
    inline ListRouteCalculatorsRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}

  private:

    int m_maxResults;
    bool m_maxResultsHasBeenSet = false;

    Aws::String m_nextToken;
    bool m_nextTokenHasBeenSet = false;
  };

} // namespace Model
} // namespace LocationService
} // namespace Aws


text:
from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy(app)

lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'


text:
class DetectRepositoryLanguagesWorker
  include ApplicationWorker
  include ExceptionBacktrace
  include ExclusiveLeaseGuard

  sidekiq_options retry: 1

  LEASE_TIMEOUT = 300

  attr_reader :project

  # rubocop: disable CodeReuse/ActiveRecord
  def perform(project_id, user_id)
    @project = Project.find_by(id: project_id)
    user = User.find_by(id: user_id)
    return unless project && user

    try_obtain_lease do
      ::Projects::DetectRepositoryLanguagesService.new(project, user).execute
    end
  end
  # rubocop: enable CodeReuse/ActiveRecord

  private

  def lease_timeout
    LEASE_TIMEOUT
  end

  def lease_key
    "gitlab:detect_repository_languages:#{project.id}"
  end
end


text:
Install MUI, the world's most popular React UI framework.

MUI is available as an [npm package](https://www.npmjs.com/package/@mui/material).

## npm

To install and save in your `package.json` dependencies, run:

```sh
// with npm
npm install @mui/material @emotion/react @emotion/styled

// with yarn
yarn add @mui/material @emotion/react @emotion/styled
```

Please note that [react](https://www.npmjs.com/package/react) >= 17.0.0 and [react-dom](https://www.npmjs.com/package/react-dom) >= 17.0.0 are peer dependencies.

MUI is using [emotion](https://emotion.sh/docs/introduction) as a styling engine by default. If you want to use [`styled-components`](https://styled-components.com/) instead, run:

```sh
// with npm
npm install @mui/material @mui/styled-engine-sc styled-components

// with yarn
yarn add @mui/material @mui/styled-engine-sc styled-components
```

> 💡 Take a look at the [Styled Engine guide](/guides/styled-engine/) for more information about how to configure `styled-components` as the style engine.

## Roboto font

MUI was designed with the [Roboto](https://fonts.google.com/specimen/Roboto)
font in mind. So be sure to follow [these instructions](/components/typography/#general).
For instance, via Google Web Fonts:

```html
<link
  rel="stylesheet"
  href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
```

## Font icons

To use the font `Icon` component, you must first add the [Material icons](https://fonts.google.com/icons) font.
Here are [some instructions](/components/icons/#font-icons)
on how to do so.
For instance, via Google Web Fonts:

```html
<link
  rel="stylesheet"
  href="https://fonts.googleapis.com/icon?family=Material+Icons"
/>
```

## SVG icons

In order to use prebuilt SVG Material icons, such as those found in the [icons demos](/components/icons/)
you must first install the [@mui/icons-material](https://www.npmjs.com/package/@mui/icons-material) package:

```sh
// with npm
npm install @mui/icons-material

// with yarn
yarn add @mui/icons-material
```

## CDN

You can start using MUI with minimal Front-end infrastructure,
which is great for prototyping.

Two Universal Module Definition (**UMD**) files are provided:

- one for development: https://unpkg.com/@mui/material@latest/umd/material-ui.development.js
- one for production: https://unpkg.com/@mui/material@latest/umd/material-ui.production.min.js

You can follow [this CDN example](https://github.com/mui/material-ui/tree/master/examples/cdn) to quickly get started.

⚠ Using this approach in **production** is **discouraged** though -
the client has to download the entire library, regardless of which components are actually used,
affecting performance and bandwidth utilization.

⚠ The UMD links are using the `latest` tag to point to the latest version of the library.
This pointer is **unstable**, it shifts as we release new versions.
You should consider pointing to a specific version, such as [v5.0.0](https://unpkg.com/@mui/material@5.0.0/umd/material-ui.development.js).

## Design resources

A set of reusable components for design tools is available, designed to match the React components and to help you craft great products:

- [Figma](https://mui.com/store/items/figma-react/?utm_source=docs&utm_medium=referral&utm_campaign=installation-figma): A large UI kit with over 600 handcrafted MUI components.
- [Adobe XD](https://mui.com/store/items/adobe-xd-react/?utm_source=docs&utm_medium=referral&utm_campaign=installation-adobe-xd): A large UI kit with over 600 handcrafted MUI components.
- [Sketch](https://mui.com/store/items/sketch-react/?utm_source=docs&utm_medium=referral&utm_campaign=installation-sketch): A large UI kit with over 600 handcrafted MUI symbols.
- [UXPin](https://www.uxpin.com/merge/mui-library): A large UI kit of MUI components. The design tool renders the components in a web runtime. It uses the same React implementation as your production environment.


text:
#ifndef GRAPHICS_NODE_H
#define GRAPHICS_NODE_H

#include <QtCore/QRectF>
#include <QtCore/QPointF>
#include <QtCore/QVariant>
#include <QtCore/QString>

#include "graphicsnodedefs.hpp"

class QWidget;
class QGraphicsSceneMouseEvent;
class QGraphicsTextItem;
class GraphicsDirectedEdge;
class GraphicsNodeSocket;
class QAbstractItemModel;

class QNodeEditorSocketModel;

class GraphicsNodePrivate;

class Q_DECL_EXPORT GraphicsNode : public QObject
{
    friend class QNodeEditorSocketModel; // To update them
    friend class QNodeEditorSocketModelPrivate; // For creating GraphicsNodes
    friend class NodeWrapper; // To delete it
    Q_OBJECT

public:
    QGraphicsItem *graphicsItem() const;

    QSizeF size() const;
    QRectF rect() const;

    void setTitle(const QString &title);

    QString title() const;

    QBrush background() const;
    QPen foreground() const;

    void setBackground(const QBrush& brush);
    void setBackground(const QString& brush);
    void setForeground(const QPen& pen);
    void setForeground(const QColor& pen);
    void setForeground(const QString& pen);

    void setDecoration(const QVariant& deco);

    Q_INVOKABLE QAbstractItemModel *sinkModel() const;
    Q_INVOKABLE QAbstractItemModel *sourceModel() const;

    const QModelIndex socketIndex(const QString& name) const;

    void setSize(const qreal width, const qreal height);
    void setSize(const QSizeF size);
    void setSize(const QPointF size);

    void setRect(const qreal x, const qreal y, const qreal width, const qreal height);
    void setRect(const QRectF size);

    QModelIndex index() const;
    QAbstractItemModel* model() const;

    /**
        * set a regular QWidget as central widget
        */
    void setCentralWidget(QWidget *widget);

private:
    explicit GraphicsNode(QNodeEditorSocketModel* model, const QPersistentModelIndex& index, QGraphicsItem *parent = nullptr);
    virtual ~GraphicsNode();

    void update();
    void setIndex(const QModelIndex& idx);//FIXME HACK this is a workaround for a bug elsewhere

    GraphicsNodePrivate* d_ptr;
    Q_DECLARE_PRIVATE(GraphicsNode)
};

Q_DECLARE_METATYPE(GraphicsNode*)

#endif //GRAPHICS_NODE_H


text:
'use strict';

angular.module('MenuApp.restaurant-service', ['MenuApp.restaurant'])
    .service('RestaurantService', ['$http', function($http) {
        var directive;
        directive = this;
        this.currentView = 'alpha';

        this.enableAlphaView = function() {
            directive.currentView = 'alpha';
            this.navigationItems = this.letters;
        };

        this.enableCategoryView = function() {
            directive.currentView = 'category';
            this.navigationItems = this.categories;
        }

        this.fetchRestaurants = function(success) {
            $http.get('data.php').then(function(response) {
                directive.restaurants = response.data.restaurants;
                directive.letters = response.data.letters;
                directive.categories = response.data.categories;

                if (directive.currentView == 'alpha') {
                    directive.navigationItems = directive.letters;
                } else {
                    directive.navigationItems = directive.categories;
                }

                if (success) {
                    success.apply(directive, [response]);
                }
            });
        }
    }]);


text:
define(function(require) {
    'use strict';

    var _ = require('underscore');
    var moment = require('moment-timezone');
    var origTz = moment.fn.tz;

    /**
     * Getter/Setter for moment's timezone
     *
     * @param {string} name of timezone
     * @param {boolean=} keepTime flag if datetime have to be preserved as it is on timezone change
     * @returns {Moment|string|undefined} updated moment object or timezone name (if it is defined)
     */
    moment.fn.tz = function(name, keepTime) {
        if (name) {
            this._z = moment.tz.zone(name);
            if (this._z && keepTime) {
                var dateTimeString;
                var dateTimeFormat = 'YYYY-MM-DD[T]HH:mm:ss';
                if (this.hasOwnProperty('_tzm')) {
                    dateTimeString = this.add(-this._tzm , 'minutes').clone().utc().format(dateTimeFormat);
                    delete this._tzm;
                } else {
                    dateTimeString = this.format(dateTimeFormat);
                }
                var momentWithCorrectTZ = moment.tz(dateTimeString, dateTimeFormat, true, name);
                _.extend(this, _.pick(momentWithCorrectTZ, '_d', '_isUTC', '_offset'));
            } else {
                origTz.call(this, name);
            }
            return this;
        }
        if (this._z) { return this._z.name; }
    };

    return moment;
});


text:
from __future__ import absolute_import, division, print_function, unicode_literals

from azure.common import AzureHttpError
from .azure_common import BaseTest, arm_template
from c7n_azure.session import Session
from c7n_azure.storage_utils import StorageUtilities
from mock import patch
from c7n_azure.actions.notify import Notify
import re
from c7n.utils import local_session

class NotifyTest(BaseTest):
    def setUp(self):
        super(NotifyTest, self).setUp()
        self.session = Session()

    def test_notify_schema_validate(self):
        with self.sign_out_patch():
            p = self.load_policy({
                'name': 'test-notify-for-keyvault',
                'resource': 'azure.keyvault',
                'actions': [
                    {'type': 'notify',
                     'template': 'default',
                     'priority_header': '2',
                     'subject': 'testing notify action',
                     'to': ['user@domain.com'],
                     'transport':
                         {'type': 'asq',
                          'queue': ''}
                     }
                ]}, validate=True)
            self.assertTrue(p)

    @arm_template('keyvault.json')
    def test_notify_though_storage_queue(self):
        account = self.setup_account()

        # Create queue, make sure it is empty
        queue_url = "https://" + account.name + ".queue.core.windows.net/testnotify"
        queue, name = StorageUtilities.get_queue_client_by_uri(queue_url, self.session)
        queue.clear_messages(name)

        p = self.load_policy({
            'name': 'test-notify-for-keyvault',
            'resource': 'azure.keyvault',
            'filters': [
                {'type': 'value',
                 'key': 'name',
                 'op': 'glob',
                 'value_type': 'normalize',
                 'value': 'cckeyvault1*'}],
            'actions': [
                {'type': 'notify',
                 'template': 'default',
                 'priority_header': '2',
                 'subject': 'testing notify action',
                 'to': ['user@domain.com'],
                 'transport':
                     {'type': 'asq',
                      'queue': queue_url}
                 }
            ]
        })
        resources = p.run()
        self.assertEqual(len(resources), 1)

        # Pull messages, should be 1
        messages = StorageUtilities.get_queue_messages(queue, name)
        self.assertEqual(len(messages), 1)

    @patch('c7n_azure.storage_utils.StorageUtilities.put_queue_message')
    @patch('c7n_azure.storage_utils.StorageUtilities.get_queue_client_by_uri')
    @patch('logging.Logger.error')
    def test_access_error(self,
                          logger_mock,
                          get_queue_client_by_uri,
                          put_queue_message):
        put_queue_message.side_effect = AzureHttpError('forbidden', 403)
        get_queue_client_by_uri.return_value = 'service', 'name'

        action = Notify()

        action.send_to_azure_queue("url", "message", local_session(Session))

        args, _ = logger_mock.call_args

        self.assertIsNotNone(re.match("Access Error*", args[0]))

    @patch('c7n_azure.storage_utils.StorageUtilities.put_queue_message')
    @patch('c7n_azure.storage_utils.StorageUtilities.get_queue_client_by_uri')
    @patch('logging.Logger.error')
    def test_error_putting_to_queue(self,
                                    logger_mock,
                                    get_queue_client_by_uri,
                                    put_queue_message):
        put_queue_message.side_effect = AzureHttpError('not found', 404)
        get_queue_client_by_uri.return_value = 'service', 'name'

        action = Notify()

        action.send_to_azure_queue("url", "message", local_session(Session))

        args, _ = logger_mock.call_args

        self.assertIsNone(re.match("Access Error*", args[0]))
        self.assertIsNotNone(re.match("Error*", args[0]))


text:
namespace ArmyOfCreatures.Console
{
    using System;
    using System.Globalization;
    using System.Threading;

    using ArmyOfCreatures.Console.Commands;
    using ArmyOfCreatures.Extended;
    using ArmyOfCreatures.Logic;
    using ArmyOfCreatures.Logic.Battles;

    // No comments for you! It was hard to write so it should be hard to read.
    public static class Program
    {
        public static void Main()
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            ICreaturesFactory creaturesFactory = GetCreaturesFactory();
            ILogger logger = new ConsoleLogger();
            IBattleManager battleManager = GetBattleManager(creaturesFactory, logger);

            // Process commands
            ICommandManager commandManager = new CommandManager();
            while (true)
            {
                var commandLine = Console.ReadLine();
                commandManager.ProcessCommand(commandLine, battleManager);
            }
        }

        private static IBattleManager GetBattleManager(ICreaturesFactory creaturesFactory, ILogger logger)
        {
            // You are allowed to add, change and remove code here
            return new BattleManagerForThree(creaturesFactory, logger);
        }

        private static ICreaturesFactory GetCreaturesFactory()
        {
            // You are allowed to add, change and remove code here
            return new CreaturesFactory();
        }
    }
}


text:
volsurface
==========

Visualize volatility surface

# Data

There are two data sources under `data/` folder.

# R Output for SPX options EOD data on 12/31/2013

The quality is worse than what Mr. Gatheral has. There isn't enough resolution (or interpolation!?).
But you can more or less see the volatility smile and skew.

* Source 1

![Surface Plot2](volatility_surface_3d_1.png?raw=true)

* Source 2

![Surface Plot2](volatility_surface_3d_2.png?raw=true)

# References

http://faculty.baruch.cuny.edu/jgatheral/ImpliedVolatilitySurface.pdf


text:
/* pmwinmm.c -- system specific definitions */

#include "windows.h"
#include "mmsystem.h"
#include "portmidi.h"
#include "pminternal.h"
#include "pmwinmm.h"
#include "string.h"
#include "porttime.h"

/* asserts used to verify portMidi code logic is sound; later may want
    something more graceful */
#include <assert.h>

#ifdef DEBUG
/* this printf stuff really important for debugging client app w/host errors.
    probably want to do something else besides read/write from/to console
    for portability, however */
#define STRING_MAX 80
#include "stdio.h"
#endif

#define streql(x, y) (strcmp(x, y) == 0)

#define MIDI_SYSEX      0xf0
#define MIDI_EOX        0xf7

/* callback routines */
static void CALLBACK winmm_in_callback(HMIDIIN hMidiIn,
        WORD wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);
static void CALLBACK winmm_streamout_callback(HMIDIOUT hmo, UINT wMsg,
        DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);
static void CALLBACK winmm_out_callback(HMIDIOUT hmo, UINT wMsg,
    DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);

extern pm_fns_node pm_winmm_in_dictionary;
extern pm_fns_node pm_winmm_out_dictionary;

static void winmm_out_delete(PmInternal *midi); /* forward reference */

#define SYSEX_BYTES_PER_BUFFER 32

#define MIDIHDR_SIZE(x) ((x) + sizeof(MIDIHDR) + sizeof(MIDIEVENT))

/*
==============================================================================
win32 mmedia system specific structure passed to midi callbacks
==============================================================================
*/

/* global winmm device info */
MIDIINCAPS *midi_in_caps = NULL;
MIDIINCAPS midi_in_mapper_caps;
UINT midi_num_inputs = 0;
MIDIOUTCAPS *midi_out_caps = NULL;
MIDIOUTCAPS midi_out_mapper_caps;
UINT midi_num_outputs = 0;

/* per device info */
typedef struct midiwinmm_struct {

    union {
        HMIDISTRM stream;   /* windows handle for stream */
        HMIDIOUT out;       /* windows handle for out calls */
        HMIDIIN in;         /* windows handle for in calls */
    } handle;

    /* midi output messages are sent in these buffers, which are allocated
     * in a round-robin fashion, using next_buffer as an index
     */
    LPMIDIHDR *buffers;     /* pool of buffers for midi in or out data */
    int num_buffers;        /* how many buffers */
    int next_buffer;        /* index of next buffer to send */
    HANDLE buffer_signal;   /* used to wait for buffer to become free */

    unsigned long last_time;    /* last output time */
    int first_message;          /* flag: treat first message differently */
    int sysex_mode;             /* middle of sending sysex */
    unsigned long sysex_word;   /* accumulate data when receiving sysex */
    unsigned int sysex_byte_count;/* count how many received or to send */
    LPMIDIHDR hdr;              /* the message accumulating sysex to send */
    unsigned long sync_time;    /* when did we last determine delta? */
    long delta;                 /* difference between stream time and
                                   real time */
    int error;                  /* host error from doing port midi call */
    int callback_error;         /* host error from midi in or out callback */
} midiwinmm_node, *midiwinmm_type;

/*
=============================================================================
general MIDI device queries
=============================================================================
*/
static void pm_winmm_general_inputs()
{
    UINT i;
    WORD wRtn;
    midi_num_inputs = midiInGetNumDevs();
    midi_in_caps = pm_alloc(sizeof(MIDIINCAPS) * midi_num_inputs);

    if (midi_in_caps == NULL) {
        // if you can't open a particular system-level midi interface
        // (such as winmm), we just consider that system or API to be
        // unavailable and move on without reporting an error. This
        // may be the wrong thing to do, especially in this case.
        return;
    }

    for (i = 0; i < midi_num_inputs; i++) {
        wRtn = midiInGetDevCaps(i, (LPMIDIINCAPS) &midi_in_caps[i],
                                sizeof(MIDIINCAPS));
        if (wRtn == MMSYSERR_NOERROR) {
            /* ignore errors here -- if pm_descriptor_max is exceeded, some
               devices will not be accessible. */
            pm_add_device("MMSystem", midi_in_caps[i].szPname, TRUE,
                          (void *) i, &pm_winmm_in_dictionary);
        }
    }
}

static void pm_winmm_mapper_input()
{
    WORD wRtn;
    /* Note: if MIDIMAPPER opened as input (documentation implies you
        can, but current system fails to retrieve input mapper
        capabilities) then you still should retrieve some formof
        setup info. */
    wRtn = midiInGetDevCaps((UINT) MIDIMAPPER,
               (LPMIDIINCAPS) &midi_in_mapper_caps, sizeof(MIDIINCAPS));
    if (wRtn == MMSYSERR_NOERROR) {
        pm_add_device("MMSystem", midi_in_mapper_caps.szPname, TRUE,
                      (void *) MIDIMAPPER, &pm_winmm_in_dictionary);
    }
}

static void pm_winmm_general_outputs()
{
    UINT i;
    DWORD wRtn;
    midi_num_outputs = midiOutGetNumDevs();
    midi_out_caps = pm_alloc( sizeof(MIDIOUTCAPS) * midi_num_outputs );

    if (midi_out_caps == NULL) {
        // no error is reported -- see pm_winmm_general_inputs
        return;
    }

    for (i = 0; i < midi_num_outputs; i++) {
        wRtn = midiOutGetDevCaps(i, (LPMIDIOUTCAPS) &midi_out_caps[i],
                                 sizeof(MIDIOUTCAPS));
        if (wRtn == MMSYSERR_NOERROR) {
            pm_add_device("MMSystem", midi_out_caps[i].szPname, FALSE,
                      (void *) i, &pm_winmm_out_dictionary);
        }
    }
}

static void pm_winmm_mapper_output()
{
    WORD wRtn;
    /* Note: if MIDIMAPPER opened as output (pseudo MIDI device
        maps device independent messages into device dependant ones,
        via NT midimapper program) you still should get some setup info */
    wRtn = midiOutGetDevCaps((UINT) MIDIMAPPER,(LPMIDIOUTCAPS)
                              &midi_out_mapper_caps,sizeof(MIDIOUTCAPS));
    if (wRtn == MMSYSERR_NOERROR) {
        pm_add_device("MMSystem", midi_out_mapper_caps.szPname, FALSE,
                  (void *) MIDIMAPPER, &pm_winmm_out_dictionary);
    }
}

/*
=========================================================================================
host error handling
=========================================================================================
*/
static unsigned int winmm_has_host_error(PmInternal * midi)
{
    midiwinmm_type m = (midiwinmm_type)midi->descriptor;
    return m->callback_error || m->error;
}

/* str_copy_len -- like strcat, but won't overrun the destination string */
/*
 * returns length of resulting string
 */
static int str_copy_len(char *dst, char *src, int len)
{
    strncpy(dst, src, len);
    /* just in case suffex is greater then len, terminate with zero */
    dst[len - 1] = 0;
    return strlen(dst);
}

static void winmm_get_host_error(PmInternal * midi, char * msg, UINT len)
{
    /* precondition: midi != NULL */
    midiwinmm_node * m = (midiwinmm_node *) midi->descriptor;
    char *hdr1 = "Host error: ";
    char *hdr2 = "Host callback error: ";

    msg[0] = 0; /* initialize result string to empty */

    if (descriptors[midi->device_id].pub.input) {
        /* input and output use different winmm API calls */
        if (m) { /* make sure there is an open device to examine */
            if (m->error != MMSYSERR_NOERROR) {
                int n = str_copy_len(msg, hdr1, len);
                /* read and record host error */
                int err = midiInGetErrorText(m->error, msg + n, len - n);
                assert(err == MMSYSERR_NOERROR);
                m->error = MMSYSERR_NOERROR;
            } else if (m->callback_error != MMSYSERR_NOERROR) {
                int n = str_copy_len(msg, hdr2, len);
                int err = midiInGetErrorText(m->callback_error, msg + n,
                                             len - n);
                assert(err == MMSYSERR_NOERROR);
                m->callback_error = MMSYSERR_NOERROR;
            }
        }
    } else { /* output port */
        if (m) {
            if (m->error != MMSYSERR_NOERROR) {
                int n = str_copy_len(msg, hdr1, len);
                int err = midiOutGetErrorText(m->error, msg + n, len - n);
                assert(err == MMSYSERR_NOERROR);
                m->error = MMSYSERR_NOERROR;
            } else if (m->callback_error != MMSYSERR_NOERROR) {
                int n = str_copy_len(msg, hdr2, len);
                int err = midiOutGetErrorText(m->callback_error, msg + n,
                                              len = n);
                assert(err == MMSYSERR_NOERROR);
                m->callback_error = MMSYSERR_NOERROR;
            }
        }
    }
}

/*
=============================================================================
buffer handling
=============================================================================
*/
static MIDIHDR *allocate_buffer(long data_size)
{
    /* we're actually allocating slightly more than data_size because one more word of
     * data is contained in MIDIEVENT. We include the size of MIDIEVENT because we need
     * the MIDIEVENT header in addition to the data
     */
    LPMIDIHDR hdr = (LPMIDIHDR) pm_alloc(MIDIHDR_SIZE(data_size));
    MIDIEVENT *evt;
    if (!hdr) return NULL;
    evt = (MIDIEVENT *) (hdr + 1); /* place MIDIEVENT after header */
    hdr->lpData = (LPSTR) evt;
    hdr->dwBufferLength = sizeof(MIDIEVENT) + data_size;
    hdr->dwFlags = 0;
    hdr->dwUser = 0;
    return hdr;
}

static PmError allocate_buffers(midiwinmm_type m, long data_size, long count)
{
    PmError rslt = pmNoError;
    /* buffers is an array of count pointers to MIDIHDR/MIDIEVENT struct */
    m->buffers = (LPMIDIHDR *) pm_alloc(sizeof(LPMIDIHDR) * count);
    if (!m->buffers) return pmInsufficientMemory;
    m->num_buffers = count;
    while (count > 0) {
        LPMIDIHDR hdr = allocate_buffer(data_size);
        if (!hdr) rslt = pmInsufficientMemory;
        count--;
        m->buffers[count] = hdr; /* this may be NULL if allocation fails */
    }
    return rslt;
}

static LPMIDIHDR get_free_output_buffer(PmInternal *midi)
{
    LPMIDIHDR r = NULL;
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    if (!m->buffers) {
        if (allocate_buffers(m, PM_DEFAULT_SYSEX_BUFFER_SIZE, 2)) {
            return NULL;
        }
    }
    /* busy wait until we find a free buffer */
    while (TRUE) {
        int i;
        for (i = 0; i < m->num_buffers; i++) {
            m->next_buffer++;
            if (m->next_buffer >= m->num_buffers) m->next_buffer = 0;
            r = m->buffers[m->next_buffer];
            if ((r->dwFlags & MHDR_PREPARED) == 0) goto found_buffer;
        }
        /* after scanning every buffer and not finding anything, block */
        WaitForSingleObject(m->buffer_signal, INFINITE);
    }
found_buffer:
    r->dwBytesRecorded = 0;
    m->error = midiOutPrepareHeader(m->handle.out, r, sizeof(MIDIHDR));
    return r;
}

/*
=========================================================================================
begin midi input implementation
=========================================================================================
*/

static PmError winmm_in_open(PmInternal *midi, void *driverInfo)
{
    DWORD dwDevice;
    int i = midi->device_id;
    midiwinmm_type m;
    LPMIDIHDR hdr;
    dwDevice = (DWORD) descriptors[i].descriptor;

    /* create system dependent device data */
    m = (midiwinmm_type) pm_alloc(sizeof(midiwinmm_node)); /* create */
    midi->descriptor = m;
    if (!m) goto no_memory;
    m->handle.in = NULL;
    m->buffers = NULL;
    m->num_buffers = 0;
    m->next_buffer = 0;
    m->last_time = 0;
    m->first_message = TRUE; /* not used for input */
    m->sysex_mode = FALSE;
    m->sysex_word = 0;
    m->sysex_byte_count = 0;
    m->sync_time = 0;
    m->delta = 0;
    m->error = MMSYSERR_NOERROR;
    m->callback_error = MMSYSERR_NOERROR;

    /* open device */
    pm_hosterror = midiInOpen(&(m->handle.in), /* input device handle */
                      dwDevice, /* device ID */
                      (DWORD) winmm_in_callback, /* callback address */
                      (DWORD) midi, /* callback instance data */
                      CALLBACK_FUNCTION); /* callback is a procedure */
    if (pm_hosterror) goto free_descriptor;

    /* allocate first buffer for sysex data */
    hdr = allocate_buffer(PM_DEFAULT_SYSEX_BUFFER_SIZE);
    if (!hdr) goto close_device;
    pm_hosterror = midiInPrepareHeader(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) {
        pm_free(hdr);
        goto close_device;
    }
    pm_hosterror = midiInAddBuffer(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) goto close_device;

    /* allocate second buffer */
    hdr = allocate_buffer(PM_DEFAULT_SYSEX_BUFFER_SIZE);
    if (!hdr) goto close_device;
    pm_hosterror = midiInPrepareHeader(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) {
        pm_free(hdr);
        goto reset_device; /* because first buffer was added */
    }
    pm_hosterror = midiInAddBuffer(m->handle.in, hdr, sizeof(MIDIHDR));
    if (pm_hosterror) goto reset_device;

    /* start device */
    pm_hosterror = midiInStart(m->handle.in);
    if (pm_hosterror) goto reset_device;
    return pmNoError;

    /* undo steps leading up to the detected error */
reset_device:
    /* ignore return code (we already have an error to report) */
    midiInReset(m->handle.in);
close_device:
    midiInClose(m->handle.in); /* ignore return code */
free_descriptor:
    midi->descriptor = NULL;
    pm_free(m);
no_memory:
    if (pm_hosterror) {
        int err = midiInGetErrorText(pm_hosterror, (char *) pm_hosterror_text,
                                     PM_HOST_ERROR_MSG_LEN);
        assert(err == MMSYSERR_NOERROR);
        return pmHostError;
    }
    /* if !pm_hosterror, then the error must be pmInsufficientMemory */
    return pmInsufficientMemory;
    /* note: if we return an error code, the device will be
       closed and memory will be freed. It's up to the caller
       to free the parameter midi */
}

/* winmm_in_close -- close an open midi input device */
/*
 * assume midi is non-null (checked by caller)
 */
static PmError winmm_in_close(PmInternal *midi)
{
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    if (!m) return pmBadPtr;
    /* device to close */
    if (pm_hosterror = midiInStop(m->handle.in)) {
        midiInReset(m->handle.in); /* try to reset and close port */
        midiInClose(m->handle.in);
    } else if (pm_hosterror = midiInReset(m->handle.in)) {
        midiInClose(m->handle.in); /* best effort to close midi port */
    } else {
        pm_hosterror = midiInClose(m->handle.in);
    }
    midi->descriptor = NULL;
    pm_free(m); /* delete */
    if (pm_hosterror) {
        int err = midiInGetErrorText(pm_hosterror, (char *) pm_hosterror_text,
                                     PM_HOST_ERROR_MSG_LEN);
        assert(err == MMSYSERR_NOERROR);
        return pmHostError;
    }
    return pmNoError;
}

/* Callback function executed via midiInput SW interrupt (via midiInOpen). */
static void FAR PASCAL winmm_in_callback(
     HMIDIIN hMidiIn,   /* midiInput device Handle */
     WORD wMsg,         /* midi msg */
     DWORD dwInstance,  /* application data */
     DWORD dwParam1,    /* MIDI data */
     DWORD dwParam2)    /* device timestamp (wrt most recent midiInStart) */
{
    static int entry = 0;
    PmInternal *midi = (PmInternal *) dwInstance;
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;

    if (++entry > 1) {
        assert(FALSE);
    }

    /* for simplicity, this logic perhaps overly conservative */
    /* note also that this might leak memory if buffers are being
       returned as a result of midiInReset */
    if (m->callback_error) {
        entry--;
        return;
    }

    switch (wMsg) {
      case MIM_DATA: {
        /* dwParam1 is MIDI data received, packed into DWORD w/ 1st byte of
                message LOB;
           dwParam2 is time message received by input device driver, specified
            in [ms] from when midiInStart called.
           each message is expanded to include the status byte */

        long new_driver_time = dwParam2;

        if ((dwParam1 & 0x80) == 0) {
            /* not a status byte -- ignore it. This happens running the
               sysex.c test under Win2K with MidiMan USB 1x1 interface.
               Is it a driver bug or a Win32 bug? If not, there's a bug
               here somewhere. -RBD
             */
        } else { /* data to process */
            PmEvent event;
            if (midi->time_proc)
                dwParam2 = (*midi->time_proc)(midi->time_info);
            event.timestamp = dwParam2;
            event.message = dwParam1;
            pm_read_short(midi, &event);
        }
        break;
      }
      case MIM_LONGDATA: {
        MIDIHDR *lpMidiHdr = (MIDIHDR *) dwParam1;
        unsigned char *data = lpMidiHdr->lpData;
        unsigned int i = 0;
        long size = sizeof(MIDIHDR) + lpMidiHdr->dwBufferLength;
        /* ignore sysex data, but free returned buffers */
        if (lpMidiHdr->dwBytesRecorded > 0 &&
            midi->filters & PM_FILT_SYSEX) {
                m->callback_error = midiInAddBuffer(hMidiIn, lpMidiHdr,
                                                    sizeof(MIDIHDR));
                break;
        }
        if (midi->time_proc)
            dwParam2 = (*midi->time_proc)(midi->time_info);

        while (i < lpMidiHdr->dwBytesRecorded) {
            /* collect bytes from *data into a word */
            pm_read_byte(midi, *data, dwParam2);
            data++;
            i++;
        }
        /* when a device is closed, the pending MIM_LONGDATA buffers are
           returned to this callback with dwBytesRecorded == 0. In this
           case, we do not want to send them back to the interface (if
           we do, the interface will not close, and Windows OS may hang). */
        if (lpMidiHdr->dwBytesRecorded > 0) {
            m->callback_error = midiInAddBuffer(hMidiIn, lpMidiHdr,
                                                sizeof(MIDIHDR));
        } else {
            pm_free(lpMidiHdr);
        }
        break;
      }
      case MIM_OPEN: /* fall thru */
      case MIM_CLOSE:
      case MIM_ERROR:
      case MIM_LONGERROR:
      default:
        break;
    }
    entry--;
}

/*
=========================================================================================
begin midi output implementation
=========================================================================================
*/

/* begin helper routines used by midiOutStream interface */

/* add_to_buffer -- adds timestamped short msg to buffer, returns fullp */
static int add_to_buffer(midiwinmm_type m, LPMIDIHDR hdr,
                          unsigned long delta, unsigned long msg)
{
    unsigned long *ptr = (unsigned long *)
        (hdr->lpData + hdr->dwBytesRecorded);
    *ptr++ = delta; /* dwDeltaTime */
    *ptr++ = 0;     /* dwStream */
    *ptr++ = msg;   /* dwEvent */
    hdr->dwBytesRecorded += 3 * sizeof(long);
    /* if the addition of three more words (a message) would extend beyond
       the buffer length, then return TRUE (full)
     */
    return hdr->dwBytesRecorded + 3 * sizeof(long) > hdr->dwBufferLength;
}

#ifdef GARBAGE
static void start_sysex_buffer(LPMIDIHDR hdr, unsigned long delta)
{
    unsigned long *ptr = (unsigned long *) hdr->lpData;
    *ptr++ = delta;
    *ptr++ = 0;
    *ptr = MEVT_F_LONG;
    hdr->dwBytesRecorded = 3 * sizeof(long);
}

static int add_byte_to_buffer(midiwinmm_type m, LPMIDIHDR hdr,
                                  unsigned char midi_byte)
{
 allocate message if hdr is null
 send message if it is full
 add byte to non-full message
    unsigned char *ptr = (unsigned char *) (hdr->lpData + hdr->dwBytesRecorded);
    *ptr = midi_byte;
    return ++hdr->dwBytesRecorded >= hdr->dwBufferLength;
}
#endif

static PmTimestamp pm_time_get(midiwinmm_type m)
{
    MMTIME mmtime;
    MMRESULT wRtn;
    mmtime.wType = TIME_TICKS;
    mmtime.u.ticks = 0;
    wRtn = midiStreamPosition(m->handle.stream, &mmtime, sizeof(mmtime));
    assert(wRtn == MMSYSERR_NOERROR);
    return mmtime.u.ticks;
}

#ifdef GARBAGE
static unsigned long synchronize(PmInternal *midi, midiwinmm_type m)
{
    unsigned long pm_stream_time_2 = pm_time_get(m);
    unsigned long real_time;
    unsigned long pm_stream_time;
    /* figure out the time */
    do {
        /* read real_time between two reads of stream time */
        pm_stream_time = pm_stream_time_2;
        real_time = (*midi->time_proc)(midi->time_info);
        pm_stream_time_2 = pm_time_get(m);
        /* repeat if more than 1ms elapsed */
    } while (pm_stream_time_2 > pm_stream_time + 1);
    m->delta = pm_stream_time - real_time;
    m->sync_time = real_time;
    return real_time;
}
#endif

/* end helper routines used by midiOutStream interface */

static PmError winmm_out_open(PmInternal *midi, void *driverInfo)
{
    DWORD dwDevice;
    int i = midi->device_id;
    midiwinmm_type m;
    MIDIPROPTEMPO propdata;
    MIDIPROPTIMEDIV divdata;
    dwDevice = (DWORD) descriptors[i].descriptor;

    /* create system dependent device data */
    m = (midiwinmm_type) pm_alloc(sizeof(midiwinmm_node)); /* create */
    midi->descriptor = m;
    if (!m) goto no_memory;
    m->handle.out = NULL;
    m->buffers = NULL;
    m->num_buffers = 0;
    m->next_buffer = 0;
    m->last_time = 0;
    m->first_message = TRUE; /* we treat first message as special case */
    m->sysex_mode = FALSE;
    m->sysex_word = 0;
    m->sysex_byte_count = 0;
    m->hdr = NULL;
    m->sync_time = 0;
    m->delta = 0;
    m->error = MMSYSERR_NOERROR;
    m->callback_error = MMSYSERR_NOERROR;

    /* create a signal */
    m->buffer_signal = CreateEvent(NULL, FALSE, FALSE, NULL);

    /* this should only fail when there are very serious problems */
    assert(m->buffer_signal);

    /* open device */
    if (midi->latency == 0) {
        /* use simple midi out calls */
        pm_hosterror = midiOutOpen((LPHMIDIOUT) &m->handle.out, /* device Handle */
                           dwDevice, /* device ID  */
                           (DWORD) winmm_out_callback,
                           (DWORD) midi, /* callback instance data */
                           CALLBACK_FUNCTION); /* callback type */
    } else {
        /* use stream-based midi output (schedulable in future) */
        pm_hosterror = midiStreamOpen(&m->handle.stream, /* device Handle */
                              (LPUINT) &dwDevice, /* device ID pointer */
                              1, /* reserved, must be 1 */
                              (DWORD) winmm_streamout_callback,
                              (DWORD) midi, /* callback instance data */
                              CALLBACK_FUNCTION);
    }
    if (pm_hosterror != MMSYSERR_NOERROR) {
        goto free_descriptor;
    }

    if (midi->latency != 0) {
        long dur = 0;
        /* with stream output, specified number of buffers allocated here */
        int count = midi->buffer_len;
        if (count == 0)
            count = midi->latency / 2; /* how many buffers to get */

        propdata.cbStruct = sizeof(MIDIPROPTEMPO);
        propdata.dwTempo = 480000; /* microseconds per quarter */
        pm_hosterror = midiStreamProperty(m->handle.stream,
                                         (LPBYTE) &propdata,
                                         MIDIPROP_SET | MIDIPROP_TEMPO);
        if (pm_hosterror) goto close_device;

        divdata.cbStruct = sizeof(MIDIPROPTEMPO);
        divdata.dwTimeDiv = 480;   /* divisions per quarter */
        pm_hosterror = midiStreamProperty(m->handle.stream,
                                         (LPBYTE) &divdata,
                                         MIDIPROP_SET | MIDIPROP_TIMEDIV);
        if (pm_hosterror) goto close_device;

        /* allocate at least 3 buffers */
        if (count < 3) count = 3;
        if (allocate_buffers(m, SYSEX_BYTES_PER_BUFFER, count)) goto free_buffers;
        /* start device */
        pm_hosterror = midiStreamRestart(m->handle.stream);
        if (pm_hosterror != MMSYSERR_NOERROR) goto free_buffers;
    }
    return pmNoError;

free_buffers:
    /* buffers are freed below by winmm_out_delete */
close_device:
    midiOutClose(m->handle.out);
free_descriptor:
    midi->descriptor = NULL;
    winmm_out_delete(midi); /* frees buffers and m */
no_memory:
    if (pm_hosterror) {
        int err = midiOutGetErrorText(pm_hosterror, (char *) pm_hosterror_text,
                                      PM_HOST_ERROR_MSG_LEN);
        assert(err == MMSYSERR_NOERROR);
        return pmHostError;
    }
    return pmInsufficientMemory;
}

/* winmm_out_delete -- carefully free data associated with midi */
/**/
static void winmm_out_delete(PmInternal *midi)
{
    /* delete system dependent device data */
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    if (m) {
        if (m->buffer_signal) {
            /* don't report errors -- better not to stop cleanup */
            CloseHandle(m->buffer_signal);
        }
        if (m->buffers) {
            /* if using stream output, free buffers */
            int i;
            for (i = 0; i < m->num_buffers; i++) {
                if (m->buffers[i]) pm_free(m->buffers[i]);
            }
            pm_free(m->buffers);
        }
    }
    midi->descriptor = NULL;
    pm_free(m); /* delete */
}

/* see comments for winmm_in_close */
static PmError winmm_out_close(PmInternal *midi)
{
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    if (m->handle.out) {
        /* device to close */
        if (midi->latency == 0) {
            pm_hosterror = midiOutClose(m->handle.out);
        } else {
            pm_hosterror = midiStreamClose(m->handle.stream);
        }
        /* regardless of outcome, free memory */
        winmm_out_delete(midi);
    }
    if (pm_hosterror) {
        int err = midiOutGetErrorText(pm_hosterror,
                                      (char *) pm_hosterror_text,
                                      PM_HOST_ERROR_MSG_LEN);
        assert(err == MMSYSERR_NOERROR);
        return pmHostError;
    }
    return pmNoError;
}

static PmError winmm_out_abort(PmInternal *midi)
{
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    m->error = MMSYSERR_NOERROR;

    /* only stop output streams */
    if (midi->latency > 0) {
        m->error = midiStreamStop(m->handle.stream);
    }
    return m->error ? pmHostError : pmNoError;
}

#ifdef GARBAGE
static PmError winmm_write_sysex_byte(PmInternal *midi, unsigned char byte)
{
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    unsigned char *msg_buffer;

    /* at the beginning of sysex, m->hdr is NULL */
    if (!m->hdr) { /* allocate a buffer if none allocated yet */
        m->hdr = get_free_output_buffer(midi);
        if (!m->hdr) return pmInsufficientMemory;
        m->sysex_byte_count = 0;
    }
    /* figure out where to write byte */
    msg_buffer = (unsigned char *) (m->hdr->lpData);
    assert(m->hdr->lpData == (char *) (m->hdr + 1));

    /* check for overflow */
    if (m->sysex_byte_count >= m->hdr->dwBufferLength) {
        /* allocate a bigger message -- double it every time */
        LPMIDIHDR big = allocate_buffer(m->sysex_byte_count * 2);
        /* printf("expand to %d bytes\n", m->sysex_byte_count * 2); */
        if (!big) return pmInsufficientMemory;
        m->error = midiOutPrepareHeader(m->handle.out, big,
                                        sizeof(MIDIHDR));
        if (m->error) {
            m->hdr = NULL;
            return pmHostError;
        }
        memcpy(big->lpData, msg_buffer, m->sysex_byte_count);
        msg_buffer = (unsigned char *) (big->lpData);
        if (m->buffers[0] == m->hdr) {
            m->buffers[0] = big;
            pm_free(m->hdr);
            /* printf("freed m->hdr\n"); */
        } else if (m->buffers[1] == m->hdr) {
            m->buffers[1] = big;
            pm_free(m->hdr);
            /* printf("freed m->hdr\n"); */
        }
        m->hdr = big;
    }

    /* append byte to message */
    msg_buffer[m->sysex_byte_count++] = byte;

    /* see if we have a complete message */
    if (byte == MIDI_EOX) {
        m->hdr->dwBytesRecorded = m->sysex_byte_count;
        /*
        { int i; int len = m->hdr->dwBytesRecorded;
          printf("OutLongMsg %d ", len);
          for (i = 0; i < len; i++) {
              printf("%2x ", msg_buffer[i]);
          }
        }
        */
        m->error = midiOutLongMsg(m->handle.out, m->hdr, sizeof(MIDIHDR));
        m->hdr = NULL; /* stop using this message buffer */
        if (m->error) return pmHostError;
    }
    return pmNoError;
}
#endif

static PmError winmm_write_short(PmInternal *midi, PmEvent *event)
{
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    PmError rslt = pmNoError;
    assert(m);
    if (midi->latency == 0) { /* use midiOut interface, ignore timestamps */
        m->error = midiOutShortMsg(m->handle.out, event->message);
        if (m->error) rslt = pmHostError;
    } else {  /* use midiStream interface -- pass data through buffers */
        unsigned long when = event->timestamp;
        unsigned long delta;
        int full;
        if (when == 0) when = midi->now;
        /* when is in real_time; translate to intended stream time */
        when = when + m->delta + midi->latency;
        /* make sure we don't go backward in time */
        if (when < m->last_time) when = m->last_time;
        delta = when - m->last_time;
        m->last_time = when;
        /* before we insert any data, we must have a buffer */
        if (m->hdr == NULL) {
            /* stream interface: buffers allocated when stream is opened */
            m->hdr = get_free_output_buffer(midi);
        }
        full = add_to_buffer(m, m->hdr, delta, event->message);
        if (full) {
            m->error = midiStreamOut(m->handle.stream, m->hdr,
                                     sizeof(MIDIHDR));
            if (m->error) rslt = pmHostError;
            m->hdr = NULL;
        }
    }
    return rslt;
}

static PmError winmm_begin_sysex(PmInternal *midi, PmTimestamp timestamp)
{
    PmError rslt = pmNoError;
    if (midi->latency  == 0) {
        /* do nothing -- it's handled in winmm_write_byte */
    } else {
        midiwinmm_type m = (midiwinmm_type) midi->descriptor;
        /* sysex expects an empty buffer */
        if (m->hdr) {
            m->error = midiStreamOut(m->handle.stream, m->hdr, sizeof(MIDIHDR));
            if (m->error) rslt = pmHostError;
        }
        m->hdr = NULL;
    }
    return rslt;
}

static PmError winmm_end_sysex(PmInternal *midi, PmTimestamp timestamp)
{
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    PmError rslt = pmNoError;
    assert(m);
    if (midi->latency == 0) {
        /* Not using the stream interface. The entire sysex message is
           in m->hdr, and we send it using midiOutLongMsg.
         */
        m->hdr->dwBytesRecorded = m->sysex_byte_count;
        /*
        { int i; int len = m->hdr->dwBytesRecorded;
          printf("OutLongMsg %d ", len);
          for (i = 0; i < len; i++) {
              printf("%2x ", msg_buffer[i]);
          }
        }
        */
        m->error = midiOutLongMsg(m->handle.out, m->hdr, sizeof(MIDIHDR));
        if (m->error) rslt = pmHostError;
    } else if (m->hdr) {
        /* Using stream interface. There are accumulated bytes in m->hdr
           to send using midiStreamOut
         */
        /* add bytes recorded to MIDIEVENT length, but don't
           count the MIDIEVENT data (3 longs) */
        MIDIEVENT *evt = (MIDIEVENT *) m->hdr->lpData;
        evt->dwEvent += m->hdr->dwBytesRecorded - 3 * sizeof(long);
        /* round up BytesRecorded to multiple of 4 */
        m->hdr->dwBytesRecorded =  (m->hdr->dwBytesRecorded + 3) & ~3;
        m->error = midiStreamOut(m->handle.stream, m->hdr,
                                 sizeof(MIDIHDR));
        if (m->error) {
            rslt = pmHostError;
        }
    }
    m->hdr = NULL; /* make sure we don't send it again */
    return rslt;
}

static PmError winmm_write_byte(PmInternal *midi, unsigned char byte,
                                PmTimestamp timestamp)
{
    /* write a sysex byte */
    PmError rslt = pmNoError;
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    assert(m);
    if (midi->latency == 0) {
        /* Not using stream interface. Accumulate the entire message into
           m->hdr */
        unsigned char *msg_buffer;
        /* at the beginning of sysex, m->hdr is NULL */
        if (!m->hdr) { /* allocate a buffer if none allocated yet */
            m->hdr = get_free_output_buffer(midi);
            if (!m->hdr) return pmInsufficientMemory;
            m->sysex_byte_count = 0;
        }
        /* figure out where to write byte */
        msg_buffer = (unsigned char *) (m->hdr->lpData);
        assert(m->hdr->lpData == (char *) (m->hdr + 1));

        /* check for overflow */
        if (m->sysex_byte_count >= m->hdr->dwBufferLength) {
            /* allocate a bigger message -- double it every time */
            LPMIDIHDR big = allocate_buffer(m->sysex_byte_count * 2);
            /* printf("expand to %d bytes\n", m->sysex_byte_count * 2); */
            if (!big) return pmInsufficientMemory;
            m->error = midiOutPrepareHeader(m->handle.out, big,
                                            sizeof(MIDIHDR));
            if (m->error) {
                m->hdr = NULL;
                return pmHostError;
            }
            memcpy(big->lpData, msg_buffer, m->sysex_byte_count);
            msg_buffer = (unsigned char *) (big->lpData);
            /* we keep two buffers for sysex messages. Replace whichever
               one we just reallocated */
            if (m->buffers[0] == m->hdr) {
                m->buffers[0] = big;
                pm_free(m->hdr);
                /* printf("freed m->hdr\n"); */
            } else if (m->buffers[1] == m->hdr) {
                m->buffers[1] = big;
                pm_free(m->hdr);
                /* printf("freed m->hdr\n"); */
            }
            m->hdr = big;
        }

        /* append byte to message */
        msg_buffer[m->sysex_byte_count++] = byte;

    } else { /* latency is not zero, use stream interface: accumulate
                sysex data in m->hdr and send whenever the buffer fills */
        int full;
        unsigned char *ptr;

        /* if m->hdr does not exist, allocate it */
        if (m->hdr == NULL) {
            unsigned long when = (unsigned long) timestamp;
            unsigned long delta;
            unsigned long *ptr;
            if (when == 0) when = midi->now;
            /* when is in real_time; translate to intended stream time */
            when = when + m->delta + midi->latency;
            /* make sure we don't go backward in time */
            if (when < m->last_time) when = m->last_time;
            delta = when - m->last_time;
            m->last_time = when;

            m->hdr = get_free_output_buffer(midi);
            assert(m->hdr);
            ptr = (unsigned long *) m->hdr->lpData;
            *ptr++ = delta;
            *ptr++ = 0;
            *ptr = MEVT_F_LONG;
            m->hdr->dwBytesRecorded = 3 * sizeof(long);
        }

        /* add the data byte */
        ptr = (unsigned char *) (m->hdr->lpData + m->hdr->dwBytesRecorded);
        *ptr = byte;
        full = ++m->hdr->dwBytesRecorded >= m->hdr->dwBufferLength;

        /* see if it's time to send buffer */
        if (full) {
            rslt = winmm_end_sysex(midi, timestamp);
        }
    }
    return rslt;
}

static PmError winmm_write_flush(PmInternal *midi)
{
    PmError rslt = pmNoError;
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    assert(m);
    if (midi->latency == 0) {
        /* all messages are sent immediately */
    } else if (m->hdr) {
        /* sysex messages are sent upon completion, but ordinary messages
           may be sitting in a buffer
         */
        m->error = midiStreamOut(m->handle.stream, m->hdr, sizeof(MIDIHDR));
        m->hdr = NULL;
        if (m->error) rslt = pmHostError;
    }
    return rslt;
}

static PmTimestamp winmm_synchronize(PmInternal *midi)
{
    midiwinmm_type m;
    unsigned long pm_stream_time_2;
    unsigned long real_time;
    unsigned long pm_stream_time;

    /* only synchronize if we are using stream interface */
    if (midi->latency == 0) return 0;

    /* figure out the time */
    m = (midiwinmm_type) midi->descriptor;
    pm_stream_time_2 = pm_time_get(m);

    do {
        /* read real_time between two reads of stream time */
        pm_stream_time = pm_stream_time_2;
        real_time = (*midi->time_proc)(midi->time_info);
        pm_stream_time_2 = pm_time_get(m);
        /* repeat if more than 1ms elapsed */
    } while (pm_stream_time_2 > pm_stream_time + 1);
    m->delta = pm_stream_time - real_time;
    m->sync_time = real_time;
    return real_time;
}

#ifdef GARBAGE
static PmError winmm_write(PmInternal *midi,
                           PmEvent *buffer,
                           long length) {
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    unsigned long now;
    int i;
    long msg;
    PmError rslt = pmNoError;

    m->error = MMSYSERR_NOERROR;
    if (midi->latency == 0) { /* use midiOut interface, ignore timestamps */
        for (i = 0; (i < length) && (rslt == pmNoError); i++) {
            int b = 0; /* count sysex bytes as they are handled */
            msg = buffer[i].message;
            if ((msg & 0xFF) == MIDI_SYSEX) {
                /* start a sysex message */
                m->sysex_mode = TRUE;
                unsigned char midi_byte = (unsigned char) msg;
                rslt = winmm_write_sysex_byte(midi, midi_byte);
                b = 8;
            } else if ((msg & 0x80) && ((msg & 0xFF) != MIDI_EOX)) {
                /* a non-sysex message */
                m->error = midiOutShortMsg(m->handle.out, msg);
                if (m->error) rslt = pmHostError;
                /* any non-real-time message will terminate sysex message */
                if (!is_real_time(msg)) m->sysex_mode = FALSE;
            }
            /* transmit sysex bytes until we find EOX */
            if (m->sysex_mode) {
                while (b < 32 /*bits*/ && (rslt == pmNoError)) {
                    unsigned char midi_byte = (unsigned char) (msg >> b);
                    rslt = winmm_write_sysex_byte(midi, midi_byte);
                    if (midi_byte == MIDI_EOX) {
                        b = 24; /* end of message */
                        m->sysex_mode = FALSE;
                    }
                    b += 8;
                }
            }
        }
    } else { /* use midiStream interface -- pass data through buffers */
        LPMIDIHDR hdr = NULL;
        now = (*midi->time_proc)(midi->time_info);
        if (m->first_message || m->sync_time + 100 /*ms*/ < now) {
            /* time to resync */
            now = synchronize(midi, m);
            m->first_message = FALSE;
        }
        for (i = 0; i < length && rslt == pmNoError; i++) {
            unsigned long when = buffer[i].timestamp;
            unsigned long delta;
            if (when == 0) when = now;
            /* when is in real_time; translate to intended stream time */
            when = when + m->delta + midi->latency;
            /* make sure we don't go backward in time */
            if (when < m->last_time) when = m->last_time;
            delta = when - m->last_time;
            m->last_time = when;
            /* before we insert any data, we must have a buffer */
            if (hdr == NULL) {
                /* stream interface: buffers allocated when stream is opened */
                hdr = get_free_output_buffer(midi);
                assert(hdr);
                if (m->sysex_mode) {
                    /* we are in the middle of a sysex message */
                    start_sysex_buffer(hdr, delta);
                }
            }
            msg = buffer[i].message;
            if ((msg & 0xFF) == MIDI_SYSEX) {
                /* sysex expects an empty buffer */
                if (hdr->dwBytesRecorded != 0) {
                    m->error = midiStreamOut(m->handle.stream, hdr, sizeof(MIDIHDR));
                    if (m->error) rslt = pmHostError;
                    hdr = get_free_output_buffer(midi);
                    assert(hdr);
                }
                /* when we see a MIDI_SYSEX, we always enter sysex mode and call
                   start_sysex_buffer() */
                start_sysex_buffer(hdr, delta);
                m->sysex_mode = TRUE;
            }
            /* allow a non-real-time status byte to terminate sysex message */
            if (m->sysex_mode && (msg & 0x80) && (msg & 0xFF) != MIDI_SYSEX &&
                !is_real_time(msg)) {
                /* I'm not sure what WinMM does if you send an incomplete sysex
                   message, but the best way out of this mess seems to be to
                   recreate the code used when you encounter an EOX, so ...
                 */
                MIDIEVENT *evt = (MIDIEVENT) hdr->lpData;
                evt->dwEvent += hdr->dwBytesRecorded - 3 * sizeof(long);
                /* round up BytesRecorded to multiple of 4 */
                hdr->dwBytesRecorded =  (hdr->dwBytesRecorded + 3) & ~3;
                m->error = midiStreamOut(m->handle.stream, hdr,
                                            sizeof(MIDIHDR));
                if (m->error) {
                    rslt = pmHostError;
                }
                hdr = NULL; /* make sure we don't send it again */
                m->sysex_mode = FALSE; /* skip to normal message send code */
            }
            if (m->sysex_mode) {
                int b = 0; /* count bytes as they are handled */
                while (b < 32 /* bits per word */ && (rslt == pmNoError)) {
                    int full;
                    unsigned char midi_byte = (unsigned char) (msg >> b);
                    if (!hdr) {
                        hdr = get_free_output_buffer(midi);
                        assert(hdr);
                        /* get ready to put sysex bytes in buffer */
                        start_sysex_buffer(hdr, delta);
                    }
                    full = add_byte_to_buffer(m, hdr, midi_byte);
                    if (midi_byte == MIDI_EOX) {
                        b = 24; /* pretend this is last byte to exit loop */
                        m->sysex_mode = FALSE;
                    }
                    /* see if it's time to send buffer, note that by always
                       sending complete sysex message right away, we can use
                       this code to set up the MIDIEVENT properly
                     */
                    if (full || midi_byte == MIDI_EOX) {
                        /* add bytes recorded to MIDIEVENT length, but don't
                           count the MIDIEVENT data (3 longs) */
                        MIDIEVENT *evt = (MIDIEVENT *) hdr->lpData;
                        evt->dwEvent += hdr->dwBytesRecorded - 3 * sizeof(long);
                        /* round up BytesRecorded to multiple of 4 */
                        hdr->dwBytesRecorded =  (hdr->dwBytesRecorded + 3) & ~3;
                        m->error = midiStreamOut(m->handle.stream, hdr,
                                                 sizeof(MIDIHDR));
                        if (m->error) {
                            rslt = pmHostError;
                        }
                        hdr = NULL; /* make sure we don't send it again */
                    }
                    b += 8; /* shift to next byte */
                }
            /* test rslt here in case it was set when we terminated a sysex early
               (see above) */
            } else if (rslt == pmNoError) {
                int full = add_to_buffer(m, hdr, delta, msg);
                if (full) {
                    m->error = midiStreamOut(m->handle.stream, hdr,
                                             sizeof(MIDIHDR));
                    if (m->error) rslt = pmHostError;
                    hdr = NULL;
                }
            }
        }
        if (hdr && rslt == pmNoError) {
            if (m->sysex_mode) {
                MIDIEVENT *evt = (MIDIEVENT *) hdr->lpData;
                evt->dwEvent += hdr->dwBytesRecorded - 3 * sizeof(long);
                /* round up BytesRecorded to multiple of 4 */
                hdr->dwBytesRecorded = (hdr->dwBytesRecorded + 3) & ~3;
            }
            m->error = midiStreamOut(m->handle.stream, hdr, sizeof(MIDIHDR));
            if (m->error) rslt = pmHostError;
        }
    }
    return rslt;
}
#endif

/* winmm_out_callback -- recycle sysex buffers */
static void CALLBACK winmm_out_callback(HMIDIOUT hmo, UINT wMsg,
    DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
    PmInternal *midi = (PmInternal *) dwInstance;
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    LPMIDIHDR hdr = (LPMIDIHDR) dwParam1;
    int err;
    static int entry = 0;
    if(++entry > 1) {
        assert(FALSE);
    }
    if (m->callback_error || wMsg != MOM_DONE) {
        entry--;
        return;
    }
    /* Future optimization: eliminate UnprepareHeader calls -- they aren't
       necessary; however, this code uses the prepared-flag to indicate which
       buffers are free, so we need to do something to flag empty buffers if
       we leave them prepared
     */
    m->callback_error = midiOutUnprepareHeader(m->handle.out, hdr,
                                               sizeof(MIDIHDR));
    /* notify waiting sender that a buffer is available */
    /* any errors could be reported via callback_error, but this is always
       treated as a Midi error, so we'd have to write a lot more code to
       detect that a non-Midi error occurred and do the right thing to find
       the corresponding error message text. Therefore, just use assert()
     */
    err = SetEvent(m->buffer_signal);
    assert(err); /* false -> error */
    entry--;
}

/* winmm_streamout_callback -- unprepare (free) buffer header */
static void CALLBACK winmm_streamout_callback(HMIDIOUT hmo, UINT wMsg,
        DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
    PmInternal *midi = (PmInternal *) dwInstance;
    midiwinmm_type m = (midiwinmm_type) midi->descriptor;
    LPMIDIHDR hdr = (LPMIDIHDR) dwParam1;
    int err;
    static int entry = 0;
    if(++entry > 1) {
        /* We've reentered this routine. I assume this never happens, but
           check to make sure. Apparently, it is possible that this callback
           can be called reentrantly because it happened once while debugging.
           It looks like this routine is actually reentrant so we can remove
           the assertion if necessary. */
        assert(FALSE);
    }
    if(m->callback_error || wMsg != MOM_DONE) {
        entry--;
        return;
    }
    m->callback_error = midiOutUnprepareHeader(m->handle.out, hdr,
                                               sizeof(MIDIHDR));
    err = SetEvent(m->buffer_signal);
    assert(err); /* false -> error */
    entry--;
}

/*
=========================================================================================
begin exported functions
=========================================================================================
*/

#define winmm_in_abort pm_fail_fn
pm_fns_node pm_winmm_in_dictionary = {
    none_write_short,
    none_sysex,
    none_sysex,
    none_write_byte,
    none_write_short,
    none_write_flush,
    winmm_synchronize,
    winmm_in_open,
    winmm_in_abort,
    winmm_in_close,
    success_poll,
    winmm_has_host_error,
    winmm_get_host_error
};

pm_fns_node pm_winmm_out_dictionary = {
    winmm_write_short,
    winmm_begin_sysex,
    winmm_end_sysex,
    winmm_write_byte,
    winmm_write_short, /* short realtime message */
    winmm_write_flush,
    winmm_synchronize,
    winmm_out_open,
    winmm_out_abort,
    winmm_out_close,
    none_poll,
    winmm_has_host_error,
    winmm_get_host_error
};

/* initialize winmm interface. Note that if there is something wrong
   with winmm (e.g. it is not supported or installed), it is not an
   error. We should simply return without having added any devices to
   the table. Hence, no error code is returned. Furthermore, this init
   code is called along with every other supported interface, so the
   user would have a very hard time figuring out what hardware and API
   generated the error. Finally, it would add complexity to pmwin.c to
   remember where the error code came from in order to convert to text.
 */
void pm_winmm_init( void )
{
    pm_winmm_mapper_input();
    pm_winmm_mapper_output();
    pm_winmm_general_inputs();
    pm_winmm_general_outputs();
}

/* no error codes are returned, even if errors are encountered, because
   there is probably nothing the user could do (e.g. it would be an error
   to retry.
 */
void pm_winmm_term( void )
{
    int i;
    #ifdef DEBUG
        char msg[PM_HOST_ERROR_MSG_LEN];
    #endif
    int doneAny = 0;
    #ifdef DEBUG
        printf("pm_winmm_term called\n");
    #endif
    for (i = 0; i < pm_descriptor_index; i++) {
        PmInternal * midi= descriptors[i].internalDescriptor;
        if (midi) {
            midiwinmm_type m = (midiwinmm_type) midi->descriptor;
            if (m->handle.out) {
                /* close next open device*/
                #ifdef DEBUG
                    if (doneAny == 0) {
                        printf("begin closing open devices...\n");
                        doneAny = 1;
                    }
                    /* report any host errors; this EXTEREMELY useful when
                       trying to debug client app */
                    if (winmm_has_host_error(midi)) {
                        winmm_get_host_error(midi,msg,PM_HOST_ERROR_MSG_LEN);
                        printf(msg);
                    }
                #endif
                /* close all open ports */
                (*midi->dictionary->close)(midi);
            }
        }
    }
#ifdef DEBUG
    if (doneAny) {
        printf("warning: devices were left open. They have been closed.\n");
    }
    printf("pm_winmm_term exiting\n");
#endif
    pm_descriptor_index = 0;
}


text:
@interface Photo (MKAnnotation) <MKAnnotation>

- (UIImage *)thumbnail; // blocks!

@end


text:
#include "UIVideoPlayer.h"

#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include <unordered_map>
#include <stdlib.h>
#include <jni.h>
#include <string>
#include "jni/JniHelper.h"
#include "base/CCDirector.h"
#include "CCGLView.h"
#include "base/CCEventListenerKeyboard.h"

//-----------------------------------------------------------------------------------------------------------
#define  CLASS_NAME "org/cocos2dx/lib/Cocos2dxVideoHelper"

void executeVideoCallback(int index,int event);

USING_NS_CC;

extern "C" {
    void Java_org_cocos2dx_lib_Cocos2dxVideoHelper_nativeExecuteVideoCallback(JNIEnv * env, jobject obj, jint index,jint event) {
        executeVideoCallback(index,event);
    }
}

int createVideoWidgetJNI()
{
    JniMethodInfo t;
    int ret = -1;
    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "createVideoWidget", "()I")) {
        ret = t.env->CallStaticIntMethod(t.classID, t.methodID);

        t.env->DeleteLocalRef(t.classID);
    }

    return ret;
}

void callVideoNonParameterFun(int index,const char* funName)
{
    JniMethodInfo t;

    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, funName, "(I)V")) {
        t.env->CallStaticVoidMethod(t.classID, t.methodID, index);

        t.env->DeleteLocalRef(t.classID);
    }
}

void removeVideoWidgetJNI(int index)
{
    callVideoNonParameterFun(index,"removeVideoWidget");
}

void setVideoRectJNI(int index,int left,int top,int width,int height)
{
    JniMethodInfo t;

    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setVideoRect", "(IIIII)V")) {
        t.env->CallStaticVoidMethod(t.classID, t.methodID, index, left, top, width, height);

        t.env->DeleteLocalRef(t.classID);
    }
}

void setVideoURLJNI(int index,int videoSource,const std::string& videoUrl)
{
    JniMethodInfo t;
    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setVideoUrl", "(IILjava/lang/String;)V")) {
        jstring stringArg = t.env->NewStringUTF(videoUrl.c_str());
        t.env->CallStaticVoidMethod(t.classID, t.methodID, index, videoSource,stringArg);

        t.env->DeleteLocalRef(t.classID);
        t.env->DeleteLocalRef(stringArg);
    }
}

void startVideoJNI(int index)
{
    callVideoNonParameterFun(index,"startVideo");
}

void pauseVideoJNI(int index)
{
    callVideoNonParameterFun(index,"pauseVideo");
}

void resumeVideoJNI(int index)
{
    callVideoNonParameterFun(index,"resumeVideo");
}

void stopVideoJNI(int index)
{
    callVideoNonParameterFun(index,"stopVideo");
}

void seekVideoToJNI(int index,int msec)
{
    JniMethodInfo t;

    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "seekVideoTo", "(II)V")) {
        t.env->CallStaticVoidMethod(t.classID, t.methodID, index, msec);

        t.env->DeleteLocalRef(t.classID);
    }
}

void setVideoVisible(int index,bool visible)
{
    JniMethodInfo t;

    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setVideoVisible", "(IZ)V")) {
        t.env->CallStaticVoidMethod(t.classID, t.methodID, index, visible);

        t.env->DeleteLocalRef(t.classID);
    }
}

void setVideoKeepRatioEnabled(int index,bool enabled)
{
    JniMethodInfo t;

    if (JniHelper::getStaticMethodInfo(t, CLASS_NAME, "setVideoKeepRatioEnabled", "(IZ)V")) {
        t.env->CallStaticVoidMethod(t.classID, t.methodID, index, enabled);

        t.env->DeleteLocalRef(t.classID);
    }
}
//-----------------------------------------------------------------------------------------------------------

using namespace cocos2d::experimental::ui;

static std::unordered_map<int, VideoPlayer*> s_allVideoPlayers;

VideoPlayer::VideoPlayer()
: _videoPlayerIndex(-1)
, _eventCallback(nullptr)
, _fullScreenEnabled(false)
, _fullScreenDirty(false)
, _keepAspectRatioEnabled(false)
{
    _videoPlayerIndex = createVideoWidgetJNI();
    s_allVideoPlayers[_videoPlayerIndex] = this;

    auto listener = EventListenerKeyboard::create();
    listener->onKeyReleased = [&](EventKeyboard::KeyCode keycode, cocos2d::Event* event){
        if (keycode == EventKeyboard::KeyCode::KEY_BACKSPACE && _fullScreenEnabled)
        {
            this->setFullScreenEnabled(false);
        }
    };

    _eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
}

VideoPlayer::~VideoPlayer()
{
    s_allVideoPlayers.erase(_videoPlayerIndex);
    removeVideoWidgetJNI(_videoPlayerIndex);
}

void VideoPlayer::setFileName(const std::string& fileName)
{
    _videoURL = fileName;
    _videoSource = VideoPlayer::Source::FILENAME;
    setVideoURLJNI(_videoPlayerIndex, (int)Source::FILENAME,_videoURL);
}

void VideoPlayer::setURL(const std::string& videoUrl)
{
    _videoURL = videoUrl;
    _videoSource = VideoPlayer::Source::URL;
    setVideoURLJNI(_videoPlayerIndex,(int)Source::URL,_videoURL);
}

void VideoPlayer::draw(Renderer* renderer, const Mat4 &transform, uint32_t flags)
{
    cocos2d::ui::Widget::draw(renderer,transform,flags);

    if ((flags&FLAGS_TRANSFORM_DIRTY) || _fullScreenDirty)
    {
        _fullScreenDirty = false;
        auto directorInstance = Director::getInstance();
        auto glView = directorInstance->getOpenGLView();
        auto frameSize = glView->getFrameSize();

        if (_fullScreenEnabled)
        {
            setVideoRectJNI(_videoPlayerIndex,0,0,frameSize.width,frameSize.height);
        }
        else
        {
            auto winSize = directorInstance->getWinSize();

            auto leftBottom = convertToWorldSpace(Point::ZERO);
            auto rightTop = convertToWorldSpace(Point(_contentSize.width,_contentSize.height));

            auto uiLeft = frameSize.width / 2 + (leftBottom.x - winSize.width / 2 ) * glView->getScaleX();
            auto uiTop = frameSize.height /2 - (rightTop.y - winSize.height / 2) * glView->getScaleY();

            setVideoRectJNI(_videoPlayerIndex,uiLeft,uiTop,
                (rightTop.x - leftBottom.x) * glView->getScaleX(),
                (rightTop.y - leftBottom.y) * glView->getScaleY());
        }
    }

#if CC_VIDEOPLAYER_DEBUG_DRAW
    _customDebugDrawCommand.init(_globalZOrder);
    _customDebugDrawCommand.func = CC_CALLBACK_0(VideoPlayer::drawDebugData, this);
    renderer->addCommand(&_customDebugDrawCommand);
#endif
}

void VideoPlayer::setFullScreenEnabled(bool enabled)
{
    if (_fullScreenEnabled != enabled)
    {
        _fullScreenEnabled = enabled;
        _fullScreenDirty = true;
    }
}

bool VideoPlayer::isFullScreenEnabled()const
{
    return _fullScreenEnabled;
}

void VideoPlayer::setKeepAspectRatioEnabled(bool enable)
{
    if (_keepAspectRatioEnabled != enable)
    {
        _keepAspectRatioEnabled = enable;
        setVideoKeepRatioEnabled(_videoPlayerIndex,enable);
    }
}

#if CC_VIDEOPLAYER_DEBUG_DRAW
void VideoPlayer::drawDebugData()
{
    Director* director = Director::getInstance();
    CCASSERT(nullptr != director, "Director is null when seting matrix stack");

    director->pushMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
    director->loadMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW, _modelViewTransform);

    auto size = getContentSize();

    Point vertices[4]=
    {
        Point::ZERO,
        Point(size.width, 0),
        Point(size.width, size.height),
        Point(0, size.height)
    };

    DrawPrimitives::drawPoly(vertices, 4, true);

    director->popMatrix(MATRIX_STACK_TYPE::MATRIX_STACK_MODELVIEW);
}
#endif

void VideoPlayer::play()
{
    if (! _videoURL.empty())
    {
        startVideoJNI(_videoPlayerIndex);
    }
}

void VideoPlayer::pause()
{
    if (! _videoURL.empty())
    {
        pauseVideoJNI(_videoPlayerIndex);
    }
}

void VideoPlayer::resume()
{
    if (! _videoURL.empty())
    {
        resumeVideoJNI(_videoPlayerIndex);
    }
}

void VideoPlayer::stop()
{
    if (! _videoURL.empty())
    {
        stopVideoJNI(_videoPlayerIndex);
    }
}

void VideoPlayer::seekTo(float sec)
{
    if (! _videoURL.empty())
    {
        seekVideoToJNI(_videoPlayerIndex,int(sec * 1000));
    }
}

bool VideoPlayer::isPlaying() const
{
    return _isPlaying;
}

void VideoPlayer::setVisible(bool visible)
{
    cocos2d::ui::Widget::setVisible(visible);

    if (! _videoURL.empty())
    {
        setVideoVisible(_videoPlayerIndex,visible);
    }
}

void VideoPlayer::addEventListener(const VideoPlayer::ccVideoPlayerCallback& callback)
{
    _eventCallback = callback;
}

void VideoPlayer::onPlayEvent(VideoPlayer::EventType event)
{
    if (event == VideoPlayer::EventType::PLAYING) {
        _isPlaying = true;
    } else {
        _isPlaying = false;
    }

    if (_eventCallback)
    {
        _eventCallback(this,event);
    }
}

cocos2d::ui::Widget* VideoPlayer::createCloneInstance()
{
    return VideoPlayer::create();
}

void VideoPlayer::copySpecialProperties(Widget *widget)
{
    VideoPlayer* videoPlayer = dynamic_cast<VideoPlayer*>(widget);
    if (videoPlayer)
    {
        _isPlaying = videoPlayer->_isPlaying;
        _fullScreenEnabled = videoPlayer->_fullScreenEnabled;
        _fullScreenDirty = videoPlayer->_fullScreenDirty;
        _videoURL = videoPlayer->_videoURL;
        _keepAspectRatioEnabled = videoPlayer->_keepAspectRatioEnabled;
        _videoSource = videoPlayer->_videoSource;
        _videoPlayerIndex = videoPlayer->_videoPlayerIndex;
        _eventCallback = videoPlayer->_eventCallback;
        _videoView = videoPlayer->_videoView;
    }
}

void executeVideoCallback(int index,int event)
{
    auto it = s_allVideoPlayers.find(index);
    if (it != s_allVideoPlayers.end())
    {
        s_allVideoPlayers[index]->onPlayEvent((VideoPlayer::EventType)event);
    }
}

#endif


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
W. C. H. Peters, Naturw. Reise Mossambique 6(2):563. 1864

#### Original name
null

### Remarks
null


text:
.c-home-banner .c-home-banner__panel-tab {
  font-size: 2rem;
  color: var(--theme-color__supporting-1--lighter);
}
.media-greater-than-large .c-home-banner .c-home-banner__panel-tab {
  font-size: 3rem;
}

.c-home-banner .c-home-banner__panel-body {
  font-size: 1.5rem;
  padding: var(--spacing-sm) var(--spacing-md);
}
.media-greater-than-large .c-home-banner .c-home-banner__panel-body {
  font-size: 2rem;
}
.media-greater-than-x-large .c-home-banner .c-home-banner__panel-body {
  padding: var(--spacing-lg) var(--spacing-xl);
}

.c-home-banner .c-home-banner__accordion {
  outline-color: var(--theme-color__accent-1);
}


text:
namespace cast {
namespace utils {

// Converts grpc::Status to a string message.
std::string GrpcStatusToString(const grpc::Status& status);

// Holds a value of type T with grpc::Status::OK or an error grpc::Status.
template <typename T,
          typename std::enable_if<!std::is_reference<T>::value, T*>::type =
              nullptr>
class GrpcStatusOr {
 public:
  GrpcStatusOr() : status_(grpc::StatusCode::UNKNOWN, "") {}

  // Constructs GrpcStatusOr from an error |status_code|.
  GrpcStatusOr(grpc::StatusCode status_code)  // NOLINT
      : GrpcStatusOr(status_code, "") {}

  // Constructs GrpcStatusOr from an error |status_code| and |error_message|.
  GrpcStatusOr(grpc::StatusCode status_code, const std::string& error_message)
      : status_(status_code, error_message) {
    DCHECK(!status_.ok());
  }

  // Constructs GrpcStatusOr from an error |status|.
  GrpcStatusOr(grpc::Status status)  // NOLINT
      : status_(std::move(status)) {
    DCHECK(!status_.ok());
  }

  // Constructs GrpcStatusOr from the |data|. Status code is set to OK.
  GrpcStatusOr(const T& data)  // NOLINT
      : status_(grpc::Status::OK), data_(data) {}

  // Constructs GrpcStatusOr from the |data|. Status code is set to OK.
  GrpcStatusOr(T&& data)  // NOLINT
      : status_(grpc::Status::OK), data_(std::move(data)) {}

  // Constructs GrpcStatusOr from the |data| of type U that is possible to
  // convert to type |T|. For example, std::unique_ptr<MockClass> converted to
  // std::unique_ptr<Class>. Status code is set to OK.
  template <typename U,
            typename std::enable_if<std::is_constructible<T, U>::value,
                                    U>::type* = nullptr>
  GrpcStatusOr(U&& data)  // NOLINT
      : status_(grpc::Status::OK), data_(std::forward<U>(data)) {}

  GrpcStatusOr(GrpcStatusOr&&) = default;
  GrpcStatusOr& operator=(GrpcStatusOr&&) = default;
  GrpcStatusOr(const GrpcStatusOr&) = default;
  GrpcStatusOr& operator=(const GrpcStatusOr&) = default;
  ~GrpcStatusOr() = default;

  // Returns if status is OK.
  bool ok() const { return status_.ok(); }

  // Returns const reference to gRPC status.
  const grpc::Status& status() const& { return status_; }

  // Returns r-value to gRPC status.
  grpc::Status&& status() && { return std::move(status_); }

  // Returns the pointer to the stored data. Checks if status is not OK.
  T* operator->() {
    DCHECK(status_.ok());
    return &*data_;
  }

  // Returns the const pointer to the stored data. Checks if status is not OK.
  const T* operator->() const {
    DCHECK(status_.ok());
    return &*data_;
  }

  // Returns the const reference to the stored data. Checks if status is not OK.
  const T& operator*() const& {
    DCHECK(status_.ok());
    return *data_;
  }

  // Returns the lvalue-ref to the underlying value. Checks if status is not OK.
  const T& value() const& {
    DCHECK(status_.ok());
    return *data_;
  }

  // Returns the rvalue-ref to the underlying value. To trigger this accessor,
  // the status object needs to be moved first: std::move(status_).value().
  // Checks if status is not OK.
  T&& value() && {
    DCHECK(status_.ok());
    status_ = grpc::Status(grpc::StatusCode::UNKNOWN, "");
    return std::move(data_).value();
  }

  // Sets the data.
  void emplace(T&& data) {
    status_ = grpc::Status::OK;
    data_.emplace(std::move(data));
  }

  std::string ToString() const { return GrpcStatusToString(status()); }

 private:
  grpc::Status status_;
  absl::optional<T> data_;
};

}  // namespace utils
}  // namespace cast

#endif  // CHROMECAST_CAST_CORE_GRPC_GRPC_STATUS_OR_H_


text:
SHAKE128
========

SHAKE128 is an *extendable-output function* (XOF) in the SHA-3 family, as specified in `FIPS 202`_.

As a XOF, SHAKE128 is a generalization of a cryptographic hash function.
Instead of creating a fixed-length digest (e.g. 32 bytes like SHA-2/256),
it can produce outputs of any desired length.

Output bits do **not** depend of the output length.

The *128* in its name indicates its maximum security level (in bits),
as described in Sections A.1 and A.2 of `FIPS 202`_.

In the following example, the output is 26 bytes (208 bits) long::

    >>> from Crypto.Hash import SHAKE128
    >>> from binascii import hexlify
    >>>
    >>> shake = SHAKE128.new()
    >>> shake.update(b'Some data')
    >>> print hexlify(shake.read(26))

.. _FIPS 202: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf

.. _SHA-2: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf

.. automodule:: Crypto.Hash.SHAKE128
    :members: