"""
Backends in `einops` are organized to meet the following requirements
- backends are not imported unless those are actually needed, because
    - backends may not be installed
    - importing all available backends will drive to significant memory footprint
    - backends may by present but installed with errors (but never used),
      importing may drive to crashes
- backend should be either symbolic or imperative (tensorflow is for both, but that causes problems)
    - this determines which methods (from_numpy/to_numpy or create_symbol/eval_symbol) should be defined
- if backend can't (temporarily) provide symbols for shape dimensions, UnknownSize objects are used
"""

import sys
import warnings

__author__ = 'Alex Rogozhnikov'

_backends = {}
_debug_importing = False

def get_backend(tensor) -> 'AbstractBackend':
    """
    Takes a correct backend (e.g. numpy backend if tensor is numpy.ndarray) for a tensor.
    If needed, imports package and creates backend
    """
    for framework_name, backend in _backends.items():
        if backend.is_appropriate_type(tensor):
            return backend

    # Find backend subclasses recursively
    backend_subclasses = []
    backends = AbstractBackend.__subclasses__()
    while backends:
        backend = backends.pop()
        backends += backend.__subclasses__()
        backend_subclasses.append(backend)

    for BackendSubclass in backend_subclasses:
        if _debug_importing:
            print('Testing for subclass of ', BackendSubclass)
        if BackendSubclass.framework_name not in _backends:
            # check that module was already imported. Otherwise it can't be imported
            if BackendSubclass.framework_name in sys.modules:
                if _debug_importing:
                    print('Imported backend for ', BackendSubclass.framework_name)
                backend = BackendSubclass()
                _backends[backend.framework_name] = backend
                if backend.is_appropriate_type(tensor):
                    return backend

    raise RuntimeError('Tensor type unknown to einops {}'.format(type(tensor)))

class AbstractBackend:
    """ Base backend class, major part of methods are only for debugging purposes. """
    framework_name = None

    def is_appropriate_type(self, tensor):
        """ helper method should recognize tensors it can handle """
        raise NotImplementedError()

    def from_numpy(self, x):
        raise NotImplementedError("framework doesn't support imperative execution")

    def to_numpy(self, x):
        raise NotImplementedError("framework doesn't support imperative execution")

    def create_symbol(self, shape):
        raise NotImplementedError("framework doesn't support symbolic computations")

    def eval_symbol(self, symbol, input_dict):
        raise NotImplementedError("framework doesn't support symbolic computations")

    def arange(self, start, stop):
        # supplementary method used only in testing, so should implement CPU version
        raise NotImplementedError("framework doesn't implement arange")

    def shape(self, x):
        """shape should return a tuple with integers or "shape symbols" (which will evaluate to actual size)"""
        return x.shape

    def reshape(self, x, shape):
        return x.reshape(shape)

    def transpose(self, x, axes):
        return x.transpose(axes)

    def reduce(self, x, operation, axes):
        return getattr(x, operation)(axis=axes)

    def stack_on_zeroth_dimension(self, tensors: list):
        raise NotImplementedError()

    def add_axis(self, x, new_position):
        raise NotImplementedError()

    def add_axes(self, x, n_axes, pos2len):
        repeats = [1] * n_axes
        for axis_position, axis_length in pos2len.items():
            x = self.add_axis(x, axis_position)
            repeats[axis_position] = axis_length
        return self.tile(x, tuple(repeats))

    def tile(self, x, repeats):
        """repeats is a number of  """
        raise NotImplementedError()

    def is_float_type(self, x):
        # some backends (torch) can't compute average for non-floating types.
        # Decided to drop average for all backends if type is not floating
        raise NotImplementedError()

    def layers(self):
        raise NotImplementedError("backend does not provide layers")

    def __repr__(self):
        return "<einops backend for {}>".format(self.framework_name)

class UnknownSize:
    """ pseudo-symbol for symbolic frameworks which do not provide symbols for shape elements """

    def __floordiv__(self, other):
        return self

    def __eq__(self, other):
        return True  # we don't know actual size

    def __mul__(self, other):
        return self

    def __rmul__(self, other):
        return self

    def __hash__(self):
        return None.__hash__()

class NumpyBackend(AbstractBackend):
    framework_name = 'numpy'

    def __init__(self):
        import numpy
        self.np = numpy

    def is_appropriate_type(self, tensor):
        return isinstance(tensor, self.np.ndarray)

    def from_numpy(self, x):
        return x

    def to_numpy(self, x):
        return x

    def arange(self, start, stop):
        return self.np.arange(start, stop)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.np.stack(tensors)

    def tile(self, x, repeats):
        return self.np.tile(x, repeats)

    def is_float_type(self, x):
        return x.dtype in ('float16', 'float32', 'float64', 'float128')

    def add_axis(self, x, new_position):
        return self.np.expand_dims(x, new_position)

class JaxBackend(NumpyBackend):
    framework_name = 'jax'

    def __init__(self):
        super(JaxBackend, self).__init__()
        self.onp = self.np

        import jax.numpy
        self.np = jax.numpy

    def from_numpy(self, x):
        return self.np.asarray(x)

    def to_numpy(self, x):
        return self.onp.asarray(x)

class GluonBackend(AbstractBackend):
    framework_name = 'mxnet.ndarray'

    def __init__(self):
        import mxnet
        self.mx = mxnet

    def is_appropriate_type(self, tensor):
        return isinstance(tensor, self.mx.nd.NDArray)

    def from_numpy(self, x):
        if len(x.shape) == 0:
            x = x[None]  # poor support of scalars in mxnet, otherwise mxnet can't attach gradients
        var = self.mx.nd.array(x, dtype=x.dtype)
        var.attach_grad()
        return var

    def to_numpy(self, x):
        return self.mx.nd.NDArray.asnumpy(x)

    def reshape(self, x, shape):
        if len(shape) == 0:
            return x  # poor support of scalars in mxnet
        return x.reshape(shape)

    def arange(self, start, stop):
        return self.mx.nd.arange(start, stop)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.mx.nd.stack(*tensors)

    def tile(self, x, repeats):
        return self.mx.nd.tile(x, repeats)

    def add_axis(self, x, new_position):
        return self.mx.nd.expand_dims(x, new_position)

    def is_float_type(self, x):
        return 'float' in str(x.dtype)

    def layers(self):
        from .layers import gluon
        return gluon

class MXNetBackend(AbstractBackend):
    framework_name = 'mxnet.symbol'

    def __init__(self):
        import mxnet
        self.mx = mxnet

    def is_appropriate_type(self, tensor):
        return isinstance(tensor, self.mx.symbol.Symbol)

    def create_symbol(self, shape, dtype='float32'):
        # mxnet accepts zeros as undefined dimensions
        shape = tuple(0 if d is None else d for d in shape)
        var = self.mx.symbol.Variable('input', shape=shape, dtype=dtype)
        return var

    def eval_symbol(self, symbol, input_dict):
        args = {var.name: self.mx.nd.array(val) for var, val in input_dict}
        ex = symbol.bind(ctx=self.mx.cpu(), args=args)
        ex.forward()
        return ex.outputs[0].asnumpy()

    def shape(self, x):
        # mxnet has problems with shape inference - it does not provide shape symbols
        # shape_array seems to be impossible to use in shape inference
        # infer_shape_partial returns empty tuple if was not able to infer shape
        # reductions such as sum can't return scalars, but return 1-element vectors
        shape = x.infer_shape_partial()[1][0]
        if len(shape) == 0:
            warnings.warn('mxnet inferred shape to be (), which probably means it could not be inferred')
        shape = tuple(UnknownSize() if d == 0 else d for d in shape)
        return shape

    def reshape(self, x, shape):
        if len(shape) == 0:
            return x  # poor support of scalars in mxnet
        if any(isinstance(dimension, UnknownSize) for dimension in shape):
            from einops import EinopsError
            raise EinopsError("Mxnet could't infer all dimensions statically, please provide those with axes_lengths")
        return x.reshape(shape)

    def arange(self, start, stop):
        return self.mx.symbol.arange(start, stop)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.mx.symbol.stack(*tensors)

    def tile(self, x, repeats):
        return self.mx.symbol.tile(x, repeats)

    def add_axis(self, x, new_position):
        return self.mx.symbol.expand_dims(x, new_position)

    def is_float_type(self, x):
        return 'float' in str(x.infer_type()[1][0])

    def layers(self):
        from .layers import gluon
        return gluon

