text:
// Copyright 2019 Google LLC
//
// 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 com.google.chcapi.perfdiag.benchmark;

import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicReference;

import java.io.PrintStream;
import java.io.ByteArrayOutputStream;

import picocli.CommandLine.Mixin;
import picocli.CommandLine.Command;

import org.apache.commons.io.output.NullOutputStream;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;

import com.google.chcapi.perfdiag.model.Attributes;
import com.google.chcapi.perfdiag.benchmark.config.DicomStoreConfig;
import com.google.chcapi.perfdiag.benchmark.stats.MetricAggregates;
import com.google.chcapi.perfdiag.profiler.HttpRequestProfiler;
import com.google.chcapi.perfdiag.profiler.HttpRequestProfilerFactory;
import com.google.chcapi.perfdiag.profiler.HttpRequestMetrics;

/**
 * This benchmark shows the user how fast it is to download a large dataset (a whole DICOM store).
 * It involves sending requests to get study information (QIDO) and sending paralleled requests to
 * retrieve all studies in the dicom store (WADO).
 *
 * @author Mikhail Ukhlin
 */
@Command
public class DownloadDatasetBenchmark extends Benchmark {

  /**
   * DICOM store configuration from command line.
   */
  @Mixin
  protected DicomStoreConfig dicomStoreConfig;

  /**
   * Aggregates for latency of querying studies.
   */
  private MetricAggregates queryStudiesAggregates;

  /**
   * Aggregates for latency of first byte received.
   */
  private MetricAggregates firstResponseAggregates;

  /**
   * Aggregates for latency of reading first study.
   */
  private MetricAggregates firstStudyAggregates;

  /**
   * Aggregates for latency of downloading the whole dataset.
   */
  private MetricAggregates totalAggregates;

  /**
   * Aggregates for transfer rate of downloading the whole dataset.
   */
  private MetricAggregates transferRateAggregates;

  /**
   * Validates configuration and initializes aggregates.
   */
  @Override
  protected void validateConfig() {
    super.validateConfig();
    final int iterations = commonConfig.getIterations();
    queryStudiesAggregates = new MetricAggregates(iterations);
    firstResponseAggregates = new MetricAggregates(iterations);
    firstStudyAggregates = new MetricAggregates(iterations);
    totalAggregates = new MetricAggregates(iterations);
    transferRateAggregates = new MetricAggregates(iterations);
  }

  /**
   * Retrieves DICOM studies in parallel and stores metrics for each request to the specified
   * output stream if any.
   *
   * @param iteration Iteration number.
   * @param output Output stream to write metrics or {@code null} if output file is not specified.
   * @throws Exception if an error occurred.
   */
  @Override
  protected void runIteration(int iteration, PrintStream output) throws Exception {
    final AtomicReference<HttpRequestMetrics> firstResponseMetrics = new AtomicReference<>();
    final AtomicReference<HttpRequestMetrics> firstStudyMetrics = new AtomicReference<>();

    // Fetch list of available studies
    final HttpRequestProfiler queryStudiesRequest =
        HttpRequestProfilerFactory.createListDicomStudiesRequest(dicomStoreConfig);
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    final long iterationStartTime = System.currentTimeMillis();
    final HttpRequestMetrics queryStudiesMetrics = queryStudiesRequest.execute(buffer);
    final List<Attributes> studies = MAPPER.readValue(buffer.toByteArray(),
        new TypeReference<List<Attributes>>() {});
    final int threadCount = Math.min(commonConfig.getMaxThreads(), studies.size());
    printStudiesFound(studies.size(), threadCount);

    if (studies.size() > 0) {
      // Create separate task for each study
      final ExecutorService pool = Executors.newFixedThreadPool(threadCount);
      final List<Callable<HttpRequestMetrics>> tasks = new ArrayList<>();
      for (Attributes study : studies) {
        final String studyId = study.getStudyUID();
        if (studyId != null) {
          tasks.add(new Callable<HttpRequestMetrics>() {
            @Override public HttpRequestMetrics call() throws Exception {
              // Execute request
              final HttpRequestProfiler request =
                  HttpRequestProfilerFactory.createRetrieveDicomStudyRequest(dicomStoreConfig, studyId);
              final HttpRequestMetrics metrics = request.execute(NullOutputStream.NULL_OUTPUT_STREAM);

              // Update first response and first study metrics
              firstResponseMetrics.updateAndGet(m -> {
                return m == null || metrics.getResponseTime() < m.getResponseTime() ? metrics : m;
              });
              firstStudyMetrics.updateAndGet(m -> {
                return m == null || metrics.getEndTime() < m.getEndTime() ? metrics : m;
              });

              // Print progress
              printProgress();
              return metrics;
            }
          });
        }
      }

      // Wait for completion
      final List<Future<HttpRequestMetrics>> futures = pool.invokeAll(tasks);
      final long totalLatency = System.currentTimeMillis() - iterationStartTime;

      // Print requests metrics and count bytes read
      int cacheHits = 0;
      int cacheMisses = 0;
      long totalBytesRead = queryStudiesMetrics.getBytesRead();
      for (Future<HttpRequestMetrics> future : futures) {
        try {
          final HttpRequestMetrics metrics = future.get();
          totalBytesRead += metrics.getBytesRead();
          cacheHits = metrics.getCacheStatus().incrementHits(cacheHits);
          cacheMisses = metrics.getCacheStatus().incrementMisses(cacheMisses);
        } catch (Exception e) {
          printRequestFailed(e);
        }
      }

      // Update aggregates
      final double transferRate = (double) totalBytesRead / (double) totalLatency / 1048.576;
      queryStudiesAggregates.addValue(queryStudiesMetrics.getTotalLatency());
      firstResponseAggregates.addValue(firstResponseMetrics.get().getResponseLatency());
      firstStudyAggregates.addValue(firstStudyMetrics.get().getTotalLatency());
      totalAggregates.addValue(totalLatency);
      transferRateAggregates.addValue(transferRate);

      // Print iteration metrics to stdout
      printDownloadDatasetMetrics(queryStudiesMetrics.getTotalLatency(),
          firstResponseMetrics.get().getResponseLatency(), firstStudyMetrics.get().getTotalLatency(),
          totalLatency, totalBytesRead, transferRate, cacheHits, cacheMisses);

      // Print iteration metrics to CSV file if output option is specified
      if (output != null) {
        if (iteration == 0) {
          output.println("ITERATION, QUERYING_STUDIES_LATENCY, FIRST_BYTE_RECEIVED_LATENCY, "
              + "READING_FIRST_STUDY_LATENCY, READING_WHOLE_DATASET_LATENCY, "
              + "TOTAL_BYTES_READ, MB_READ_PER_SECOND");
        }
        output.print(iteration);
        output.print(", ");
        output.print(queryStudiesMetrics.getTotalLatency());
        output.print(", ");
        output.print(firstResponseMetrics.get().getResponseLatency());
        output.print(", ");
        output.print(firstStudyMetrics.get().getTotalLatency());
        output.print(", ");
        output.print(totalLatency);
        output.print(", ");
        output.print(totalBytesRead);
        output.print(", ");
        output.print(transferRate);
        output.println();
      }
    }
  }

  /**
   * Prints calculated aggreagtes for all iterations to stdout.
   */
  @Override
  protected void printAggregates() {
    printDownloadDatasetAggregates(queryStudiesAggregates, firstResponseAggregates,
        firstStudyAggregates, totalAggregates, transferRateAggregates);
  }

  /* Object mapper to convert JSON response */
  private static final ObjectMapper MAPPER = new ObjectMapper()
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

}


text:
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser')
var express = require('express');
var morgan = require('morgan');
var userRoutes = require('../users/userRoutes');
var questionRoutes = require('../questions/questionRoutes');

module.exports = function(app) {

  app.use(bodyParser.json());

  //Allows for the use of cookies for authentication
  app.use(cookieParser());

  //Logging middleware which allows all requests to be visible in the terminal
  app.use(morgan());

  app.use(express.static(__dirname + '/../../client/'));

  userRoutes(app);
  questionRoutes(app);
};

redpajama_set_name: RedPajamaGithub


text:
[![NPM version][npm-version-image]][npm-url] [![NPM quality][npm-quality]](http://packagequality.com/#?package=total.js) [![NPM downloads][npm-downloads-image]][npm-url] [![MIT License][license-image]][license-url]

- [__Live chat with professional support__](https://messenger.totaljs.com)
- [__HelpDesk with professional support__](https://helpdesk.totaljs.com)

Node.js PayPal Express Checkout
===============================

* Easy to use
* __No dependencies__
* [Full source-code of the eshop with PayPal written in node.js](http://www.totaljs.com/eshop/)

PayPal account
--------------

Read here: <https://developer.paypal.com/docs/classic/api/apiCredentials/#creating-an-api-signature>

- Log in to your PayPal business account at www.paypal.com. Click the profile icon ( Profile menu ) on the top right side of the page. From the Business Profile menu, select Profile and Settings.
- From the left menu, click My selling tools.
- In the Selling online section, click the Update link for the API access item.
- To generate the API signature, click Request API Credentials on the API Access page. ![Request API credentials](https://www.paypalobjects.com/webstatic/en_US/developer/docs/api/classicApiCerts/requestApiCreds.png)
- Select Request API signature and click Agree and Submit to generate the API signature. ![Signature](https://www.paypalobjects.com/webstatic/en_US/developer/docs/api/classicApiCerts/signatureCredentials.png)

***

```text
$ npm install paypal-express-checkout
```

***

```javascript
var Paypal = require('paypal-express-checkout');
// debug = optional, defaults to false, if true then paypal's sandbox url is used
// paypal.init('some username', 'some password', 'signature', 'return url', 'cancel url', debug);
var paypal = Paypal.init('username', 'password', 'signature', 'http://www.example.com/return', 'http://www.example.com/cancel', true);

// Localization (OPTIONAL): https://developer.paypal.com/docs/classic/api/locale_codes/
// paypal.locale = 'SK';
// or
// paypal.locale = 'en_US';

// checkout
// requireAddress = optional, defaults to false
// paypal.pay('Invoice number', amount, 'description', 'currency', requireAddress, callback);
// paypal.pay('20130001', 123.23, 'iPad', 'EUR', function(err, url) {
// or with "requireAddress": true
paypal.pay('20130001', 123.23, 'iPad', 'EUR', true, function(err, url) {
	if (err) {
		console.log(err);
		return;
	}

	// redirect to paypal webpage
	response.redirect(url);
});

// result in GET method
// paypal.detail('token', 'PayerID', callback);
// or
// paypal.detail(totaljs.controller, callback);

paypal.detail('EC-788441863R616634K', '9TM892TKTDWCE', function(err, data, invoiceNumber, price) {

	if (err) {
		console.log(err);
		return;
	}

	// data.success == {Boolean}

	if (data.success)
		console.log('DONE, PAYMENT IS COMPLETED.');
	else
		console.log('SOME PROBLEM:', data);

	/*
	data (object) =
	{ TOKEN: 'EC-35S39602J3144082X',
	  TIMESTAMP: '2013-01-27T08:47:50Z',
	  CORRELATIONID: 'e51b76c4b3dc1',
	  ACK: 'Success',
	  VERSION: '52.0',
	  BUILD: '4181146',
	  TRANSACTIONID: '87S10228Y4778651P',
	  TRANSACTIONTYPE: 'expresscheckout',
	  PAYMENTTYPE: 'instant',
	  ORDERTIME: '2013-01-27T08:47:49Z',
	  AMT: '10.00',
	  TAXAMT: '0.00',
	  CURRENCYCODE: 'EUR',
	  PAYMENTSTATUS: 'Pending',
	  PENDINGREASON: 'multicurrency',
	  REASONCODE: 'None' };
	*/

});

```

## PayPal PAYMENTSTATUS

```
Canceled_Reversal: A reversal has been canceled. For example, you won a dispute with the customer, and the funds for the transaction that was reversed have been returned to you.
Completed: The payment has been completed, and the funds have been added successfully to your account balance.
Created: A German ELV payment is made using Express Checkout.
Denied: You denied the payment. This happens only if the payment was previously pending because of possible reasons described for the pending_reason variable or the Fraud_Management_Filters_x variable.
Expired: This authorization has expired and cannot be captured.
Failed: The payment has failed. This happens only if the payment was made from your customer's bank account.
Pending: The payment is pending. See pending_reason for more information.
Refunded: You refunded the payment.
Reversed: A payment was reversed due to a chargeback or other type of reversal. The funds have been removed from your account balance and returned to the buyer. The reason for the reversal is specified in the ReasonCode element.
Processed: A payment has been accepted.
Voided: This authorization has been voided.
```

## How to prevent of pending paymentstatus?

> Login into your bussiness account and click here: https://www.sandbox.paypal.com/ca/cgi-bin/?cmd=_profile-pref&source=acct_setup&fli=true

## Contributors

| Contributor | Type | E-mail |
|-------------|------|--------|
| [Peter Širka](https://www.petersirka.eu) | author + support | <petersirka@gmail.com> |
| [Martin Smola](https://github.com/molda) | support + contributor | <smola.martin@gmail.com> |
| [Johann Botha](https://github.com/johannbotha) | contributor | <johannbbotha@gmail.com> |

## Images

![Payment Card Types](https://www.paypalobjects.com/webstatic/en_US/i/buttons/cc-badges-ppmcvdam.png)

![PayPal Express Checkout Button](https://www.paypalobjects.com/webstatic/en_US/i/btn/png/gold-pill-paypalcheckout-34px.png)

[license-image]: https://img.shields.io/badge/license-MIT-blue.svg?style=flat
[license-url]: license.txt

[npm-url]: https://npmjs.org/package/total.js
[npm-version-image]: https://img.shields.io/npm/v/total.js.svg?style=flat
[npm-downloads-image]: https://img.shields.io/npm/dm/total.js.svg?style=flat
[npm-quality]: http://npm.packagequality.com/shield/total.js.svg


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.FileUpload = void 0;

var _react = _interopRequireWildcard(require("react"));

var _propTypes = _interopRequireDefault(require("prop-types"));

var _Button = require("../button/Button");

var _Messages = require("../messages/Messages");

var _ProgressBar = require("../progressbar/ProgressBar");

var _DomHandler = _interopRequireDefault(require("../utils/DomHandler"));

var _classnames = _interopRequireDefault(require("classnames"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; if (obj != null) { var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }

function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }

function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }

function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

var FileUpload =
/*#__PURE__*/
function (_Component) {
  _inherits(FileUpload, _Component);

  function FileUpload(props) {
    var _this;

    _classCallCheck(this, FileUpload);

    _this = _possibleConstructorReturn(this, _getPrototypeOf(FileUpload).call(this, props));
    _this.state = {
      files: [],
      msgs: []
    };
    _this.upload = _this.upload.bind(_assertThisInitialized(_this));
    _this.clear = _this.clear.bind(_assertThisInitialized(_this));
    _this.onFileSelect = _this.onFileSelect.bind(_assertThisInitialized(_this));
    _this.onDragEnter = _this.onDragEnter.bind(_assertThisInitialized(_this));
    _this.onDragOver = _this.onDragOver.bind(_assertThisInitialized(_this));
    _this.onDragLeave = _this.onDragLeave.bind(_assertThisInitialized(_this));
    _this.onDrop = _this.onDrop.bind(_assertThisInitialized(_this));
    _this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this));
    _this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this));
    _this.onSimpleUploaderClick = _this.onSimpleUploaderClick.bind(_assertThisInitialized(_this));
    return _this;
  }

  _createClass(FileUpload, [{
    key: "hasFiles",
    value: function hasFiles() {
      return this.state.files && this.state.files.length > 0;
    }
  }, {
    key: "isImage",
    value: function isImage(file) {
      return /^image\//.test(file.type);
    }
  }, {
    key: "remove",
    value: function remove(index) {
      this.clearInputElement();

      var currentFiles = _toConsumableArray(this.state.files);

      currentFiles.splice(index, 1);
      this.setState({
        files: currentFiles
      });
    }
  }, {
    key: "clearInputElement",
    value: function clearInputElement() {
      this.fileInput.value = '';

      if (this.props.mode === 'basic') {
        this.fileInput.style.display = 'inline';
      }
    }
  }, {
    key: "formatSize",
    value: function formatSize(bytes) {
      if (bytes === 0) {
        return '0 B';
      }

      var k = 1000,
          dm = 3,
          sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
          i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
    }
  }, {
    key: "onFileSelect",
    value: function onFileSelect(event) {
      var _this2 = this;

      this.setState({
        msgs: []
      });
      this.files = this.state.files || [];
      var files = event.dataTransfer ? event.dataTransfer.files : event.target.files;

      for (var i = 0; i < files.length; i++) {
        var file = files[i];

        if (!this.isFileSelected(file)) {
          if (this.validate(file)) {
            if (this.isImage(file)) {
              file.objectURL = window.URL.createObjectURL(file);
            }

            this.files.push(file);
          }
        }
      }

      this.setState({
        files: this.files
      }, function () {
        if (_this2.hasFiles() && _this2.props.auto) {
          _this2.upload();
        }
      });

      if (this.props.onSelect) {
        this.props.onSelect({
          originalEvent: event,
          files: files
        });
      }

      this.clearInputElement();

      if (this.props.mode === 'basic') {
        this.fileInput.style.display = 'none';
      }
    }
  }, {
    key: "isFileSelected",
    value: function isFileSelected(file) {
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = this.state.files[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          var sFile = _step.value;
          if (sFile.name + sFile.type + sFile.size === file.name + file.type + file.size) return true;
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }

      return false;
    }
  }, {
    key: "validate",
    value: function validate(file) {
      if (this.props.maxFileSize && file.size > this.props.maxFileSize) {
        var message = {
          severity: 'error',
          summary: this.props.invalidFileSizeMessageSummary.replace('{0}', file.name),
          detail: this.props.invalidFileSizeMessageDetail.replace('{0}', this.formatSize(this.props.maxFileSize))
        };

        if (this.props.mode === 'advanced') {
          this.messagesUI.show(message);
        }

        if (this.props.onValidationFail) {
          this.props.onValidationFail(file);
        }

        return false;
      }

      return true;
    }
  }, {
    key: "upload",
    value: function upload() {
      var _this3 = this;

      if (this.props.customUpload) {
        if (this.props.uploadHandler) {
          this.props.uploadHandler({
            files: this.state.files
          });
        }
      } else {
        this.setState({
          msgs: []
        });
        var xhr = new XMLHttpRequest();
        var formData = new FormData();

        if (this.props.onBeforeUpload) {
          this.props.onBeforeUpload({
            'xhr': xhr,
            'formData': formData
          });
        }

        var _iteratorNormalCompletion2 = true;
        var _didIteratorError2 = false;
        var _iteratorError2 = undefined;

        try {
          for (var _iterator2 = this.state.files[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
            var file = _step2.value;
            formData.append(this.props.name, file, file.name);
          }
        } catch (err) {
          _didIteratorError2 = true;
          _iteratorError2 = err;
        } finally {
          try {
            if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
              _iterator2.return();
            }
          } finally {
            if (_didIteratorError2) {
              throw _iteratorError2;
            }
          }
        }

        xhr.upload.addEventListener('progress', function (event) {
          if (event.lengthComputable) {
            _this3.setState({
              progress: Math.round(event.loaded * 100 / event.total)
            });
          }

          if (_this3.props.onProgress) {
            _this3.props.onProgress({
              originalEvent: event,
              progress: _this3.progress
            });
          }

          ;
        });

        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            _this3.setState({
              progress: 0
            });

            if (xhr.status >= 200 && xhr.status < 300) {
              if (_this3.props.onUpload) {
                _this3.props.onUpload({
                  xhr: xhr,
                  files: _this3.files
                });
              }
            } else {
              if (_this3.props.onError) {
                _this3.props.onError({
                  xhr: xhr,
                  files: _this3.files
                });
              }
            }

            _this3.clear();
          }
        };

        xhr.open('POST', this.props.url, true);

        if (this.props.onBeforeSend) {
          this.props.onBeforeSend({
            'xhr': xhr,
            'formData': formData
          });
        }

        xhr.withCredentials = this.props.withCredentials;
        xhr.send(formData);
      }
    }
  }, {
    key: "clear",
    value: function clear() {
      this.setState({
        files: []
      });

      if (this.props.onClear) {
        this.props.onClear();
      }

      this.clearInputElement();
    }
  }, {
    key: "onFocus",
    value: function onFocus(event) {
      _DomHandler.default.addClass(event.currentTarget.parentElement, 'p-focus');
    }
  }, {
    key: "onBlur",
    value: function onBlur(event) {
      _DomHandler.default.removeClass(event.currentTarget.parentElement, 'p-focus');
    }
  }, {
    key: "onDragEnter",
    value: function onDragEnter(event) {
      if (!this.props.disabled) {
        event.stopPropagation();
        event.preventDefault();
      }
    }
  }, {
    key: "onDragOver",
    value: function onDragOver(event) {
      if (!this.props.disabled) {
        _DomHandler.default.addClass(this.content, 'p-fileupload-highlight');

        event.stopPropagation();
        event.preventDefault();
      }
    }
  }, {
    key: "onDragLeave",
    value: function onDragLeave(event) {
      if (!this.props.disabled) {
        _DomHandler.default.removeClass(this.content, 'p-fileupload-highlight');
      }
    }
  }, {
    key: "onDrop",
    value: function onDrop(event) {
      if (!this.props.disabled) {
        _DomHandler.default.removeClass(this.content, 'p-fileupload-highlight');

        event.stopPropagation();
        event.preventDefault();
        var files = event.dataTransfer ? event.dataTransfer.files : event.target.files;
        var allowDrop = this.props.multiple || files && files.length === 1;

        if (allowDrop) {
          this.onFileSelect(event);
        }
      }
    }
  }, {
    key: "onSimpleUploaderClick",
    value: function onSimpleUploaderClick() {
      if (this.hasFiles()) {
        this.upload();
      }
    }
  }, {
    key: "renderChooseButton",
    value: function renderChooseButton() {
      var _this4 = this;

      var className = (0, _classnames.default)('p-button p-fileupload-choose p-component p-button-text-icon-left');
      return _react.default.createElement("span", {
        icon: "pi pi-plus",
        className: className
      }, _react.default.createElement("input", {
        ref: function ref(el) {
          return _this4.fileInput = el;
        },
        type: "file",
        onChange: this.onFileSelect,
        onFocus: this.onFocus,
        onBlur: this.onBlur,
        multiple: this.props.multiple,
        accept: this.props.accept,
        disabled: this.props.disabled
      }), _react.default.createElement("span", {
        className: "p-button-icon p-button-icon-left p-clickable pi pi-fw pi-plus"
      }), _react.default.createElement("span", {
        className: "p-button-text p-clickable"
      }, this.props.chooseLabel));
    }
  }, {
    key: "renderFiles",
    value: function renderFiles() {
      var _this5 = this;

      return _react.default.createElement("div", {
        className: "p-fileupload-files"
      }, this.state.files.map(function (file, index) {
        var preview = _this5.isImage(file) ? _react.default.createElement("div", null, _react.default.createElement("img", {
          alt: file.name,
          role: "presentation",
          src: file.objectURL,
          width: _this5.props.previewWidth
        })) : null;

        var fileName = _react.default.createElement("div", null, file.name);

        var size = _react.default.createElement("div", null, _this5.formatSize(file.size));

        var removeButton = _react.default.createElement("div", null, _react.default.createElement(_Button.Button, {
          type: "button",
          icon: "pi pi-times",
          onClick: function onClick() {
            return _this5.remove(index);
          }
        }));

        return _react.default.createElement("div", {
          className: "p-fileupload-row",
          key: file.name + file.type + file.size
        }, preview, fileName, size, removeButton);
      }));
    }
  }, {
    key: "renderAdvanced",
    value: function renderAdvanced() {
      var _this6 = this;

      var className = (0, _classnames.default)('p-fileupload p-component', this.props.className);
      var uploadButton, cancelButton, filesList, progressBar;
      var chooseButton = this.renderChooseButton();

      if (!this.props.auto) {
        uploadButton = _react.default.createElement(_Button.Button, {
          label: this.props.uploadLabel,
          icon: "pi pi-upload",
          onClick: this.upload,
          disabled: this.props.disabled || !this.hasFiles()
        });
        cancelButton = _react.default.createElement(_Button.Button, {
          label: this.props.cancelLabel,
          icon: "pi pi-times",
          onClick: this.clear,
          disabled: this.props.disabled || !this.hasFiles()
        });
      }

      if (this.hasFiles()) {
        filesList = this.renderFiles();
        progressBar = _react.default.createElement(_ProgressBar.ProgressBar, {
          value: this.state.progress,
          showValue: false
        });
      }

      return _react.default.createElement("div", {
        id: this.props.id,
        className: className,
        style: this.props.style
      }, _react.default.createElement("div", {
        className: "p-fileupload-buttonbar"
      }, chooseButton, uploadButton, cancelButton), _react.default.createElement("div", {
        ref: function ref(el) {
          _this6.content = el;
        },
        className: "p-fileupload-content",
        onDragEnter: this.onDragEnter,
        onDragOver: this.onDragOver,
        onDragLeave: this.onDragLeave,
        onDrop: this.onDrop
      }, progressBar, _react.default.createElement(_Messages.Messages, {
        ref: function ref(el) {
          return _this6.messagesUI = el;
        }
      }), filesList));
    }
  }, {
    key: "renderBasic",
    value: function renderBasic() {
      var _this7 = this;

      var buttonClassName = (0, _classnames.default)('p-button p-fileupload-choose p-component p-button-text-icon-left', {
        'p-fileupload-choose-selected': this.hasFiles()
      });
      var iconClassName = (0, _classnames.default)('p-button-icon-left pi', {
        'pi-plus': !this.hasFiles() || this.props.auto,
        'pi-upload': this.hasFiles() && !this.props.auto
      });
      return _react.default.createElement("span", {
        className: buttonClassName,
        onMouseUp: this.onSimpleUploaderClick
      }, _react.default.createElement("span", {
        className: iconClassName
      }), _react.default.createElement("span", {
        className: "p-button-text p-clickable"
      }, this.props.auto ? this.props.chooseLabel : this.hasFiles() ? this.state.files[0].name : this.props.chooseLabel), _react.default.createElement("input", {
        ref: function ref(el) {
          return _this7.fileInput = el;
        },
        type: "file",
        multiple: this.props.multiple,
        accept: this.props.accept,
        disabled: this.props.disabled,
        onChange: this.onFileSelect,
        onFocus: this.onFocus,
        onBlur: this.onBlur
      }));
    }
  }, {
    key: "render",
    value: function render() {
      if (this.props.mode === 'advanced') return this.renderAdvanced();else if (this.props.mode === 'basic') return this.renderBasic();
    }
  }]);

  return FileUpload;
}(_react.Component);

exports.FileUpload = FileUpload;

_defineProperty(FileUpload, "defaultProps", {
  id: null,
  name: null,
  url: null,
  mode: 'advanced',
  multiple: false,
  accept: null,
  disabled: false,
  auto: false,
  maxFileSize: null,
  invalidFileSizeMessageSummary: '{0}: Invalid file size, ',
  invalidFileSizeMessageDetail: 'maximum upload size is {0}.',
  style: null,
  className: null,
  widthCredentials: false,
  previewWidth: 50,
  chooseLabel: 'Choose',
  uploadLabel: 'Upload',
  cancelLabel: 'Cancel',
  customUpload: false,
  onBeforeUpload: null,
  onBeforeSend: null,
  onUpload: null,
  onError: null,
  onClear: null,
  onSelect: null,
  onProgress: null,
  onValidationFail: null,
  uploadHandler: null
});

_defineProperty(FileUpload, "propTypes", {
  id: _propTypes.default.string,
  name: _propTypes.default.string,
  url: _propTypes.default.string,
  mode: _propTypes.default.string,
  multiple: _propTypes.default.bool,
  accept: _propTypes.default.string,
  disabled: _propTypes.default.bool,
  auto: _propTypes.default.bool,
  maxFileSize: _propTypes.default.number,
  invalidFileSizeMessageSummary: _propTypes.default.string,
  invalidFileSizeMessageDetail: _propTypes.default.string,
  style: _propTypes.default.object,
  className: _propTypes.default.string,
  widthCredentials: _propTypes.default.bool,
  previewWidth: _propTypes.default.number,
  chooseLabel: _propTypes.default.string,
  uploadLabel: _propTypes.default.string,
  cancelLabel: _propTypes.default.string,
  customUpload: _propTypes.default.bool,
  onBeforeUpload: _propTypes.default.func,
  onBeforeSend: _propTypes.default.func,
  onUpload: _propTypes.default.func,
  onError: _propTypes.default.func,
  onClear: _propTypes.default.func,
  onSelect: _propTypes.default.func,
  onProgress: _propTypes.default.func,
  onValidationFail: _propTypes.default.func,
  uploadHandler: _propTypes.default.func
});


text:
package org.ovirt.engine.ui.webadmin.section.main.view.tab.user;

import javax.inject.Inject;

import org.ovirt.engine.core.common.businessentities.DbUser;
import org.ovirt.engine.core.common.businessentities.Quota;
import org.ovirt.engine.ui.common.uicommon.model.SearchableDetailModelProvider;
import org.ovirt.engine.ui.common.widget.table.column.TextColumnWithTooltip;
import org.ovirt.engine.ui.uicommonweb.models.users.UserListModel;
import org.ovirt.engine.ui.uicommonweb.models.users.UserQuotaListModel;
import org.ovirt.engine.ui.webadmin.section.main.presenter.tab.user.SubTabUserQuotaPresenter;
import org.ovirt.engine.ui.webadmin.section.main.view.AbstractSubTabTableView;
import org.ovirt.engine.ui.webadmin.widget.table.column.QuotaDcStatusColumn;

public class SubTabUserQuotaView extends AbstractSubTabTableView<DbUser, Quota, UserListModel, UserQuotaListModel>
        implements SubTabUserQuotaPresenter.ViewDef {

    @Inject
    public SubTabUserQuotaView(SearchableDetailModelProvider<Quota, UserListModel, UserQuotaListModel> modelProvider) {
        super(modelProvider);
        initTable();
        initWidget(getTable());
    }

    void initTable() {
        getTable().addColumn(new QuotaDcStatusColumn(), "", "30px");

        getTable().addColumn(new TextColumnWithTooltip<Quota>() {
            @Override
            public String getValue(Quota object) {
                return object.getQuotaName() == null ? "" : object.getQuotaName();
            }
        }, "Name");

        getTable().addColumn(new TextColumnWithTooltip<Quota>() {
            @Override
            public String getValue(Quota object) {
                return object.getDescription() == null ? "" : object.getDescription();
            }
        }, "Description");
        getTable().addColumn(new TextColumnWithTooltip<Quota>() {
            @Override
            public String getValue(Quota object) {
                return object.getStoragePoolName() == null ? "" : object.getStoragePoolName();
            }
        }, "Data Center");
        getTable().addColumn(new TextColumnWithTooltip<Quota>() {
            @Override
            public String getValue(Quota object) {
                return (object.getMemSizeMBUsage() == null ? "0" : object.getMemSizeMBUsage().toString()) + "/"
                        + (object.getMemSizeMB() == null ? "*" : object.getMemSizeMB().toString()) + " GB";
            }
        },
                "Used Memory/Total");
        getTable().addColumn(new TextColumnWithTooltip<Quota>() {
            @Override
            public String getValue(Quota object) {
                return (object.getVirtualCpuUsage() == null ? "0" : object.getVirtualCpuUsage().toString()) + "/"
                        + (object.getVirtualCpu() == null ? "*" : object.getVirtualCpu().toString());
            }
        },
                "Running CPU/Total");
        getTable().addColumn(new TextColumnWithTooltip<Quota>() {
            @Override
            public String getValue(Quota object) {
                return (object.getStorageSizeGBUsage() == null ? "0" : object.getStorageSizeGBUsage().toString()) + "/"
                        + (object.getStorageSizeGB() == null ? "*" : object.getStorageSizeGB().toString()) + " GB";
            }
        },
                "Used Storage/Total");
    }

}


text:
<?php

namespace Chipin\AdminBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ChipinAdminBundle extends Bundle
{
}


text:
package com.purejadeite.jadegreen.content;

import com.purejadeite.jadegreen.definition.table.cell.TableCellDefinitionInterface;

/**
 * Tableの構成要素となるCell読み込み定義
 * @author mitsuhiroseino
 */
public class TableCellContent extends AbstractTableCellContent<TableCellDefinitionInterface<?, ?>> {

	private static final long serialVersionUID = -6172471723011313228L;

	/**
	 * コンストラクタ
	 * @param parent 親コンテンツ
	 * @param definition 定義
	 */
	public TableCellContent(TableContentInterface parent, TableCellDefinitionInterface<?, ?> definition) {
		super(parent, definition);
	}

}


text:
package net.sf.fc.gui.m.settings;

import java.io.File;
import java.util.List;

import javax.xml.bind.JAXBException;

import net.sf.fc.gui.c.settings.SettingsProperty;
import net.sf.fc.gui.m.BaseModel;
import net.sf.fc.script.SettingsProxy;
import net.sf.fc.script.gen.settings.LogLevel;
import net.sf.fc.script.gen.settings.LookAndFeel;
import net.sf.fc.script.gen.settings.MostRecentlyUsed;
import net.sf.fc.script.gen.settings.Paths;
import net.sf.fc.script.gen.settings.Settings;

public final class SettingsModel extends BaseModel {

    private final SettingsProxy settingsProxy;
    private Settings snapshotSettings;

    public SettingsModel(SettingsProxy settingsProxy) {
        this.settingsProxy = settingsProxy;
        snapshotSettings = settingsProxy.getSettings();
    }

    public void setLogLevel(LogLevel logLevel) {
        LogLevel oldLogLevel = settingsProxy.getLogLevel();
        settingsProxy.setLogLevel(logLevel);
        firePropertyChange(SettingsProperty.LogLevel.toString(), oldLogLevel, logLevel);
    }

    public void setMostRecentlyUsedLimit(Integer limit) {
        Integer oldLimit = settingsProxy.getMostRecentlyUsedLimit();
        settingsProxy.setMostRecentlyUsedLimit(limit);
        firePropertyChange(SettingsProperty.MostRecentlyUsedLimit.toString(), oldLimit, limit);
    }

    public void setMostRecentlyUsedList(File file) {
        List<File> oldFiles = settingsProxy.getMostRecentlyUsedList().getFiles();
        settingsProxy.addMostRecentlyUsedFile(file);
        firePropertyChange(SettingsProperty.MostRecentlyUsedList.toString(), oldFiles, settingsProxy.getMostRecentlyUsedList().getFiles());
    }

    public void setLookAndFeel(String laf) {
        String oldLaf = settingsProxy.getLookAndFeelName();
        settingsProxy.setLookAndFeelName(laf);
        firePropertyChange(SettingsProperty.LookAndFeel.toString(), oldLaf, laf);
    }

    public void setDrawWindowBorders(Boolean draw) {
        Boolean oldDraw = settingsProxy.isDrawWindowBorders();
        settingsProxy.setDrawWindowBorders(draw);
        firePropertyChange(SettingsProperty.DrawWindowBorders.toString(), oldDraw, draw);
    }

    public void setCopyPath(String copyPath) {
        String oldCopyPath = settingsProxy.getCopyPath();
        settingsProxy.setCopyPath(copyPath);
        firePropertyChange(SettingsProperty.CopyPath.toString(), oldCopyPath, copyPath);
    }

    public void setRestorePath(String restorePath) {
        String oldRestorePath = settingsProxy.getRestorePath();
        settingsProxy.setRestorePath(restorePath);
        firePropertyChange(SettingsProperty.RestorePath.toString(), oldRestorePath, restorePath);
    }

    public void setOptionsPath(String optionsPath) {
        String oldOptionsPath = settingsProxy.getOptionsPath();
        settingsProxy.setOptionsPath(optionsPath);
        firePropertyChange(SettingsProperty.OptionsPath.toString(), oldOptionsPath, optionsPath);
    }

    public void getDefaultSettings() {
        setSettings(settingsProxy.getDefaultSettings());
    }

    public void setSettings(Settings settings) {
        if(!settingsProxy.getSettings().equals(settings)) {
            setLogLevel(settings.getLogLevel());
            LookAndFeel laf = settings.getLookAndFeel();
            if(!laf.equals(settingsProxy.getSettings().getLookAndFeel())) {
                setLookAndFeel(laf.getSelected());
                setDrawWindowBorders(laf.isDrawWindowBorders());
            }
            MostRecentlyUsed mru = settings.getMostRecentlyUsed();
            if(!mru.equals(settingsProxy.getMostRecentlyUsed())) {
                setMostRecentlyUsedLimit(mru.getLimit());
            }
            Paths paths = settings.getPaths();
            if(!paths.equals(settingsProxy.getPaths())) {
                setCopyPath(paths.getCopyPath());
                setRestorePath(paths.getRestorePath());
                setOptionsPath(paths.getOptionsPath());
            }
        }
    }

    public void getSnapshotSettings() {
        snapshotSettings = settingsProxy.getSettings();
    }

    public void getRestoreSnapshotSettings() {
        setSettings(snapshotSettings);
    }

    public void getSaveSettings() {
        try {
            settingsProxy.saveSettingsToDisk();
            snapshotSettings = settingsProxy.getSettings();
            firePropertyChange(SettingsProperty.SaveSettings.toString(), Boolean.FALSE, Boolean.TRUE);
        } catch (JAXBException e) {
            // Send a save settings failure message with the message from the JAXBException as the object.
            firePropertyChange(SettingsProperty.SaveSettingsFailure.toString(), null, e.getMessage());
            // TODO Log the Exception.
            e.printStackTrace();
        }
    }

}


text:
nj=16
cmd="run.pl"
stage=-2
num_gselect=30 # Gaussian-selection using diagonal model: number of Gaussians to select
min_post=0.0001 # Minimum posterior to use (posteriors below this are pruned out)
ivec_dim=400 # Subspace dimensionality
p=100 # Oversampling parameter for randomized SVD
vad_scp=
# End configuration section.

echo "$0 $@"  # Print the command line for logging

if [ -f path.sh ]; then . ./path.sh; fi
. parse_options.sh || exit 1;

if [ $# != 3 ]; then
  echo "Usage: $0 <ubm-mdl> <data-dir> <stats-dir>"
  echo " e.g.: $0 exp/ivec_mdl/ubm/final.ubm data/train exp/fast_ivec_mdl/stats"
  echo "main options (for others, see top of script file)"
  echo "  --config <config-file>                           # config containing options"
  echo "  --cmd (utils/run.pl|utils/queue.pl <queue opts>) # how to run jobs."
  echo "  --nj <n|4>                                      # Number of jobs (also see num-processes and num-threads)"
  echo "  --stage <stage|-2>                               # To control partial reruns"
  echo "  --num-gselect <n|20>                             # Number of Gaussians to select using"
  echo "                                                   # diagonal model."
  exit 1;
fi

ubm_mdl=$1
data=$2
stats_dir=$3

[ ! -f $data/feats.scp ] && echo "No such file $data/feats.scp" && exit 1;

# Split the data dir for parallelization
mkdir -p $stats_dir/log
sdata=$data/split$nj;
utils/split_data.sh $data $nj || exit 1;

# Set up features
ubm_dir=`dirname $ubm_mdl`
delta_opts=`cat $ubm_dir/delta_opts`
if [ -z "$vad_scp" ]; then
  feats="ark,s,cs:add-deltas $delta_opts scp:$sdata/JOB/feats.scp ark:- | apply-cmvn-sliding --norm-vars=false --center=true --cmn-window=300 ark:- ark:- |"
else
  feats="ark,s,cs:add-deltas $delta_opts scp:$sdata/JOB/feats.scp ark:- | apply-cmvn-sliding --norm-vars=false --center=true --cmn-window=300 ark:- ark:- | select-voiced-frames ark:- scp:$vad_scp ark:- |"
fi

ubm_path=`dirname $ubm_mdl`

# Do Gaussian selection and posterior extraction
if [ $stage -le -2 ]; then
  fgmm-global-to-gmm $ubm_mdl $ubm_path/full_to_diag.dubm
fi

if [ $stage -le -1 ]; then
  echo $nj > $stats_dir/num_jobs
  echo "$0: doing Gaussian selection and posterior computation"
  $cmd JOB=1:$nj $stats_dir/log/gselect.JOB.log \
    gmm-gselect --n=$num_gselect $ubm_path/full_to_diag.dubm "$feats" ark:- \| \
    fgmm-global-gselect-to-post --min-post=$min_post $ubm_mdl "$feats" \
       ark,s,cs:- "ark:|gzip -c >$stats_dir/post.JOB.gz" || exit 1;
else
  if ! [ $nj -eq $(cat $stats_dir/num_jobs) ]; then
    echo "Num-jobs mismatch $nj versus $(cat $stats_dir/num_jobs)"
    exit 1
  fi
fi

# Extract the stats
echo "$0: Extracting stats for ivector model estimation"
post_dim=$(fgmm-global-info $ubm_mdl | grep number | cut -f 4 -d " ")
$cmd JOB=1:$nj $stats_dir/log/acc_stats.JOB.log \
  fast-ivector-full-acc-stats \
    --p=$p \
    --ivec-dim=$ivec_dim \
    "$feats" "ark,o:gunzip -c $stats_dir/post.JOB.gz|" $post_dim \
    ark:$stats_dir/stats_N.JOB ark:$stats_dir/stats_F.JOB \
    $stats_dir/stats_NFS.JOB || touch $stats_dir/.error &
wait
[ -f $stats_dir/.error ] && echo "Error accumulating stats" && rm $stats_dir/.error && exit 1;
echo "Succeeded in obtaining stats"


text:
import unittest
import numpy as np
from astropy import units as u
import scipy.integrate as integrate
from .context import superbol
from superbol.mag2flux import *
from superbol.fbol import *
from superbol.fit_blackbody import *

class TestFbol(unittest.TestCase):

    def setUp(self):
        self.key = np.array(['U', 'B', 'V', 'R', 'I'])
        self.magnitudes = np.array([7.129, 5.554, 4.383, 3.917, 3.794])
        self.uncertainties = np.array([0.02, 0.02, 0.02, 0.02, 0.02])
        self.av = 0.435
        self.flux_array = u.Quantity([5.87565760e-12, 3.79417256e-11,
                                      6.40953095e-11, 5.90280490e-11,
                                      3.41930932e-11],
                                      u.erg / (u.Angstrom * u.cm**2 * u.s))
        self.flux_uncertainties = u.Quantity([1.0e-12, 1.0e-12,
                                      1.0e-12, 1.0e-12,
                                      1.0e-12],
                                      u.erg / (u.Angstrom * u.cm**2 * u.s))

        self.eff_wl_array = u.Quantity([3660., 4380., 5450., 6410., 7980.],
                                        u.Angstrom)

    def test_integrate_fqbol_returns_correct_flux_value(self):
        expected = np.trapz(self.flux_array, self.eff_wl_array)
        result, uncertainty = integrate_fqbol(self.eff_wl_array, self.flux_array, self.flux_uncertainties)

        self.assertEqual(expected, result)

    def test_integrate_fqbol_returns_correct_flux_uncertainty(self):
        quad_terms = np.array([])

        for i, uncertainty in enumerate(self.flux_uncertainties):
            if i == 0:
                term = 0.5 * (self.eff_wl_array[i+1] - self.eff_wl_array[i]) * uncertainty
                quad_terms = np.append(quad_terms, term)
            elif i == len(self.flux_uncertainties) - 1:
                term = 0.5 * (self.eff_wl_array[i] - self.eff_wl_array[i-1]) * uncertainty
                quad_terms = np.append(quad_terms, term)
            else:
                term = 0.5 * (self.eff_wl_array[i+1] - self.eff_wl_array[i-1]) * uncertainty
                quad_terms = np.append(quad_terms, term)

        expected = np.sqrt(np.sum(x*x for x in quad_terms))
        result, uncertainty = integrate_fqbol(self.eff_wl_array, self.flux_array, self.flux_uncertainties)

        self.assertEqual(expected, uncertainty)

    def test_uv_correction_linear(self):
        wavelengths = [2000., 3660.]
        fluxes = [0.0, 5.87565760e-12]
        expected = np.trapz(fluxes,wavelengths)
        result, uncertainty = uv_correction_linear(3660.,
                                                   5.87565760e-12,
                                                   6.0e-13)
        self.assertEqual(expected, result)

class TestBlackbodyIntegration(unittest.TestCase):

    def setUp(self):
        self.best_fit_temperature = 4565.75044459
        self.best_fit_temperature_err = 10.0
        self.best_fit_angular_radius = 4.59019554625e-09
        self.best_fit_angular_radius_err = 5.e-10
        self.longest_wavelength = 7980.
        self.shortest_wavelength = 3660.

    def test_ir_correction(self):
        expected = integrate.quad(bb_flux_nounits, self.longest_wavelength,
                                  np.inf,
                                  args=(self.best_fit_temperature,
                                  self.best_fit_angular_radius))
        result = ir_correction(self.best_fit_temperature,
                               self.best_fit_temperature_err,
                               self.best_fit_angular_radius,
                               self.best_fit_angular_radius_err,
                               self.longest_wavelength)
        self.assertAlmostEqual(expected[0], result[0])

    def test_uv_correction_blackbody(self):
        expected = integrate.quad(bb_flux_nounits, 0, self.shortest_wavelength,
                                  args=(self.best_fit_temperature,
                                        self.best_fit_angular_radius))
        result = uv_correction_blackbody(self.best_fit_temperature,
                                         self.best_fit_temperature_err,
                                         self.best_fit_angular_radius,
                                         self.best_fit_angular_radius_err,
                                         self.shortest_wavelength)
        self.assertAlmostEqual(expected[0], result[0])


text:
// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:

#ifndef FLUSSPFERD_XML_NODE_LIST_HPP
#define FLUSSPFERD_XML_NODE_LIST_HPP

#include "node_map.hpp"

#include <DOM/NodeList.hpp>

namespace xml_plugin {

FLUSSPFERD_CLASS_DESCRIPTION(
    node_list,
    (constructible, false)
    (full_name, "xml.NodeList")
    (constructor_name, "NodeList")
    (properties,
      ("length", getter, get_length)
    )
    (methods,
      ("item", bind, item)
    )
)
{

public:
  typedef Arabica::DOM::NodeList<std::string> wrapped_type;

  node_list(flusspferd::object const &proto, wrapped_type const &node, weak_node_map map);
  virtual ~node_list();

  int get_length();

  flusspferd::object item(int idx);

protected:

  void property_op(property_mode mode, flusspferd::value const &id, flusspferd::value &x);
  bool property_resolve(flusspferd::value const &id, unsigned);

  wrapped_type list_;
  weak_node_map node_map_;
};

}

#endif


text:
<SIF_ObjectData>
<ActivityProvider RefId="EE2D941017DC11DBAC45E8B6A9745757">
  <LocalId>EE2D941017DC11DBAC45E8B6A9745757</LocalId>
  <ProviderName>School of Rock</ProviderName>
  <Address Type="01">
    <Street>
      <Line1>13917 4th St.</Line1>
      <StreetNumber>13917</StreetNumber>
      <StreetName>4th</StreetName>
      <StreetType>St.</StreetType>
    </Street>
    <City>Boca Raton</City>
    <County>Palm Beach</County>
    <StatePr Code="FL" />
    <Country Code="US" />
    <PostalCode>33487</PostalCode>
  </Address>
</ActivityProvider></SIF_ObjectData>


text:
using UnityEngine;
using System.Collections;

namespace BehaviorDesigner.Runtime
{
    [System.Serializable]
    public class SharedVector2 : SharedVariable<Vector2>
    {
        public override string ToString() { return mValue.ToString(); }
        public static implicit operator SharedVector2(Vector2 value) { return new SharedVector2 { mValue = value }; }
    }
}


text:
---
yuiCompress: !!bool true
---
(function($, window, document) {

    var $head = $('head'),
        curTheme = null,
        curThemeIsInverse = false,
        haveLocalStorage = null,

    /**
     * \url https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
     */
    storageAvailable = function(type) {
        try {
            var storage = window[type],
                x = '__storage_test__';
            storage.setItem(x, x);
            storage.removeItem(x);
            return true;
        } catch(e) {
            return false;
        }
    },

    switchTo = function(theme, isInverse) {
        // save theme name globally
        curTheme = theme;
        curThemeIsInverse = isInverse;
        themeStorage('save');
        // do actual switch
        updateStylesheets();
        updateImages();
        // notify page of theme change
        window.setTimeout(function() {
            $(window).trigger('denvelop-theme-switched', [true, curTheme]);
        }, 400); // at this point, theme switching more or less completed
    },

    /**
     * Function that can be used to access the local storage for loading/saving
     * the theme and if it is an inverted theme.
     *
     * \param action String indicating what to do. Can be 'load' or 'save'.
     * \return A boolean indicating if the action was successful.
     */
    themeStorage = function(action) {
        // check support if not done yet
        if (haveLocalStorage === null) {
            haveLocalStorage = storageAvailable('localStorage');
        }
        // if no support, do nothing
        if (!haveLocalStorage) {
            return false;
        }
        // either load or save the theme from/to storage
        if (action === 'load') {
            var storage = window.localStorage,
                theme = storage.getItem('themeName'),
                themeInverted = storage.getItem('themeInverted');
            if (theme !== null && themeInverted !== null) {
                curTheme = theme;
                curThemeIsInverse = (themeInverted === '1');
                return true;
            }
            return false;
        } else if (action === 'save') {
            var storage = window.localStorage;
            storage.setItem('themeName', curTheme);
            storage.setItem('themeInverted', (curThemeIsInverse ? '1' : '0'));
            return true;
        }
        // unknown action
        return false;
    },

    /**
     * Update the classes of the theme swatches on the page, if any.
     */
    updateActiveTheme = function() {
        $('#themes .theme[data-theme-name="' + curTheme + '"]').
            addClass('active').
            siblings().
            removeClass('active');
    },

    updateImages = function() {
        $('img.logo.invertible').each(function() {
            var $img = $(this);
            if (curThemeIsInverse) {
                $img.attr('src', $img.attr('src').replace(/\.svg$/, '-i.svg'));
            } else {
                $img.attr('src', $img.attr('src').replace(/-i\.svg$/, '.svg'));
            }
        });
    },

    /**
     * Update disabled stylesheets.
     */
    updateStylesheets = function() {
        var links = $('link[rel$=stylesheet][title^=theme-]');
        links.each(function() {
            this.disabled = true;
        });
        $('link[rel$=stylesheet][title=theme-' + curTheme + ']').get(0).disabled = false;
    };

    /**
     * Initialize handlers on page load.
     */
    $(function() {
        // set current theme, possibly use localStorage
        if (!themeStorage('load')) {
            curTheme = 'default';
            curThemeIsInverse = false;
        }
        updateStylesheets();
        updateImages();
        updateActiveTheme();
        // enable switching
        var $body = $('body'),
            $window = $(window);
        $body.on('click', '.theme', function() {
            var $link = $(this);
            if (!$link.hasClass('active')) {
                switchTo($link.data('theme-name'), $link.hasClass('theme-inverse'));
                updateActiveTheme();
            }
        });
        // update pages when they are loaded
        $window.on('denvelop-navigated', function(e, prevPage, curPage) {
            // set active theme on home page
            if (curPage.id === 'home') {
                updateActiveTheme();
            }
            // possibly update images that need inversion
            updateImages();
        });
        // after having set the theme and now that everything has settled,
        // enable transitions when changing the theme from now on
        setTimeout(function() {
            $body.addClass('loaded');
            $window.on('denvelop-theme-switch', function(e, themeName) {
                var $link = $('link[rel$=stylesheet][title="theme-' + themeName + '"]');
                if ($link.size() > 0) {
                    switchTo($link.attr('title').match(/-(\w+)$/)[1], ($link.data('inverse') === 1));
                    updateActiveTheme();
                } else {
                    // we did not switch
                    setTimeout(function() {
                        $window.trigger('denvelop-theme-switched', [false, curTheme]);
                    });
                }
            });
        }, 1000);
    });

}(jQuery, window, document));


text:
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Pregunta.Me.Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Aon")]
[assembly: AssemblyProduct("Pregunta.Me.Services")]
[assembly: AssemblyCopyright("Copyright © Aon 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("Pregunta.Me.UnitTests")]
[assembly: InternalsVisibleTo("Pregunta.Me.Specs")]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ea86aa9b-ab2c-4ec1-b380-cf1ee39f14e4")]

// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
package com.navigation.reactnative;

import android.content.res.ColorStateList;
import android.view.Gravity;
import android.view.View;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.modules.i18nmanager.I18nUtil;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.ViewManagerDelegate;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.viewmanagers.NVFloatingActionButtonManagerDelegate;
import com.facebook.react.viewmanagers.NVFloatingActionButtonManagerInterface;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.Map;

public class FloatingActionButtonViewManager extends SimpleViewManager<FloatingActionButtonView> implements NVFloatingActionButtonManagerInterface<FloatingActionButtonView> {
    private final ViewManagerDelegate<FloatingActionButtonView> delegate;

    public FloatingActionButtonViewManager() {
        delegate = new NVFloatingActionButtonManagerDelegate<>(this);
    }

    @Nullable
    @Override
    protected ViewManagerDelegate<FloatingActionButtonView> getDelegate() {
        return delegate;
    }

    @NonNull
    @Override
    public String getName() {
        return "NVFloatingActionButton";
    }

    @NonNull
    @Override
    protected FloatingActionButtonView createViewInstance(@NonNull ThemedReactContext reactContext) {
        return new FloatingActionButtonView(reactContext);
    }

    @ReactProp(name = "image")
    public void setImage(FloatingActionButtonView view, ReadableMap icon) {
        view.setIconSource(icon);
    }

    @ReactProp(name = "fabBackgroundColor", customType = "Color")
    public void setFabBackgroundColor(FloatingActionButtonView view, @Nullable Integer backgroundColor) {
        view.setBackgroundTintList(ColorStateList.valueOf(backgroundColor != null ? backgroundColor : view.defaultBackgroundColor));
    }

    @ReactProp(name = "rippleColor", customType = "Color")
    public void setRippleColor(FloatingActionButtonView view, @Nullable Integer rippleColor) {
        view.setRippleColor(ColorStateList.valueOf(rippleColor != null ? rippleColor : view.defaultRippleColor));
    }

    @ReactProp(name = "fabColor", customType = "Color")
    public void setFabColor(FloatingActionButtonView view, @Nullable Integer color) {
        view.setImageTintList(color != null ? ColorStateList.valueOf(color) : null);
    }

    @ReactProp(name = "anchor")
    public void setAnchor(FloatingActionButtonView view, @Nullable String anchor) {
        if ("navigationBar".equals(anchor) || "bottomNavigationBar".equals(anchor) || "bottomSheet".equals(anchor)) {
            view.setAnchor(anchor);
        } else {
            view.params.setAnchorId(View.NO_ID);
            view.setAnchor(null);
        }
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "gravity")
    public void setGravity(FloatingActionButtonView view, String gravity) {
        view.params.gravity = convertGravity(gravity);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "anchorGravity")
    public void setAnchorGravity(FloatingActionButtonView view, String anchorGravity) {
        view.params.anchorGravity = convertGravity(anchorGravity);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    private int convertGravity(String gravity) {
        if ("topLeft".equals(gravity)) return Gravity.TOP | Gravity.LEFT;
        if ("topStart".equals(gravity)) return Gravity.TOP | Gravity.START;
        if ("top".equals(gravity)) return Gravity.TOP | Gravity.CENTER;
        if ("topRight".equals(gravity)) return Gravity.TOP | Gravity.RIGHT;
        if ("topEnd".equals(gravity)) return Gravity.TOP | Gravity.END;
        if ("left".equals(gravity)) return Gravity.CENTER | Gravity.LEFT;
        if ("start".equals(gravity)) return Gravity.CENTER | Gravity.START;
        if ("center".equals(gravity)) return Gravity.CENTER;
        if ("right".equals(gravity)) return Gravity.CENTER | Gravity.RIGHT;
        if ("end".equals(gravity)) return Gravity.CENTER | Gravity.END;
        if ("bottomLeft".equals(gravity)) return Gravity.BOTTOM | Gravity.LEFT;
        if ("bottomStart".equals(gravity)) return Gravity.BOTTOM | Gravity.START;
        if ("bottom".equals(gravity)) return Gravity.BOTTOM | Gravity.CENTER;
        if ("bottomRight".equals(gravity)) return Gravity.BOTTOM | Gravity.RIGHT;
        if ("bottomEnd".equals(gravity)) return Gravity.BOTTOM | Gravity.END;
        return Gravity.NO_GRAVITY;
    }

    @ReactProp(name = "fabMarginTop")
    public void setFabMarginTop(FloatingActionButtonView view, int marginTop) {
        view.marginTop = (int) PixelUtil.toPixelFromDIP(marginTop);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "fabMarginRight")
    public void setFabMarginRight(FloatingActionButtonView view, int marginRight) {
        view.marginRight = (int) PixelUtil.toPixelFromDIP(marginRight);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "fabMarginBottom")
    public void setFabMarginBottom(FloatingActionButtonView view, int marginBottom) {
        view.marginBottom = (int) PixelUtil.toPixelFromDIP(marginBottom);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "fabMarginStart")
    public void setFabMarginStart(FloatingActionButtonView view, int marginStart) {
        view.marginStart = (int) PixelUtil.toPixelFromDIP(marginStart);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "fabMarginEnd")
    public void setFabMarginEnd(FloatingActionButtonView view, int marginEnd) {
        view.marginEnd = (int) PixelUtil.toPixelFromDIP(marginEnd);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "fabMarginLeft")
    public void setFabMarginLeft(FloatingActionButtonView view, int marginLeft) {
        view.marginLeft = (int) PixelUtil.toPixelFromDIP(marginLeft);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "fabMargin")
    public void setFabMargin(FloatingActionButtonView view, int margin) {
        view.margin = (int) PixelUtil.toPixelFromDIP(margin);
        if (view.getParent() != null) view.getParent().requestLayout();
    }

    @ReactProp(name = "fabElevation")
    public void setFabElevation(FloatingActionButtonView view, int elevation) {
        view.setCompatElevation(PixelUtil.toPixelFromDIP(elevation));
    }

    @ReactProp(name = "contentDescription")
    public void setContentDescription(FloatingActionButtonView view, String contentDescription) {
        view.setContentDescription(contentDescription);
    }

    @ReactProp(name = "size")
    public void setSize(FloatingActionButtonView view, int size) {
        view.clearCustomSize();
        if (size > 0) view.setCustomSize((int) PixelUtil.toPixelFromDIP(size));
        else view.setSize(FloatingActionButton.SIZE_NORMAL);
    }

    @ReactProp(name = "testID")
    public void setTestID(FloatingActionButtonView view, String testID) {
        view.setTag(testID);
    }

    @Override
    protected void onAfterUpdateTransaction(@NonNull FloatingActionButtonView view) {
        super.onAfterUpdateTransaction(view);
        boolean rtl = I18nUtil.getInstance().isRTL(view.getContext());
        int marginLeft = Math.max(view.marginLeft, !rtl ? view.marginStart : view.marginEnd);
        int marginRight = Math.max(view.marginRight, !rtl ? view.marginEnd : view.marginStart);
        view.params.setMargins(
            Math.max(marginLeft, view.margin), Math.max(view.marginTop, view.margin),
            Math.max(marginRight, view.margin), Math.max(view.marginBottom, view.margin
        ));
    }

    @Override
    public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
        return MapBuilder.<String, Object>builder()
            .put("topOnPress", MapBuilder.of("registrationName", "onPress"))
            .build();
    }
}


text:
/**
 * External dependencies.
 */

var request = require('request');

/**
 * Internal dependencies.
 */

var Response = require('./response');

/**
 * Small request wrapper. Nothing fancy.
 *
 * @param {Object} options
 * @param {Function} callback
 * @api public
 */

module.exports = function(options, fn) {
  request(options, function(err, res, body) {
    fn(new Response(err, res));
  });
};


text:
import copy

from oslo_serialization import jsonutils
from senlin.objects.requests import policies
from senlin.tests.unit.common import base as test_base

class TestPolicyList(test_base.SenlinTestCase):

    def test_policy_list_request_body_full(self):
        params = {
            'name': ['policy1'],
            'type': ['senlin.policy.scaling-1.0'],
            'limit': 2,
            'marker': 'd6901ce0-1403-4b9c-abf5-25c59cf79823',
            'sort': 'name:asc',
            'project_safe': False
        }
        sot = policies.PolicyListRequest(**params)
        self.assertEqual(['policy1'], sot.name)
        self.assertEqual(['senlin.policy.scaling-1.0'], sot.type)
        self.assertEqual(2, sot.limit)
        self.assertEqual('d6901ce0-1403-4b9c-abf5-25c59cf79823', sot.marker)
        self.assertEqual('name:asc', sot.sort)
        self.assertFalse(sot.project_safe)

class TestPolicyCreate(test_base.SenlinTestCase):

    spec = {
        "properties": {
            "adjustment": {
                "min_step": 1,
                "number": 1,
                "type": "CHANGE_IN_CAPACITY"
            },
            "event": "CLUSTER_SCALE_IN"
        },
        "type": "senlin.policy.scaling",
        "version": "1.0"
    }

    def test_policy_create_body(self):
        spec = copy.deepcopy(self.spec)
        sot = policies.PolicyCreateRequestBody(name='foo', spec=spec)
        self.assertEqual('foo', sot.name)
        self.assertEqual('senlin.policy.scaling', sot.spec['type'])
        self.assertEqual('1.0', sot.spec['version'])

    def test_policy_create_request(self):
        spec = copy.deepcopy(self.spec)
        policy = policies.PolicyCreateRequestBody(name='foo', spec=spec)
        sot = policies.PolicyCreateRequest(policy=policy)

        self.assertIsInstance(sot.policy, policies.PolicyCreateRequestBody)

    def test_request_body_to_primitive(self):
        spec = copy.deepcopy(self.spec)
        sot = policies.PolicyCreateRequestBody(name='foo', spec=spec)
        self.assertEqual('foo', sot.name)

        res = sot.obj_to_primitive()
        # request body
        self.assertEqual('PolicyCreateRequestBody', res['senlin_object.name'])
        self.assertEqual('1.0', res['senlin_object.version'])
        self.assertEqual('senlin', res['senlin_object.namespace'])
        self.assertIn('name', res['senlin_object.changes'])
        self.assertIn('spec', res['senlin_object.changes'])
        # spec
        data = res['senlin_object.data']
        self.assertEqual(u'foo', data['name'])
        spec_data = jsonutils.loads(data['spec'])
        self.assertEqual('senlin.policy.scaling', spec_data['type'])
        self.assertEqual('1.0', spec_data['version'])

    def test_request_to_primitive(self):
        spec = copy.deepcopy(self.spec)
        body = policies.PolicyCreateRequestBody(name='foo', spec=spec)
        sot = policies.PolicyCreateRequest(policy=body)

        self.assertIsInstance(sot.policy, policies.PolicyCreateRequestBody)
        self.assertEqual('foo', sot.policy.name)

        res = sot.obj_to_primitive()
        self.assertIn('policy', res['senlin_object.changes'])
        self.assertEqual('PolicyCreateRequest', res['senlin_object.name'])
        self.assertEqual('senlin', res['senlin_object.namespace'])
        self.assertEqual('1.0', res['senlin_object.version'])

        data = res['senlin_object.data']['policy']
        self.assertEqual('PolicyCreateRequestBody', data['senlin_object.name'])
        self.assertEqual('senlin', data['senlin_object.namespace'])
        self.assertEqual('1.0', data['senlin_object.version'])
        self.assertIn('name', data['senlin_object.changes'])
        self.assertIn('spec', data['senlin_object.changes'])

        pd = data['senlin_object.data']
        self.assertEqual(u'foo', pd['name'])

        spec_data = jsonutils.loads(pd['spec'])
        self.assertEqual('senlin.policy.scaling', spec_data['type'])
        self.assertEqual('1.0', spec_data['version'])

class TestPolicyGet(test_base.SenlinTestCase):

    def test_policy_get(self):
        sot = policies.PolicyGetRequest(identity='foo')

        self.assertEqual('foo', sot.identity)

class TestPolicyUpdate(test_base.SenlinTestCase):

    def test_policy_update_body(self):
        data = {'name': 'foo'}
        sot = policies.PolicyUpdateRequestBody(**data)
        self.assertEqual('foo', sot.name)

    def test_policy_update(self):
        data = {'name': 'foo'}
        body = policies.PolicyUpdateRequestBody(**data)

        request = {
            'identity': 'pid',
            'policy': body
        }
        sot = policies.PolicyUpdateRequest(**request)
        self.assertEqual('pid', sot.identity)
        self.assertIsInstance(sot.policy, policies.PolicyUpdateRequestBody)

    def test_policy_data_to_primitive(self):
        data = {'name': 'foo'}
        sot = policies.PolicyUpdateRequestBody(**data)
        res = sot.obj_to_primitive()

        self.assertIn('name', res['senlin_object.changes'])
        self.assertEqual(u'foo', res['senlin_object.data']['name'])
        self.assertEqual('PolicyUpdateRequestBody', res['senlin_object.name'])
        self.assertEqual('senlin', res['senlin_object.namespace'])
        self.assertEqual('1.0', res['senlin_object.version'])

    def test_request_to_primitive(self):
        data = {'name': 'foo'}
        name = policies.PolicyUpdateRequestBody(**data)

        request = {
            'identity': 'pid',
            'name': name
        }
        sot = policies.PolicyUpdateRequest(**request)
        res = sot.obj_to_primitive()

        self.assertIn('identity', res['senlin_object.changes'])
        self.assertEqual(u'pid', res['senlin_object.data']['identity'])
        self.assertEqual('PolicyUpdateRequest', res['senlin_object.name'])
        self.assertEqual('senlin', res['senlin_object.namespace'])
        self.assertEqual('1.0', res['senlin_object.version'])

class TestPolicyValidate(test_base.SenlinTestCase):
    spec = {
        "properties": {
            "adjustment": {
                "min_step": 1,
                "number": 1,
                "type": "CHANGE_IN_CAPACITY"
            },
            "event": "CLUSTER_SCALE_IN"
        },
        "type": "senlin.policy.scaling",
        "version": "1.0"
    }

    def test_validate_request_body(self):
        spec = copy.deepcopy(self.spec)
        body = policies.PolicyValidateRequestBody(spec=spec)

        self.assertEqual(spec['type'], body.spec['type'])
        self.assertEqual(spec['version'], body.spec['version'])

    def test_validate_request(self):
        spec = copy.deepcopy(self.spec)
        body = policies.PolicyValidateRequestBody(spec=spec)
        policy = policies.PolicyValidateRequest(policy=body)

        self.assertIsInstance(
            policy.policy, policies.PolicyValidateRequestBody)

    def test_request_body_to_primitive(self):
        spec = copy.deepcopy(self.spec)

        sot = policies.PolicyValidateRequestBody(spec=spec)
        res = sot.obj_to_primitive()

        self.assertIn('spec', res['senlin_object.changes'])
        self.assertEqual(
            'PolicyValidateRequestBody', res['senlin_object.name'])
        self.assertEqual('senlin', res['senlin_object.namespace'])
        self.assertEqual('1.0', res['senlin_object.version'])

        pd = res['senlin_object.data']['spec']
        data = jsonutils.loads(pd)
        self.assertEqual('senlin.policy.scaling', data['type'])
        self.assertEqual('1.0', data['version'])

    def test_request_to_primitive(self):
        spec = copy.deepcopy(self.spec)
        body = policies.PolicyValidateRequestBody(spec=spec)
        policy = policies.PolicyValidateRequest(policy=body)

        res = policy.obj_to_primitive()

        self.assertIn('policy', res['senlin_object.changes'])
        self.assertEqual('PolicyValidateRequest', res['senlin_object.name'])
        self.assertEqual('senlin', res['senlin_object.namespace'])
        self.assertEqual('1.0', res['senlin_object.version'])

        body = res['senlin_object.data']['policy']

        self.assertIn('spec', body['senlin_object.changes'])
        self.assertEqual(
            'PolicyValidateRequestBody', body['senlin_object.name'])
        self.assertEqual('senlin', body['senlin_object.namespace'])
        self.assertEqual('1.0', body['senlin_object.version'])

        pd = body['senlin_object.data']['spec']
        data = jsonutils.loads(pd)
        self.assertEqual('senlin.policy.scaling', data['type'])
        self.assertEqual('1.0', data['version'])

class TestPolicyDelete(test_base.SenlinTestCase):

    def test_policy_delete(self):
        sot = policies.PolicyDeleteRequest(identity='foo')

        self.assertEqual('foo', sot.identity)


text:
const Bank = require('./bank');

class BankProxy {
  constructor(aBank) {
    this.bank = aBank;
  }

  deposit(amount) {
    this.bank.deposit(amount);
    console.log(`deposit ${amount}... total cash: ${this.bank.total()}`);
  }

  withdraw(amount) {
    if (this.bank.withdraw(amount)) {
      console.log(`withdraw ${amount}... total cash: ${this.bank.total()}`);
    } else {
      console.log(`failed to withdraw!`);
    }
  }

  total() {
    return console.log(`total cash: ${this.bank.total()}`);
  }
}

module.exports = BankProxy;


text:
import {setDefinition} from './';
import {inflateEvents} from './utils/trace';

setDefinition('meteor-method-trace', async function(dl, args) {
  const _id = String(args.traceId);
  const shard = await dl.findShard(args.appId);
  const result = await dl.findOne(shard, 'methodTraces', {_id});

  if (!result) {
    return null;
  }

  return inflateEvents(result);
});


text:
ExampleClass::ExampleClass() {
	m_iValue = 0;
}

int ExampleClass::GetValue() {
	return m_iValue;
}

void ExampleClass::DoSomething() {
	m_iValue = 3;
}


text:
/**
 * \file mac_api.h
 * \brief A API class to support different MACs from multiple vendors.
 * Vendor must implement a function which fills supported callback functions which Upper layer will use.
 */

#ifndef MAC_API_H
#define MAC_API_H

#include <inttypes.h>
#include "mlme.h"
#include "mac_mcps.h"

#ifdef __cplusplus
extern "C" {
#endif

struct channel_list_s;

typedef struct mac_api_s mac_api_t;

/**
 * Every MAC adapting to Upper layer must implement a function which creates mac_api_t pointer, e.g 'mac_api_t* create_mac_api();'
 * In the function external Mac needs to fill necessary function pointers so that Upper layer can use it.
 * For Nanostack to work, following (mlme/mcps) request functions are mandatory:
 *   - mcps-data
 *   - scan
 *   - start
 *   - poll
 *   - get
 *   - set
 *   - reset
 *   - (purge)
 * Also indication and confirm callbacks for above are needed plus
 *   - beacon notify
 *   - comm status
 *
 * \return mac_api_t Ownership of newly created object
 */

/*!
 * \enum mlme_primitive
 * \brief Enum for MLME primitive types.
 */
typedef enum {
    MLME_ASSOCIATE,
    MLME_DISASSOCIATE,
    MLME_BEACON_NOTIFY,
    MLME_GET,
    MLME_GTS,
    MLME_ORPHAN,
    MLME_RESET,
    MLME_RX_ENABLE,
    MLME_SCAN,
    MLME_COMM_STATUS,
    MLME_SET,
    MLME_START,
    MLME_SYNC,
    MLME_SYNC_LOSS,
    MLME_POLL
} mlme_primitive;

/**
 * \struct mac_description_storage_size_s
 * \brief Container for MAC storage sizes.
 */
typedef struct mac_description_storage_size_s {
    uint8_t device_decription_table_size;   /**< MAC Device description list size */
    uint8_t key_description_table_size;     /**< MAC Key description list size */
    uint8_t key_lookup_size;                /**< Key description key lookup list size */
    uint8_t key_usage_size;                 /**< Key description key usage list size */
} mac_description_storage_size_t;

/*!
 * \enum mac_extended_address_type
 * \brief Enum for MAC extended address types.
 */
typedef enum mac_extended_address_type {
    MAC_EXTENDED_READ_ONLY, /** EUID64 which is unique */
    MAC_EXTENDED_DYNAMIC /** Configured MAC 64-bit address to RAM and Radio */
} mac_extended_address_type;
//External MAC functions

/**
 * @brief mlme_associate_response
 * @param api API to handle the request
 * @param data MLME-ASSOCIATE.response specific values
 */
//typedef void mlme_associate_response(const mac_api_t* api, mlme_associate_resp_t *data);

//typedef void mlme_orphan_response(const mac_api_t* api, mlme_orphan_resp_t *data);

/**
 * @brief mlme_request
 * @param api API to handle the request
 * @param id The identifier of the MLME primitive
 * @param data Primitive specific data (\see mlme.h)
 */
typedef void mlme_request(const mac_api_t *api, mlme_primitive id, const void *data);

/**
 * @brief mcps_request MCPS_DATA request call
 * @param api API to handle the request
 * @param data MCPS-DATA.request specific values
 */
typedef void mcps_data_request(const mac_api_t *api, const mcps_data_req_t *data);

/**
 * @brief mcps_request MCPS_DATA with IE extions request call
 * @param api API to handle the request
 * @param data MCPS-DATA.request specific values
 * @param ie_ext Information element list to MCPS-DATA.request
 * @param asynch_channel_list Optional channel list to asynch data request. Give NULL when normal data request.
 * @param priority Data request priority level
 * @param phy_mode_id Use mode switch if given phy_mode_id > 0
 *
 * Asynch data request is mac standard extension. asynch_channel_list include channel mask which channel message is requested to send.
 */
typedef void mcps_data_request_ext(const mac_api_t *api, const mcps_data_req_t *data, const mcps_data_req_ie_list_t *ie_ext, const struct channel_list_s *asynch_channel_list, mac_data_priority_t priority, uint8_t phy_mode_id);

/**
 * @brief mcps_purge_request MCPS_PURGE request call
 * @param api API to handle the request
 * @param data MCPS-PURGE.request specific values
 * @return 0 in case of success, non-zero otherwise
 */
typedef uint8_t mcps_purge_request(const mac_api_t *api, const mcps_purge_t *data);

//Upper layer specific callback functions (will also be set by Upper layer after mac_api_t has been created and given to it)

/**
 * @brief mcps_data_confirm MCPS-DATA confirm is called as a response to MCPS-DATA request
 * @param api The API which handled the response
 * @param data MCPS-DATA.confirm specific values
 */
typedef void mcps_data_confirm(const mac_api_t *api, const mcps_data_conf_t *data);

/**
 * @brief mcps_data_confirm_ext MCPS-DATA confirm with Enhanced ACK payload is called as a response to MCPS-DATA request
 * @param api The API which handled the response
 * @param data MCPS-DATA.confirm specific values
 * @param conf_data Possible Confirmation Data
 */
typedef void mcps_data_confirm_ext(const mac_api_t *api, const mcps_data_conf_t *data, const mcps_data_conf_payload_t *conf_data);

/**
 * @brief mcps_data_indication MCPS-DATA indication is called when MAC layer has received data
 * @param api The API which handled the response
 * @param data MCPS-DATA.indication specific values
 */
typedef void mcps_data_indication(const mac_api_t *api, const mcps_data_ind_t *data);

/**
 * @brief mcps_data_indication MCPS-DATA indication is called when MAC layer has received data
 * @param api The API which handled the response
 * @param data MCPS-DATA.indication specific values
 * @param ie_ext Information element list
 */
typedef void mcps_data_indication_ext(const mac_api_t *api, const mcps_data_ind_t *data, const mcps_data_ie_list_t *ie_ext);

/**
 * @brief mcps_ack_data_req_ext Callback for request IE elements and payload to enhanced ACK
 * @param api The API which handled the response
 * @param data Pointer where MAC user set Payload and IE element pointers and length
 * @param rssi Signal strength for received packet
 * @param lqi Link quality to neighbor
 */
typedef void mcps_ack_data_req_ext(const mac_api_t *api, mcps_ack_data_payload_t *data, int8_t rssi, uint8_t lqi);

/**
 * @brief mcps_edfe_handler Callback for handle and detect edfe frame
 * @param api The API which handled the response
 * @param response_message Enhanced message response data and status
 */
typedef void mcps_edfe_handler(const mac_api_t *api, mcps_edfe_response_t *response_message);

/**
 * @brief mode_switch_resolver Callback to resolve configuration behind received PHY mode ID
 * @param api The API which handled the response
 * @param phy_mode_id PHY mode ID to be resolved
 * @param rf_config Resolved configuration
 * @return 0 in case of success, negative otherwise
 */
typedef int8_t mode_switch_resolver(const mac_api_t *api, uint8_t phy_mode_id, phy_rf_channel_configuration_s *rf_config);

/**
 * @brief mcps_purge_confirm MCPS-PURGE confirm is called as a response to MCPS-PURGE request
 * @param api The API which handled the request
 * @param data MCPS-PURGE.confirm specific values
 */
typedef void mcps_purge_confirm(const mac_api_t *api, mcps_purge_conf_t *data);

/**
 * @brief mlme_confirm One of the MLME primitive confirm callbacks
 * @param api API which handled the response
 * @param id The identifier of the MLME primitive
 * @param data Primitive specific data (\see mlme.h)
 */
typedef void mlme_confirm(const mac_api_t *api, mlme_primitive id, const void *data);

/**
 * @brief mlme_indication One of the
 * @param api API which handled the response
 * @param id The identifier of the MLME primitive
 * @param data Primitive specific data (\see mlme.h)
 */
typedef void mlme_indication(const mac_api_t *api, mlme_primitive id, const void *data);

/**
 * @brief Set extended address from MAC
 * @param api API to handle the request
 * @param mac64 pointer
 */
typedef int8_t mac_ext_mac64_address_set(const mac_api_t *api, const uint8_t *mac64);

/**
 * @brief Read extended address from MAC
 * @param api API to handle the request
 * @param mac64_buf Pointer where mac extended address can be written
 */
typedef int8_t mac_ext_mac64_address_get(const mac_api_t *api, mac_extended_address_type type, uint8_t *mac64_buf);

/**
 * @brief Read MAC security description storage sizes from MAC
 * @param api API to handle the request
 * @param buffer Pointer where supported sizes can be written
 */
typedef int8_t mac_storage_decription_sizes_get(const mac_api_t *api, mac_description_storage_size_t *buffer);

/**
 * @brief mac_api_initialize Initialises MAC layer into use, callbacks must be non-NULL.
 * @param api mac_api_t pointer, which is created by application.
 * @param data_conf_cb Upper layer function to handle MCPS confirmations
 * @param data_ind_cb Upper layer function to handle MCPS indications
 * @param mlme_conf_cb Upper layer function to handle MLME confirmations
 * @param mlme_ind_cb Upper layer function to handle MLME indications
 * @param parent_id Upper layer id, which is used in confirmation and indication callbacks
 * @return -1 if error, -2 if OOM, 0 otherwise
 */
typedef int8_t mac_api_initialize(mac_api_t *api, mcps_data_confirm *data_conf_cb,
                                  mcps_data_indication *data_ind_cb, mcps_purge_confirm *purge_conf_cb, mlme_confirm *mlme_conf_cb,
                                  mlme_indication *mlme_ind_cb, int8_t parent_id);

/**
 * @brief mac_api_enable_mcps_ext Initialises MAC 2015 extension for MCPS layer into use, callbacks must be non-NULL.
 * @param api mac_api_t pointer, which is created by application.
 * @param data_ind_cb Upper layer function to handle MCPS indications
 * @param data_cnf_cb Upper layer function to handle MCPS confirmation
 * @param ack_data_req_cb Upper layer function for set Enhanced ACK payload
 * @return -1 if error, -2 if OOM, 0 otherwise
 */
typedef int8_t mac_api_enable_mcps_ext(mac_api_t *api,
                                       mcps_data_indication_ext *data_ind_cb,
                                       mcps_data_confirm_ext *data_cnf_cb,
                                       mcps_ack_data_req_ext *ack_data_req_cb);

/**
 * @brief mac_api_enable_mcps_edfe_ext Initialises MAC 2015 extension for EDFE handler callbacks must be non-NULL.
 * @param api mac_api_t pointer, which is created by application.
 * @param edfe_ind_cb Upper layer function to handle and detect EDFE's
 * @return -1 if error, -2 if OOM, 0 otherwise
 */
typedef int8_t mac_api_enable_mcps_edfe_ext(mac_api_t *api,
                                            mcps_edfe_handler *edfe_ind_cb);

/**
 * @brief mac_api_mode_switch_resolver_ext Initialises mode switch resolver callback. Upper layer must configure function when mode switch is used.
 * @param api mac_api_t pointer, which is created by application.
 * @param mode_resolver_cb Upper layer function to resolve received PHY mode ID
 * @param base_phy_mode Base PHY mode, device returns to this mode after mode switch transmission or reception
 * @return -1 if error, 0 otherwise
 */
typedef int8_t mac_api_mode_switch_resolver_ext(mac_api_t *api,
                                                mode_switch_resolver *mode_resolver_cb, uint8_t base_phy_mode);

/**
 * \brief Struct mac_api_s defines functions for two-way communications between external MAC and Upper layer.
 * Application creates mac_api_t object by calling external MAC's creator function.
 * Then object is passed to Upper layer which then initializes it's own callback functions.
 * Then MAC is operated by Upper layer by calling MLME or MCPS primitive functions.
 */
struct mac_api_s {
    mac_api_initialize                  *mac_initialize;                /**< MAC initialize function to use */
    mac_api_enable_mcps_ext             *mac_mcps_extension_enable;     /**< MAC MCPS IE extension enable function, optional feature */
    mac_api_enable_mcps_edfe_ext        *mac_mcps_edfe_enable;          /**< MAC MCPS MCPS EDFE frame extension enable function, optional feature */
    mac_api_mode_switch_resolver_ext    *mac_mode_switch_resolver_set;  /**< MAC Mode switch resolver function set, optional feature */
    //External MAC callbacks
    mlme_request                        *mlme_req;                      /**< MAC MLME request function to use */
    mcps_data_request                   *mcps_data_req;                 /**< MAC MCPS data request function to use */
    mcps_data_request_ext               *mcps_data_req_ext;             /**< MAC MCPS data request with Information element extension function to use */
    mcps_purge_request                  *mcps_purge_req;                /**< MAC MCPS purge request function to use */
    //Upper layer callbacksMLME_ASSOCIATE
    mcps_data_confirm                   *data_conf_cb;                  /**< MAC MCPS data confirm callback function */
    mcps_data_confirm_ext               *data_conf_ext_cb;              /**< MAC MCPS data confirm with payload callback function */
    mcps_data_indication                *data_ind_cb;                   /**< MAC MCPS data indication callback function */
    mcps_data_indication_ext            *data_ind_ext_cb;               /**< MAC MCPS data indication with IE extension's callback function */
    mcps_edfe_handler                   *edfe_ind_cb;                   /**< MAC MCPS EDFE detection extension's callback function */
    mode_switch_resolver                *mode_resolver_cb;              /**< MAC Mode switch resolver callback function */
    mcps_ack_data_req_ext               *enhanced_ack_data_req_cb;      /**< Enhanced ACK IE element and payload request from MAC user */
    mcps_purge_confirm                  *purge_conf_cb;                 /**< MAC MCPS purge confirm callback function */
    mlme_confirm                        *mlme_conf_cb;                  /**< MAC MLME confirm callback function */
    mlme_indication                     *mlme_ind_cb;                   /**< MAC MLME indication callback function */
    mac_ext_mac64_address_set           *mac64_set;                     /**< MAC extension function to set mac64 address */
    mac_ext_mac64_address_get           *mac64_get;                     /**< MAC extension function to get mac64 address */
    mac_storage_decription_sizes_get    *mac_storage_sizes_get;         /**< Getter function to query data storage sizes from MAC */

    int8_t                              parent_id;                      /**< Upper layer id */
    uint16_t                            phyMTU;                         /**< Maximum Transmission Unit(MTU) used by MAC*/
};

/**
 * \struct mac_statistics_s
 * \brief MAC statistics structure.
 */
typedef struct mac_statistics_s {
    uint16_t mac_tx_queue_size;         /**< MAC TX queue current size. */
    uint16_t mac_tx_queue_peak;         /**< MAC TX queue peak size. */
    uint32_t mac_rx_count;              /**< MAC RX packet count. */
    uint32_t mac_tx_count;              /**< MAC TX packet count. */
    uint32_t mac_bc_rx_count;           /**< MAC broadcast RX packet count. */
    uint32_t mac_bc_tx_count;           /**< MAC broadcast TX packet count. */
    uint32_t mac_beacon_rx_count;       /**< MAC Beacon RX packet count. */
    uint32_t mac_beacon_tx_count;       /**< MAC Beacon TX packet count. */
    uint32_t mac_rx_drop_count;         /**< MAC RX packet drop count. */
    uint32_t mac_tx_bytes;              /**< MAC TX bytes count. */
    uint32_t mac_rx_bytes;              /**< MAC RX bytes count. */
    uint32_t mac_tx_failed_count;       /**< MAC TX failed count. */
    uint32_t mac_retry_count;           /**< MAC TX retry count. */
    uint32_t mac_cca_attempts_count;    /**< MAC CCA attempts count. */
    uint32_t mac_failed_cca_count;      /**< MAC failed CCA count. */
    uint32_t mac_tx_latency_max;        /**< MAC data request max latency. */
} mac_statistics_t;

#ifdef __cplusplus
}
#endif

#endif // MAC_API_H


text:
@class DAYStandup;

@interface DAYReportViewController : UIViewController

@property (strong, nonatomic) DAYStandup *standup;

@end