class TorchBackend(AbstractBackend):
    framework_name = 'torch'

    def __init__(self):
        import torch
        self.torch = torch

    def is_appropriate_type(self, tensor):
        return isinstance(tensor, self.torch.Tensor)

    def from_numpy(self, x):
        variable = self.torch.from_numpy(x)
        if self.is_float_type(variable):
            # attach grad only to floating types
            variable.requires_grad = True
        return variable

    def to_numpy(self, x):
        return x.detach().cpu().numpy()

    def arange(self, start, stop):
        return self.torch.arange(start, stop, dtype=self.torch.int64)

    def reduce(self, x, operation, reduced_axes):
        for axis in sorted(reduced_axes, reverse=True):
            if operation == 'min':
                x, _ = x.min(dim=axis)
            elif operation == 'max':
                x, _ = x.max(dim=axis)
            elif operation in ['sum', 'mean', 'prod']:
                x = getattr(x, operation)(dim=axis)
            else:
                raise NotImplementedError('Unknown reduction ', operation)
        return x

    def transpose(self, x, axes):
        return x.permute(axes)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.torch.stack(tensors)

    def tile(self, x, repeats):
        return x.repeat(repeats)

    def add_axis(self, x, new_position):
        return self.torch.unsqueeze(x, new_position)

    def is_float_type(self, x):
        return x.dtype in [self.torch.float16, self.torch.float32, self.torch.float64]

    def layers(self):
        from .layers import torch
        return torch

class CupyBackend(AbstractBackend):
    framework_name = 'cupy'

    def __init__(self):
        import cupy
        self.cupy = cupy

    def is_appropriate_type(self, tensor):
        return isinstance(tensor, self.cupy.ndarray)

    def from_numpy(self, x):
        return self.cupy.asarray(x)

    def to_numpy(self, x):
        return self.cupy.asnumpy(x)

    def arange(self, start, stop):
        return self.cupy.arange(start, stop)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.cupy.stack(tensors)

    def tile(self, x, repeats):
        return self.cupy.tile(x, repeats)

    def add_axis(self, x, new_position):
        return self.cupy.expand_dims(x, new_position)

    def is_float_type(self, x):
        return x.dtype in ('float16', 'float32', 'float64', 'float128')

class ChainerBackend(AbstractBackend):
    framework_name = 'chainer'

    def __init__(self):
        import chainer
        import numpy
        self.numpy = numpy
        self.chainer = chainer

    def is_appropriate_type(self, tensor):
        return isinstance(tensor, self.chainer.Variable)

    def from_numpy(self, x):
        return self.chainer.Variable(x.astype('float32'))

    def to_numpy(self, x):
        if isinstance(x, self.chainer.Variable):
            x = x.data
        return x

    def arange(self, start, stop):
        return self.numpy.arange(start, stop)

    def reduce(self, x, operation, axes):
        return getattr(self.chainer.functions, operation)(x, axis=axes)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.chainer.functions.stack(tensors)

    def tile(self, x, repeats):
        return self.chainer.functions.tile(x, repeats)

    def add_axis(self, x, new_position):
        return self.chainer.functions.expand_dims(x, new_position)

    def is_float_type(self, x):
        return x.dtype in ('float16', 'float32', 'float64', 'float128')

    def layers(self):
        from .layers import chainer
        return chainer

class HashableTuple:
    """Overcomes non-hashability of symbolic elements"""

    def __init__(self, elements: tuple):
        self.elements = elements

    def __iter__(self):
        for x in self.elements:
            yield x

    def __len__(self):
        return len(self.elements)

    def __getitem__(self, item):
        return self.elements[item]

class TensorflowBackend(AbstractBackend):
    framework_name = 'tensorflow'

    def __init__(self):
        import tensorflow
        self.tf = tensorflow

    def is_appropriate_type(self, tensor):
        return isinstance(tensor, (self.tf.Tensor, self.tf.Variable))

    def from_numpy(self, x):
        assert self.tf.executing_eagerly()
        return self.tf.convert_to_tensor(x)

    def to_numpy(self, x):
        assert self.tf.executing_eagerly()
        return x.numpy()

    def arange(self, start, stop):
        return self.tf.range(start, stop)

    def shape(self, x):
        if self.tf.executing_eagerly():
            return tuple(UnknownSize() if d is None else int(d) for d in x.shape)
        else:
            static_shape = x.shape.as_list()
            tf_shape = self.tf.shape(x)
            # use the static shape where known, otherwise use the TF shape components
            shape = tuple([s or tf_shape[dim] for dim, s in enumerate(static_shape)])
            try:
                hash(shape)
                return shape
            except:
                # unhashable symbols in shape. Wrap tuple to be hashable.
                return HashableTuple(shape)

    def reduce(self, x, operation, axes):
        return getattr(self.tf, 'reduce_' + operation)(x, axis=axes)

    def reshape(self, x, shape):
        return self.tf.reshape(x, shape)

    def transpose(self, x, axes):
        return self.tf.transpose(x, axes)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.tf.stack(tensors)

    def tile(self, x, repeats):
        return self.tf.tile(x, repeats)

    def add_axis(self, x, new_position):
        return self.tf.expand_dims(x, new_position)

    def is_float_type(self, x):
        return x.dtype in ('float16', 'float32', 'float64', 'float128')

    def layers(self):
        from .layers import tensorflow
        return tensorflow

class KerasBackend(AbstractBackend):
    framework_name = 'keras'

    def __init__(self):
        import keras
        self.keras = keras
        self.K = keras.backend

    def is_appropriate_type(self, tensor):
        return self.K.is_tensor(tensor) and self.K.is_keras_tensor(tensor)

    def create_symbol(self, shape):
        return self.keras.Input(batch_shape=shape)

    def eval_symbol(self, symbol, input_dict):
        (variable, value), = input_dict
        model = self.keras.models.Model(variable, symbol)
        return model.predict_on_batch(value)

    def arange(self, start, stop):
        return self.K.arange(start, stop)

    def shape(self, x):
        shape = self.K.shape(x)  # tf tensor (if tf is backend)
        return tuple(shape[i] for i in range(shape.shape[0]))

    def reduce(self, x, operation, axes):
        return getattr(self.K, operation)(x, axis=axes)

    def reshape(self, x, shape):
        return self.K.reshape(x, shape)

    def transpose(self, x, axes):
        return self.K.permute_dimensions(x, axes)

    def stack_on_zeroth_dimension(self, tensors: list):
        return self.K.stack(tensors)

    def tile(self, x, repeats):
        return self.K.tile(x, repeats)

    def add_axis(self, x, new_position):
        return self.K.expand_dims(x, new_position)

    def is_float_type(self, x):
        return 'float' in self.K.dtype(x)

    def layers(self):
        from .layers import keras
        return keras

{'repo_name': 'arogozhnikov/einops', 'stars': '851', 'repo_language': 'Python', 'file_name': 'test_einsum.py', 'mime_type': 'text/x-python', 'hash': -876950529948247019, 'source_dataset': 'data'}


@font-face {
    font-family: myFont4;
    src: url(myFont.woff);
}

@font-face {
    font-family: myFont5;
    src: url('myFont.woff');
}

@font-face {
    font-family: myFont6;
    src: url("myFont.woff");
}

{'repo_name': 'danny0838/webscrapbook', 'stars': '334', 'repo_language': 'JavaScript', 'file_name': 'pack.cmd', 'mime_type': 'text/plain', 'hash': 1467225654238252784, 'source_dataset': 'data'}


![mqtt.js](https://raw.githubusercontent.com/mqttjs/MQTT.js/137ee0e3940c1f01049a30248c70f24dc6e6f829/MQTT.js.png)
=======

[![Build Status](https://travis-ci.org/mqttjs/MQTT.js.svg)](https://travis-ci.org/mqttjs/MQTT.js) [![codecov](https://codecov.io/gh/mqttjs/MQTT.js/branch/master/graph/badge.svg)](https://codecov.io/gh/mqttjs/MQTT.js)

[![NPM](https://nodei.co/npm-dl/mqtt.png)](https://nodei.co/npm/mqtt/) [![NPM](https://nodei.co/npm/mqtt.png)](https://nodei.co/npm/mqtt/)

[![Sauce Test Status](https://saucelabs.com/browser-matrix/mqttjs.svg)](https://saucelabs.com/u/mqttjs)

MQTT.js is a client library for the [MQTT](http://mqtt.org/) protocol, written
in JavaScript for node.js and the browser.

* [Upgrade notes](#notes)
* [Installation](#install)
* [Example](#example)
* [Command Line Tools](#cli)
* [API](#api)
* [Browser](#browser)
* [Weapp](#weapp)
* [About QoS](#qos)
* [TypeScript](#typescript)
* [Contributing](#contributing)
* [License](#license)

MQTT.js is an OPEN Open Source Project, see the [Contributing](#contributing) section to find out what this means.

[![JavaScript Style
Guide](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)

## Important notes for existing users

v2.0.0 removes support for node v0.8, v0.10 and v0.12, and it is 3x faster in sending
packets. It also removes all the deprecated functionality in v1.0.0,
mainly `mqtt.createConnection` and `mqtt.Server`. From v2.0.0,
subscriptions are restored upon reconnection if `clean: true`.
v1.x.x is now in *LTS*, and it will keep being supported as long as
there are v0.8, v0.10 and v0.12 users.

v1.0.0 improves the overall architecture of the project, which is now
split into three components: MQTT.js keeps the Client,
[mqtt-connection](http://npm.im/mqtt-connection) includes the barebone
Connection code for server-side usage, and [mqtt-packet](http://npm.im/mqtt-packet)
includes the protocol parser and generator. The new Client improves
performance by a 30% factor, embeds Websocket support
([MOWS](http://npm.im/mows) is now deprecated), and it has a better
support for QoS 1 and 2. The previous API is still supported but
deprecated, as such, it is not documented in this README.

As a __breaking change__, the `encoding` option in the old client is
removed, and now everything is UTF-8 with the exception of the
`password` in the CONNECT message and `payload` in the PUBLISH message,
which are `Buffer`.

Another __breaking change__ is that MQTT.js now defaults to MQTT v3.1.1,
so to support old brokers, please read the [client options doc](#client).

## Installation

```sh
npm install mqtt --save
```

## Example

For the sake of simplicity, let's put the subscriber and the publisher in the same file:

```js
var mqtt = require('mqtt')
var client  = mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', function () {
  client.subscribe('presence')
  client.publish('presence', 'Hello mqtt')
})

client.on('message', function (topic, message) {
  // message is Buffer
  console.log(message.toString())
  client.end()
})
```

output:
```
Hello mqtt
```

If you want to run your own MQTT broker, you can use
[Mosquitto](http://mosquitto.org) or
[Mosca](http://mcollina.github.io/mosca/), and launch it.
You can also use a test instance: test.mosquitto.org and test.mosca.io
are both public.

If you do not want to install a separate broker, you can try using the
[mqtt-connection](https://www.npmjs.com/package/mqtt-connection).

to use MQTT.js in the browser see the [browserify](#browserify) section

## Promise support

If you want to use the new [async-await](https://blog.risingstack.com/async-await-node-js-7-nightly/) functionality in JavaScript, or just prefer using Promises instead of callbacks, [async-mqtt](https://github.com/mqttjs/async-mqtt) is a wrapper over MQTT.js which uses promises instead of callbacks when possible.

## Command Line Tools

MQTT.js bundles a command to interact with a broker.
In order to have it available on your path, you should install MQTT.js
globally:

```sh
npm install mqtt -g
```

Then, on one terminal

```
mqtt sub -t 'hello' -h 'test.mosquitto.org' -v
```

On another

```
mqtt pub -t 'hello' -h 'test.mosquitto.org' -m 'from MQTT.js'
```

See `mqtt help <command>` for the command help.

## API

  * mqtt.connect()
  * mqtt.Client()
  * mqtt.Client#publish()
  * mqtt.Client#subscribe()
  * mqtt.Client#unsubscribe()
  * mqtt.Client#end()
  * mqtt.Client#removeOutgoingMessage()
  * mqtt.Client#reconnect()
  * mqtt.Client#handleMessage()
  * mqtt.Client#connected
  * mqtt.Client#reconnecting
  * mqtt.Client#getLastMessageId()
  * mqtt.Store()
  * mqtt.Store#put()
  * mqtt.Store#del()
  * mqtt.Store#createStream()
  * mqtt.Store#close()

-------------------------------------------------------

### mqtt.connect([url], options)

Connects to the broker specified by the given url and options and
returns a [Client](#client).

The URL can be on the following protocols: 'mqtt', 'mqtts', 'tcp',
'tls', 'ws', 'wss'. The URL can also be an object as returned by
[`URL.parse()`](http://nodejs.org/api/url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost),
in that case the two objects are merged, i.e. you can pass a single
object with both the URL and the connect options.

You can also specify a `servers` options with content: `[{ host:
'localhost', port: 1883 }, ... ]`, in that case that array is iterated
at every connect.

For all MQTT-related options, see the [Client](#client)
constructor.

-------------------------------------------------------

### mqtt.Client(streamBuilder, options)

The `Client` class wraps a client connection to an
MQTT broker over an arbitrary transport method (TCP, TLS,
WebSocket, ecc).

`Client` automatically handles the following:

* Regular server pings
* QoS flow
* Automatic reconnections
* Start publishing before being connected

The arguments are:

* `streamBuilder` is a function that returns a subclass of the `Stream` class that supports
the `connect` event. Typically a `net.Socket`.
* `options` is the client connection options (see: the [connect packet](https://github.com/mcollina/mqtt-packet#connect)). Defaults:
  * `wsOptions`: is the WebSocket connection options. Default is `{}`.
     It's specific for WebSockets. For possible options have a look at: https://github.com/websockets/ws/blob/master/doc/ws.md.
  * `keepalive`: `60` seconds, set to `0` to disable
  * `reschedulePings`: reschedule ping messages after sending packets (default `true`)
  * `clientId`: `'mqttjs_' + Math.random().toString(16).substr(2, 8)`
  * `protocolId`: `'MQTT'`
  * `protocolVersion`: `4`
  * `clean`: `true`, set to false to receive QoS 1 and 2 messages while
    offline
  * `reconnectPeriod`: `1000` milliseconds, interval between two
    reconnections
  * `connectTimeout`: `30 * 1000` milliseconds, time to wait before a
    CONNACK is received
  * `username`: the username required by your broker, if any
  * `password`: the password required by your broker, if any
  * `incomingStore`: a [Store](#store) for the incoming packets
  * `outgoingStore`: a [Store](#store) for the outgoing packets
  * `queueQoSZero`: if connection is broken, queue outgoing QoS zero messages (default `true`)
  * `will`: a message that will sent by the broker automatically when
     the client disconnect badly. The format is:
    * `topic`: the topic to publish
    * `payload`: the message to publish
    * `qos`: the QoS
    * `retain`: the retain flag
  * `transformWsUrl` : optional `(url, options, client) => url` function
        For ws/wss protocols only. Can be used to implement signing
        urls which upon reconnect can have become expired.
  * `resubscribe` : if connection is broken and reconnects,
     subscribed topics are automatically subscribed again (default `true`)

In case mqtts (mqtt over tls) is required, the `options` object is
passed through to
[`tls.connect()`](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback).
If you are using a **self-signed certificate**, pass the `rejectUnauthorized: false` option.
Beware that you are exposing yourself to man in the middle attacks, so it is a configuration
that is not recommended for production environments.

If you are connecting to a broker that supports only MQTT 3.1 (not
3.1.1 compliant), you should pass these additional options:

```js
{
  protocolId: 'MQIsdp',
  protocolVersion: 3
}
```

This is confirmed on RabbitMQ 3.2.4, and on Mosquitto < 1.3. Mosquitto
version 1.3 and 1.4 works fine without those.

#### Event `'connect'`

`function (connack) {}`

Emitted on successful (re)connection (i.e. connack rc=0).
* `connack` received connack packet. When `clean` connection option is `false` and server has a previous session
for `clientId` connection option, then `connack.sessionPresent` flag is `true`. When that is the case,
you may rely on stored session and prefer not to send subscribe commands for the client.

#### Event `'reconnect'`

`function () {}`

Emitted when a reconnect starts.

#### Event `'close'`

`function () {}`

Emitted after a disconnection.

#### Event `'offline'`

`function () {}`

Emitted when the client goes offline.

#### Event `'error'`

`function (error) {}`

Emitted when the client cannot connect (i.e. connack rc != 0) or when a
parsing error occurs.

#### Event `'end'`

`function () {}`

Emitted when mqtt.Client#end() is called.
If a callback was passed to `mqtt.Client#end()`, this event is emitted once the
callback returns.

#### Event `'message'`

`function (topic, message, packet) {}`

Emitted when the client receives a publish packet
* `topic` topic of the received packet
* `message` payload of the received packet
* `packet` received packet, as defined in
  [mqtt-packet](https://github.com/mcollina/mqtt-packet#publish)

#### Event `'packetsend'`

`function (packet) {}`

Emitted when the client sends any packet. This includes .published() packets
as well as packets used by MQTT for managing subscriptions and connections
* `packet` received packet, as defined in
  [mqtt-packet](https://github.com/mcollina/mqtt-packet)

#### Event `'packetreceive'`

`function (packet) {}`

Emitted when the client receives any packet. This includes packets from
subscribed topics as well as packets used by MQTT for managing subscriptions
and connections
* `packet` received packet, as defined in
  [mqtt-packet](https://github.com/mcollina/mqtt-packet)

-------------------------------------------------------

### mqtt.Client#publish(topic, message, [options], [callback])

Publish a message to a topic

* `topic` is the topic to publish to, `String`
* `message` is the message to publish, `Buffer` or `String`
* `options` is the options to publish with, including:
  * `qos` QoS level, `Number`, default `0`
  * `retain` retain flag, `Boolean`, default `false`
  * `dup` mark as duplicate flag, `Boolean`, default `false`
* `callback` - `function (err)`, fired when the QoS handling completes,
  or at the next tick if QoS 0. An error occurs if client is disconnecting.

-------------------------------------------------------

### mqtt.Client#subscribe(topic/topic array/topic object, [options], [callback])

Subscribe to a topic or topics

* `topic` is a `String` topic to subscribe to or an `Array` of
  topics to subscribe to. It can also be an object, it has as object
  keys the topic name and as value the QoS, like `{'test1': 0, 'test2': 1}`.
  MQTT `topic` wildcard characters are supported (`+` - for single level and `#` - for multi level)
* `options` is the options to subscribe with, including:
  * `qos` qos subscription level, default 0
* `callback` - `function (err, granted)`
  callback fired on suback where:
  * `err` a subscription error or an error that occurs when client is disconnecting
  * `granted` is an array of `{topic, qos}` where:
    * `topic` is a subscribed to topic
    * `qos` is the granted qos level on it

-------------------------------------------------------

### mqtt.Client#unsubscribe(topic/topic array, [callback])

Unsubscribe from a topic or topics

* `topic` is a `String` topic or an array of topics to unsubscribe from
* `callback` - `function (err)`, fired on unsuback. An error occurs if client is disconnecting.

-------------------------------------------------------

### mqtt.Client#end([force], [cb])

Close the client, accepts the following options:

* `force`: passing it to true will close the client right away, without
  waiting for the in-flight messages to be acked. This parameter is
  optional.
* `cb`: will be called when the client is closed. This parameter is
  optional.

-------------------------------------------------------

### mqtt.Client#removeOutgoingMessage(mid)

Remove a message from the outgoingStore.
The outgoing callback will be called withe Error('Message removed') if the message is removed.

After this function is called, the messageId is released and becomes reusable.

* `mid`: The messageId of the message in the outgoingStore.

-------------------------------------------------------

### mqtt.Client#reconnect()

Connect again using the same options as connect()

-------------------------------------------------------

### mqtt.Client#handleMessage(packet, callback)

Handle messages with backpressure support, one at a time.
Override at will, but __always call `callback`__, or the client
will hang.

-------------------------------------------------------

### mqtt.Client#connected

Boolean : set to `true` if the client is connected. `false` otherwise.

-------------------------------------------------------

### mqtt.Client#getLastMessageId()

Number : get last message id. This is for sent messages only.

-------------------------------------------------------

### mqtt.Client#reconnecting

Boolean : set to `true` if the client is trying to reconnect to the server. `false` otherwise.

-------------------------------------------------------

### mqtt.Store(options)

In-memory implementation of the message store.

* `options` is the store options:
  * `clean`: `true`, clean inflight messages when close is called (default `true`)

Other implementations of `mqtt.Store`:

* [mqtt-level-store](http://npm.im/mqtt-level-store) which uses
  [Level-browserify](http://npm.im/level-browserify) to store the inflight
  data, making it usable both in Node and the Browser.
* [mqtt-nedbb-store](https://github.com/behrad/mqtt-nedb-store) which
  uses [nedb](https://www.npmjs.com/package/nedb) to store the inflight
  data.
* [mqtt-localforage-store](http://npm.im/mqtt-localforage-store) which uses
  [localForage](http://npm.im/localforage) to store the inflight
  data, making it usable in the Browser without browserify.

-------------------------------------------------------

### mqtt.Store#put(packet, callback)

Adds a packet to the store, a packet is
anything that has a `messageId` property.
The callback is called when the packet has been stored.

-------------------------------------------------------

### mqtt.Store#createStream()

Creates a stream with all the packets in the store.

-------------------------------------------------------

### mqtt.Store#del(packet, cb)

Removes a packet from the store, a packet is
anything that has a `messageId` property.
The callback is called when the packet has been removed.

-------------------------------------------------------

### mqtt.Store#close(cb)

Closes the Store.

## Browser

### Via CDN

The MQTT.js bundle is available through http://unpkg.com, specifically
at https://unpkg.com/mqtt/dist/mqtt.min.js.
See http://unpkg.com for the full documentation on version ranges.

## Wexin App
Surport [Weixin App](https://mp.weixin.qq.com/). See [Doc](https://mp.weixin.qq.com/debug/wxadoc/dev/api/network-socket.html).

## Example(js)

```js
var mqtt = require('mqtt')
var client  = mqtt.connect('wxs://test.mosquitto.org')
```

## Example(ts)

```ts
import { connect } from 'mqtt';
const client  = connect('wxs://test.mosquitto.org');
```

### Browserify

In order to use MQTT.js as a browserify module you can either require it in your browserify bundles or build it as a stand alone module. The exported module is AMD/CommonJs compatible and it will add an object in the global space.

```javascript
npm install -g browserify // install browserify
cd node_modules/mqtt
npm install . // install dev dependencies
browserify mqtt.js -s mqtt > browserMqtt.js // require mqtt in your client-side app
```

### Webpack

Just like browserify, export MQTT.js as library. The exported module would be `var mqtt = xxx` and it will add an object in the global space. You could also export module in other [formats (AMD/CommonJS/others)](http://webpack.github.io/docs/configuration.html#output-librarytarget) by setting **output.libraryTarget** in webpack configuration.

```javascript
npm install -g webpack // install webpack

cd node_modules/mqtt
npm install . // install dev dependencies
webpack mqtt.js ./browserMqtt.js --output-library mqtt
```

you can then use mqtt.js in the browser with the same api than node's one.

```html
<html>
<head>
  <title>test Ws mqtt.js</title>
</head>
<body>
<script src="./browserMqtt.js"></script>
<script>
  var client = mqtt.connect() // you add a ws:// url here
  client.subscribe("mqtt/demo")

  client.on("message", function (topic, payload) {
    alert([topic, payload].join(": "))
    client.end()
  })

  client.publish("mqtt/demo", "hello world!")
</script>
</body>
</html>
```

Your broker should accept websocket connection (see [MQTT over Websockets](https://github.com/mcollina/mosca/wiki/MQTT-over-Websockets) to setup [Mosca](http://mcollina.github.io/mosca/)).

### Signed WebSocket Urls

If you need to sign an url, for example for [AWS IoT](http://docs.aws.amazon.com/iot/latest/developerguide/protocols.html#mqtt-ws),
then you can pass in a `transformWsUrl` function to the mqtt.connect() options
This is needed because signed urls have an expiry and eventually upon reconnects, a new signed url needs to be created:

```js
// This module doesn't actually exist, just an example
var awsIotUrlSigner = require('awsIotUrlSigner')
mqtt.connect('wss://a2ukbzaqo9vbpb.iot.ap-southeast-1.amazonaws.com/mqtt', {
  transformWsUrl: function (url, options, client) {
    // It's possible to inspect some state on options(pre parsed url components)
    // and the client (reconnect state etc)
    return awsIotUrlSigner(url)
  }
})

// Now every time a new WebSocket connection is opened (hopefully not that
// often) we get a freshly signed url

```

## About QoS

Here is how QoS works:

* QoS 0 : received **at most once** : The packet is sent, and that's it. There is no validation about whether it has been received.
* QoS 1 : received **at least once** : The packet is sent and stored as long as the client has not received a confirmation from the server. MQTT ensures that it *will* be received, but there can be duplicates.
* QoS 2 : received **exactly once** : Same as QoS 1 but there is no duplicates.

About data consumption, obviously, QoS 2 > QoS 1 > QoS 0, if that's a concern to you.

## Usage with TypeScript
This repo bundles TypeScript definition files for use in TypeScript projects and to support tools that can read `.d.ts` files.

### Pre-requisites
Before you can begin using these TypeScript definitions with your project, you need to make sure your project meets a few of these requirements:
 * TypeScript >= 2.1
 * Set tsconfig.json: `{"compilerOptions" : {"moduleResolution" : "node"}, ...}`
 * Includes the TypeScript definitions for node. You can use npm to install this by typing the following into a terminal window:
   `npm install --save-dev @types/node`

## Contributing

MQTT.js is an **OPEN Open Source Project**. This means that:

> Individuals making significant and valuable contributions are given commit-access to the project to contribute as they see fit. This project is more like an open wiki than a standard guarded open source project.

See the [CONTRIBUTING.md](https://github.com/mqttjs/MQTT.js/blob/master/CONTRIBUTING.md) file for more details.

### Contributors

MQTT.js is only possible due to the excellent work of the following contributors:

Adam Rudd	GitHub/adamvr	Twitter/@adam_vr

Matteo Collina	GitHub/mcollina	Twitter/@matteocollina

Maxime Agor	GitHub/4rzael	Twitter/@4rzael

## License

MIT

{'repo_name': 'derekmolloy/exploringBB', 'stars': '358', 'repo_language': 'C++', 'file_name': 'test.pyx', 'mime_type': 'text/plain', 'hash': -6485497199526893688, 'source_dataset': 'data'}


<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0//EN"
"http://www.w3.org/TR/MathML2/dtd/xhtml-math11-f.dtd" [
<!ENTITY mathml "http://www.w3.org/1998/Math/MathML">
]>

    <title>Section12.0</title>
    <link rel="stylesheet" type="text/css" href="graphicstyle.css" />

{'repo_name': 'daly/axiom', 'stars': '207', 'repo_language': 'PostScript', 'file_name': 'eucdom-gcd.pamphlet', 'mime_type': 'text/x-tex', 'hash': -8527114405443281516, 'source_dataset': 'data'}


/* Copyright (C) 2009-2018 Free Software Foundation, Inc.

   This file is part of the GNU C Library.

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public License as
   published by the Free Software Foundation; either version 2.1 of the
   License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, see
   <http://www.gnu.org/licenses/>.  */

#ifndef _SYS_USER_H
#define _SYS_USER_H	1

struct user_regs_struct
{
  unsigned long long regs[31];
  unsigned long long sp;
  unsigned long long pc;
  unsigned long long pstate;
};

struct user_fpsimd_struct
{
  __uint128_t  vregs[32];
  unsigned int fpsr;
  unsigned int fpcr;
};

#endif

{'repo_name': 'lattera/glibc', 'stars': '1078', 'repo_language': 'C', 'file_name': 'abi-note.S', 'mime_type': 'text/x-c', 'hash': 3124030006272840104, 'source_dataset': 'data'}


//
//     Generated by class-dump 3.5 (64 bit).
//
//     class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by Steve Nygard.
//

#import <Foundation/NSObject.h>

@class NSArray, NSString;

@interface UIDictationPhrase : NSObject
{
    NSString *_text;
    NSArray *_alternativeInterpretations;
}

+ (id)phraseWithText:(id)arg1 alternativeInterpretations:(id)arg2;
@property(readonly, nonatomic) NSArray *alternativeInterpretations; // @synthesize alternativeInterpretations=_alternativeInterpretations;
@property(readonly, nonatomic) NSString *text; // @synthesize text=_text;
- (id)description;
- (void)dealloc;
- (id)initWithText:(id)arg1 alternativeInterpretations:(id)arg2;

@end

{'repo_name': 'neonichu/tvOS-headers', 'stars': '152', 'repo_language': 'Objective-C', 'file_name': 'NSCoding-Protocol.h', 'mime_type': 'text/plain', 'hash': -4512679087239478084, 'source_dataset': 'data'}


//
//  SoundSetting.h
//  AudioSetting
//
//  Created by eseedo on 1/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "cocos2d.h"

@interface SoundSetting : CCLayer {

}

+(id)scene;

@end

{'repo_name': 'zilongshanren/Cocos2DBookSource', 'stars': '114', 'repo_language': 'Objective-C', 'file_name': 'Info.plist', 'mime_type': 'text/xml', 'hash': 5280880757093640834, 'source_dataset': 'data'}


// Copyright (C) 2006-2019 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library.  This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.

// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3.  If not see
// <http://www.gnu.org/licenses/>.

#include <algorithm>
#include <iterator>
#include <sstream>
#include <testsuite_hooks.h>

struct no_assign
{
  int const x;
  no_assign() : x(23) { }
  operator int() const { return x; }
};

// libstdc++/26133
void test01()
{
  std::ostringstream oss1, oss2;

  no_assign in[4];

  std::unique_copy(in, in + 4, std::ostream_iterator<int>(oss1, "\n"));
  VERIFY( oss1.str() == "23\n" );

  std::unique_copy(in, in + 4, std::ostream_iterator<int>(oss2, "\n"),
		   std::equal_to<int>());
  VERIFY( oss2.str() == "23\n" );
}

int main()
{
  test01();
  return 0;
}

{'repo_name': 'riscv/riscv-gcc', 'stars': '155', 'repo_language': 'C', 'file_name': 'visium-protos.h', 'mime_type': 'text/x-c', 'hash': 4955303229928920141, 'source_dataset': 'data'}


/*
Copyright 2014 The Kubernetes Authors All rights reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package conversion

import (
	"fmt"
	"reflect"
)

// Cloner knows how to copy one type to another.
type Cloner struct {
	// Map from the type to a function which can do the deep copy.
	deepCopyFuncs          map[reflect.Type]reflect.Value
	generatedDeepCopyFuncs map[reflect.Type]reflect.Value
}

// NewCloner creates a new Cloner object.
func NewCloner() *Cloner {
	c := &Cloner{
		deepCopyFuncs:          map[reflect.Type]reflect.Value{},
		generatedDeepCopyFuncs: map[reflect.Type]reflect.Value{},
	}
	if err := c.RegisterDeepCopyFunc(byteSliceDeepCopy); err != nil {
		// If one of the deep-copy functions is malformed, detect it immediately.
		panic(err)
	}
	return c
}

// Prevent recursing into every byte...
func byteSliceDeepCopy(in []byte, out *[]byte, c *Cloner) error {
	if in != nil {
		*out = make([]byte, len(in))
		copy(*out, in)
	} else {
		*out = nil
	}
	return nil
}

// Verifies whether a deep-copy function has a correct signature.
func verifyDeepCopyFunctionSignature(ft reflect.Type) error {
	if ft.Kind() != reflect.Func {
		return fmt.Errorf("expected func, got: %v", ft)
	}
	if ft.NumIn() != 3 {
		return fmt.Errorf("expected three 'in' params, got %v", ft)
	}
	if ft.NumOut() != 1 {
		return fmt.Errorf("expected one 'out' param, got %v", ft)
	}
	if ft.In(1).Kind() != reflect.Ptr {
		return fmt.Errorf("expected pointer arg for 'in' param 1, got: %v", ft)
	}
	if ft.In(1).Elem() != ft.In(0) {
		return fmt.Errorf("expected 'in' param 0 the same as param 1, got: %v", ft)
	}
	var forClonerType Cloner
	if expected := reflect.TypeOf(&forClonerType); ft.In(2) != expected {
		return fmt.Errorf("expected '%v' arg for 'in' param 2, got: '%v'", expected, ft.In(2))
	}
	var forErrorType error
	// This convolution is necessary, otherwise TypeOf picks up on the fact
	// that forErrorType is nil
	errorType := reflect.TypeOf(&forErrorType).Elem()
	if ft.Out(0) != errorType {
		return fmt.Errorf("expected error return, got: %v", ft)
	}
	return nil
}

// RegisterGeneratedDeepCopyFunc registers a copying func with the Cloner.
// deepCopyFunc must take three parameters: a type input, a pointer to a
// type output, and a pointer to Cloner. It should return an error.
//
// Example:
// c.RegisterGeneratedDeepCopyFunc(
//         func(in Pod, out *Pod, c *Cloner) error {
//                 // deep copy logic...
//                 return nil
//          })
func (c *Cloner) RegisterDeepCopyFunc(deepCopyFunc interface{}) error {
	fv := reflect.ValueOf(deepCopyFunc)
	ft := fv.Type()
	if err := verifyDeepCopyFunctionSignature(ft); err != nil {
		return err
	}
	c.deepCopyFuncs[ft.In(0)] = fv
	return nil
}

// Similar to RegisterDeepCopyFunc, but registers deep copy function that were
// automatically generated.
func (c *Cloner) RegisterGeneratedDeepCopyFunc(deepCopyFunc interface{}) error {
	fv := reflect.ValueOf(deepCopyFunc)
	ft := fv.Type()
	if err := verifyDeepCopyFunctionSignature(ft); err != nil {
		return err
	}
	c.generatedDeepCopyFuncs[ft.In(0)] = fv
	return nil
}

// DeepCopy will perform a deep copy of a given object.
func (c *Cloner) DeepCopy(in interface{}) (interface{}, error) {
	// Can be invalid if we run DeepCopy(X) where X is a nil interface type.
	// For example, we get an invalid value when someone tries to deep-copy
	// a nil labels.Selector.
	// This does not occur if X is nil and is a pointer to a concrete type.
	if in == nil {
		return nil, nil
	}
	inValue := reflect.ValueOf(in)
	outValue, err := c.deepCopy(inValue)
	if err != nil {
		return nil, err
	}
	return outValue.Interface(), nil
}

func (c *Cloner) deepCopy(src reflect.Value) (reflect.Value, error) {
	inType := src.Type()

	if fv, ok := c.deepCopyFuncs[inType]; ok {
		return c.customDeepCopy(src, fv)
	}
	if fv, ok := c.generatedDeepCopyFuncs[inType]; ok {
		return c.customDeepCopy(src, fv)
	}
	return c.defaultDeepCopy(src)
}

func (c *Cloner) customDeepCopy(src, fv reflect.Value) (reflect.Value, error) {
	outValue := reflect.New(src.Type())
	args := []reflect.Value{src, outValue, reflect.ValueOf(c)}
	result := fv.Call(args)[0].Interface()
	// This convolution is necessary because nil interfaces won't convert
	// to error.
	if result == nil {
		return outValue.Elem(), nil
	}
	return outValue.Elem(), result.(error)
}

func (c *Cloner) defaultDeepCopy(src reflect.Value) (reflect.Value, error) {
	switch src.Kind() {
	case reflect.Chan, reflect.Func, reflect.UnsafePointer, reflect.Uintptr:
		return src, fmt.Errorf("cannot deep copy kind: %s", src.Kind())
	case reflect.Array:
		dst := reflect.New(src.Type())
		for i := 0; i < src.Len(); i++ {
			copyVal, err := c.deepCopy(src.Index(i))
			if err != nil {
				return src, err
			}
			dst.Elem().Index(i).Set(copyVal)
		}
		return dst.Elem(), nil
	case reflect.Interface:
		if src.IsNil() {
			return src, nil
		}
		return c.deepCopy(src.Elem())
	case reflect.Map:
		if src.IsNil() {
			return src, nil
		}
		dst := reflect.MakeMap(src.Type())
		for _, k := range src.MapKeys() {
			copyVal, err := c.deepCopy(src.MapIndex(k))
			if err != nil {
				return src, err
			}
			dst.SetMapIndex(k, copyVal)
		}
		return dst, nil
	case reflect.Ptr:
		if src.IsNil() {
			return src, nil
		}
		dst := reflect.New(src.Type().Elem())
		copyVal, err := c.deepCopy(src.Elem())
		if err != nil {
			return src, err
		}
		dst.Elem().Set(copyVal)
		return dst, nil
	case reflect.Slice:
		if src.IsNil() {
			return src, nil
		}
		dst := reflect.MakeSlice(src.Type(), 0, src.Len())
		for i := 0; i < src.Len(); i++ {
			copyVal, err := c.deepCopy(src.Index(i))
			if err != nil {
				return src, err
			}
			dst = reflect.Append(dst, copyVal)
		}
		return dst, nil
	case reflect.Struct:
		dst := reflect.New(src.Type())
		for i := 0; i < src.NumField(); i++ {
			if !dst.Elem().Field(i).CanSet() {
				// Can't set private fields. At this point, the
				// best we can do is a shallow copy. For
				// example, time.Time is a value type with
				// private members that can be shallow copied.
				return src, nil
			}
			copyVal, err := c.deepCopy(src.Field(i))
			if err != nil {
				return src, err
			}
			dst.Elem().Field(i).Set(copyVal)
		}
		return dst.Elem(), nil

	default:
		// Value types like numbers, booleans, and strings.
		return src, nil
	}
}

{'repo_name': 'kubernetes-retired/contrib', 'stars': '2411', 'repo_language': 'Go', 'file_name': 'pod.yaml', 'mime_type': 'text/plain', 'hash': -20870166191194509, 'source_dataset': 'data'}


*> \brief \b DDRVRF2
*
*  =========== DOCUMENTATION ===========
*
* Online html documentation available at
*            http://www.netlib.org/lapack/explore-html/
*
*  Definition:
*  ===========
*
*       SUBROUTINE DDRVRF2( NOUT, NN, NVAL, A, LDA, ARF, AP, ASAV  )
*
*       .. Scalar Arguments ..
*       INTEGER            LDA, NN, NOUT
*       ..
*       .. Array Arguments ..
*       INTEGER            NVAL( NN )
*       DOUBLE PRECISION   A( LDA, * ), ARF( * ), AP(*), ASAV( LDA, * )
*       ..
*
*
*> \par Purpose:
*  =============
*>
*> \verbatim
*>
*> DDRVRF2 tests the LAPACK RFP convertion routines.
*> \endverbatim
*
*  Arguments:
*  ==========
*
*> \param[in] NOUT
*> \verbatim
*>          NOUT is INTEGER
*>                The unit number for output.
*> \endverbatim
*>
*> \param[in] NN
*> \verbatim
*>          NN is INTEGER
*>                The number of values of N contained in the vector NVAL.
*> \endverbatim
*>
*> \param[in] NVAL
*> \verbatim
*>          NVAL is INTEGER array, dimension (NN)
*>                The values of the matrix dimension N.
*> \endverbatim
*>
*> \param[out] A
*> \verbatim
*>          A is DOUBLE PRECISION array, dimension (LDA,NMAX)
*> \endverbatim
*>
*> \param[in] LDA
*> \verbatim
*>          LDA is INTEGER
*>                The leading dimension of the array A.  LDA >= max(1,NMAX).
*> \endverbatim
*>
*> \param[out] ARF
*> \verbatim
*>          ARF is DOUBLE PRECISION array, dimension ((NMAX*(NMAX+1))/2).
*> \endverbatim
*>
*> \param[out] AP
*> \verbatim
*>          AP is DOUBLE PRECISION array, dimension ((NMAX*(NMAX+1))/2).
*> \endverbatim
*>
*> \param[out] ASAV
*> \verbatim
*>          ASAV is DOUBLE PRECISION array, dimension (LDA,NMAX)
*> \endverbatim
*
*  Authors:
*  ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup double_lin
*
*  =====================================================================
      SUBROUTINE DDRVRF2( NOUT, NN, NVAL, A, LDA, ARF, AP, ASAV  )
*
*  -- LAPACK test routine (version 3.4.0) --
*  -- LAPACK is a software package provided by Univ. of Tennessee,    --
*  -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
*     November 2011
*
*     .. Scalar Arguments ..
      INTEGER            LDA, NN, NOUT
*     ..
*     .. Array Arguments ..
      INTEGER            NVAL( NN )
      DOUBLE PRECISION   A( LDA, * ), ARF( * ), AP(*), ASAV( LDA, * )
*     ..
*
*  =====================================================================
*     ..
*     .. Local Scalars ..
      LOGICAL            LOWER, OK1, OK2
      CHARACTER          UPLO, CFORM
      INTEGER            I, IFORM, IIN, INFO, IUPLO, J, N,
     +                   NERRS, NRUN
*     ..
*     .. Local Arrays ..
      CHARACTER          UPLOS( 2 ), FORMS( 2 )
      INTEGER            ISEED( 4 ), ISEEDY( 4 )
*     ..
*     .. External Functions ..
      DOUBLE PRECISION   DLARND
      EXTERNAL           DLARND
*     ..
*     .. External Subroutines ..
      EXTERNAL           DTFTTR, DTFTTP, DTRTTF, DTRTTP, DTPTTR, DTPTTF
*     ..
*     .. Scalars in Common ..
      CHARACTER*32       SRNAMT
*     ..
*     .. Common blocks ..
      COMMON             / SRNAMC / SRNAMT
*     ..
*     .. Data statements ..
      DATA               ISEEDY / 1988, 1989, 1990, 1991 /
      DATA               UPLOS / 'U', 'L' /
      DATA               FORMS / 'N', 'T' /
*     ..
*     .. Executable Statements ..
*
*     Initialize constants and the random number seed.
*
      NRUN = 0
      NERRS = 0
      INFO = 0
      DO 10 I = 1, 4
         ISEED( I ) = ISEEDY( I )
   10 CONTINUE
*
      DO 120 IIN = 1, NN
*
         N = NVAL( IIN )
*
*        Do first for UPLO = 'U', then for UPLO = 'L'
*
         DO 110 IUPLO = 1, 2
*
            UPLO = UPLOS( IUPLO )
            LOWER = .TRUE.
            IF ( IUPLO.EQ.1 ) LOWER = .FALSE.
*
*           Do first for CFORM = 'N', then for CFORM = 'T'
*
            DO 100 IFORM = 1, 2
*
               CFORM = FORMS( IFORM )
*
               NRUN = NRUN + 1
*
               DO J = 1, N
                  DO I = 1, N
                     A( I, J) = DLARND( 2, ISEED )
                  END DO
               END DO
*
               SRNAMT = 'DTRTTF'
               CALL DTRTTF( CFORM, UPLO, N, A, LDA, ARF, INFO )
*
               SRNAMT = 'DTFTTP'
               CALL DTFTTP( CFORM, UPLO, N, ARF, AP, INFO )
*
               SRNAMT = 'DTPTTR'
               CALL DTPTTR( UPLO, N, AP, ASAV, LDA, INFO )
*
               OK1 = .TRUE.
               IF ( LOWER ) THEN
                  DO J = 1, N
                     DO I = J, N
                        IF ( A(I,J).NE.ASAV(I,J) ) THEN
                           OK1 = .FALSE.
                        END IF
                     END DO
                  END DO
               ELSE
                  DO J = 1, N
                     DO I = 1, J
                        IF ( A(I,J).NE.ASAV(I,J) ) THEN
                           OK1 = .FALSE.
                        END IF
                     END DO
                  END DO
               END IF
*
               NRUN = NRUN + 1
*
               SRNAMT = 'DTRTTP'
               CALL DTRTTP( UPLO, N, A, LDA, AP, INFO )
*
               SRNAMT = 'DTPTTF'
               CALL DTPTTF( CFORM, UPLO, N, AP, ARF, INFO )
*
               SRNAMT = 'DTFTTR'
               CALL DTFTTR( CFORM, UPLO, N, ARF, ASAV, LDA, INFO )
*
               OK2 = .TRUE.
               IF ( LOWER ) THEN
                  DO J = 1, N
                     DO I = J, N
                        IF ( A(I,J).NE.ASAV(I,J) ) THEN
                           OK2 = .FALSE.
                        END IF
                     END DO
                  END DO
               ELSE
                  DO J = 1, N
                     DO I = 1, J
                        IF ( A(I,J).NE.ASAV(I,J) ) THEN
                           OK2 = .FALSE.
                        END IF
                     END DO
                  END DO
               END IF
*
               IF (( .NOT.OK1 ).OR.( .NOT.OK2 )) THEN
                  IF( NERRS.EQ.0 ) THEN
                     WRITE( NOUT, * )
                     WRITE( NOUT, FMT = 9999 )
                  END IF
                  WRITE( NOUT, FMT = 9998 ) N, UPLO, CFORM
                  NERRS = NERRS + 1
               END IF
*
  100       CONTINUE
  110    CONTINUE
  120 CONTINUE
*
*     Print a summary of the results.
*
      IF ( NERRS.EQ.0 ) THEN
         WRITE( NOUT, FMT = 9997 ) NRUN
      ELSE
         WRITE( NOUT, FMT = 9996 ) NERRS, NRUN
      END IF
*
 9999 FORMAT( 1X, ' *** Error(s) while testing the RFP convertion',
     +         ' routines ***')
 9998 FORMAT( 1X, '     Error in RFP,convertion routines N=',I5,
     +        ' UPLO=''', A1, ''', FORM =''',A1,'''')
 9997 FORMAT( 1X, 'All tests for the RFP convertion routines passed ( ',
     +        I5,' tests run)')
 9996 FORMAT( 1X, 'RFP convertion routines: ',I5,' out of ',I5,
     +        ' error message recorded')
*
      RETURN
*
*     End of DDRVRF2
*
      END

{'repo_name': 'flame/libflame', 'stars': '182', 'repo_language': 'Fortran', 'file_name': 'zlatme.f', 'mime_type': 'text/plain', 'hash': 6433739132544912349, 'source_dataset': 'data'}


####
# test_shared.py:
#
# CMake tests to ensure that shared libraries are output as part of the build.
#
####
import os
import platform
import cmake

ext = "so"
if platform.system() == "Windows":
    ext = "dll"
elif platform.system() == "Darwin":
    ext = "dylib"

# Test a normal build, with the ref executable and static libraries
BUILD_DIR = os.path.join("<FPRIME>", "Ref")
OPTIONS = {"BUILD_SHARED_LIBS": "ON"}
EXPECTED = [
    os.path.join("bin", platform.system(), "Ref"),
    os.path.join("<FPRIME>", "Ref", "Top", "RefTopologyAppDictionary.xml"),
    os.path.join("lib", platform.system(), "libDrv_BlockDriver." + ext),
    os.path.join("lib", platform.system(), "libSvc_FileUplink." + ext),
    os.path.join("lib", platform.system(), "libSvc_CmdSequencer." + ext),
    os.path.join("lib", platform.system(), "libFw_Time." + ext),
    os.path.join("lib", platform.system(), "libSvc_FileManager." + ext),
    os.path.join("lib", platform.system(), "libSvc_PolyDb." + ext),
    os.path.join("lib", platform.system(), "libRef_SendBuffApp." + ext),
    os.path.join("lib", platform.system(), "libFw_FilePacket." + ext),
    os.path.join("lib", platform.system(), "libSvc_Ping." + ext),
    os.path.join("lib", platform.system(), "libFw_Types." + ext),
    os.path.join("lib", platform.system(), "libUtils_Hash." + ext),
    os.path.join("lib", platform.system(), "libFw_Port." + ext),
    os.path.join("lib", platform.system(), "libSvc_RateGroupDriver." + ext),
    os.path.join("lib", platform.system(), "libSvc_FatalHandler." + ext),
    os.path.join("lib", platform.system(), "libSvc_TlmChan." + ext),
    os.path.join("lib", platform.system(), "libFw_Obj." + ext),
    os.path.join("lib", platform.system(), "libFw_Prm." + ext),
    os.path.join("lib", platform.system(), "libSvc_ActiveRateGroup." + ext),
    os.path.join("lib", platform.system(), "libSvc_Cycle." + ext),
    os.path.join("lib", platform.system(), "libSvc_Health." + ext),
    os.path.join("lib", platform.system(), "libSvc_LinuxTime." + ext),
    os.path.join("lib", platform.system(), "libRef_PingReceiver." + ext),
    os.path.join("lib", platform.system(), "libFw_Com." + ext),
    os.path.join("lib", platform.system(), "libDrv_DataTypes." + ext),
    os.path.join("lib", platform.system(), "libSvc_ComLogger." + ext),
    os.path.join("lib", platform.system(), "libFw_SerializableFile." + ext),
    os.path.join("lib", platform.system(), "libFw_Buffer." + ext),
    os.path.join("lib", platform.system(), "libFw_Comp." + ext),
    os.path.join("lib", platform.system(), "libSvc_CmdDispatcher." + ext),
    os.path.join("lib", platform.system(), "libFw_Log." + ext),
    os.path.join("lib", platform.system(), "libFw_Tlm." + ext),
    os.path.join("lib", platform.system(), "libOs." + ext),
    os.path.join("lib", platform.system(), "libRef_SignalGen." + ext),
    os.path.join("lib", platform.system(), "libSvc_Sched." + ext),
    os.path.join("lib", platform.system(), "libSvc_Seq." + ext),
    os.path.join("lib", platform.system(), "libSvc_WatchDog." + ext),
    os.path.join("lib", platform.system(), "libSvc_AssertFatalAdapter." + ext),
    os.path.join("lib", platform.system(), "libSvc_PolyIf." + ext),
    os.path.join("lib", platform.system(), "libSvc_FileDownlink." + ext),
    os.path.join("lib", platform.system(), "libFw_ComFile." + ext),
    os.path.join("lib", platform.system(), "libRef_RecvBuffApp." + ext),
    os.path.join("lib", platform.system(), "libSvc_Time." + ext),
    os.path.join("lib", platform.system(), "libFw_Cfg." + ext),
    os.path.join("lib", platform.system(), "libSvc_Fatal." + ext),
    os.path.join("lib", platform.system(), "libSvc_ActiveLogger." + ext),
    os.path.join("lib", platform.system(), "libSvc_BufferManager." + ext),
    os.path.join("lib", platform.system(), "libFw_Cmd." + ext),
    os.path.join("lib", platform.system(), "libCFDP_Checksum." + ext),
    os.path.join("lib", platform.system(), "libSvc_PrmDb." + ext),
    os.path.join("lib", platform.system(), "libSvc_PassiveConsoleTextLogger." + ext),
]
cmake.register_test(__name__, "ref-shared")

{'repo_name': 'nasa/fprime', 'stars': '203', 'repo_language': 'C++', 'file_name': 'SocketIpDriver.md', 'mime_type': 'text/html', 'hash': -6901799889253642182, 'source_dataset': 'data'}


import random

letters = list("abcdefghijklmnopqrstuvxyz\n")

for i in range(10):
    for i in range(15):
        print(random.choice(letters), end="", flush=True)

{'repo_name': 'Disiok/poetry-seq2seq', 'stars': '158', 'repo_language': 'Jupyter Notebook', 'file_name': 'no_previous', 'mime_type': 'text/plain', 'hash': -4522746534025960232, 'source_dataset': 'data'}