text:
	<tabset>

		<tab heading="Example">

Map

							<google-map center="mymap.center" zoom="mymap.zoom" draggable="true" dragging="mymap.dragging">
							<marker pan="true" idKey='$index' data-ng-repeat="gmarker in markers" coords="gmarker.coords" ></marker>
							</google-map>

  				<form id="form" role="form">

	        				Generic Autocomplete
	        				<input type="text" id="Autocomplete" class="form-control" ng-autocomplete ng-model="result1" details="details1"/>

Found {{details1.address_components[0].long_name}} located at lat:{{details1.geometry.location.k}} , lng:{{details1.geometry.location.B}}

	    				<button data-ng-show="details1" data-ng-click="addMarker(details1.geometry.location)">Add marker</button>
					</form>

		</tab>
		<tab heading="Overview">

Overview

				The gmap package overall target is to provide an implementation of a fullstack package that collects location data from a object and displays it on a map.

				Note this is a work in progress and currently we have implemented only the client side.

				The package is based on two excellent open source directives.

Google maps for Angular.js

ngAutocomplete

				The full documentation resides in the links above but to quickly start you will need to use the <google-map> directive to create a map like this...

					<google-map center="mymap.center" zoom="mymap.zoom"
					draggable="true" dragging="mymap.dragging">

			   and add markers using the marker directive like this..

			   	<marker pan="true" idKey='$index' data-ng-repeat="gmarker in markers" coords="gmarker.coords" ></marker>

			   and close the map like this -
			   </google-map>

We have blogged about the process of developing this package here

Notes and Cool tips

You can play with the default settings of the map using it's invocation in gmap/public/controllers/gmap.js

Try to mix gmap with the socket package - imagine pushing a mobile device location and seeing it move on the map using the socket packge. :)

		</tab>

	</tabset>


text:
package presignedurl

// goModuleVersion is the tagged release for this module
const goModuleVersion = "1.9.7"

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Verrucaria danubica Servít

### Remarks
null


text:
import { Route } from "../Route";
export declare class ErrorRouteExists extends Error {
    constructor(route: Route);
}


text:
var assert = require('assert')
var StrangeItem = require('..')

describe('Strange Item sanity tests', () => {

  it('returns a class', () => {
    assert.strictEqual(typeof(StrangeItem), 'function') // prototypal inheritance
  })

  it('can be instanced', () => {
    var mySI = new StrangeItem()
    assert.ok(mySI instanceof StrangeItem)
  })

  it('instances have a value property', () => {
    var mySI = new StrangeItem()
    assert.ok(mySI.hasOwnProperty('value'))
  })
})

describe('Strange Item get/set tests', () => {
  var mySI = null

  beforeEach(() => {
    mySI = new StrangeItem('foo')
  })

  it('StrangeItem(value)', () => {
    assert.strictEqual(mySI.value, 'foo')
  })

  it('StrangeItem.set(value)', () => {
    mySI.set('bar')
    assert.strictEqual(mySI.value, 'bar')
  })

  it('StrangeItem.get()', () => {
    assert.strictEqual(mySI.get(), 'foo')
  })
})

describe('Strange Item binding tests', () => {
  var mySI = null
  var mockDOMElement = null

  beforeEach(() => {
    mySI = new StrangeItem('foo')
    mockDOMElement = {
      innerHTML: '',
      value: ''
    }
  })

  it('creates a binding', () => {
    mySI.bind(mockDOMElement)
    assert.strictEqual(mySI.bindings.length, 1)
    assert.deepStrictEqual(mySI.bindings[0].element, mockDOMElement)
    assert.strictEqual(mySI.bindings[0].attribute, 'innerHTML')
  })

  it('initializes the DOM element', () => {
    mySI.bind(mockDOMElement)
    assert.strictEqual(mockDOMElement.innerHTML, 'foo')
  })

  it('updates the DOM element when the value is changed', () => {
    mySI.bind(mockDOMElement)
    mySI.set('bar')
    assert.strictEqual(mockDOMElement.innerHTML, 'bar')
  })

  it('works for properties other than innerHTML', () => {
    mySI.bind(mockDOMElement, 'value')
    assert.strictEqual(mockDOMElement.value, 'foo')
    mySI.set('bar')
    assert.strictEqual(mockDOMElement.value, 'bar')
  })
})

describe('Strange Item autoUpdate tests', () => {

  describe('initializes', () => {
    it('has autoUpdate enabled by default', () => {
      var mySI = new StrangeItem('foo')
      assert.ok(mySI.hasOwnProperty('autoUpdate'))
      assert.ok(mySI.autoUpdate)
    })

    it('can be passed autoUpdate from the constructor', () => {
      var mySI = new StrangeItem('foo', { autoUpdate: false })
      assert.ok(!mySI.autoUpdate)
    })
  })

  describe('usage with autoUpdate = false', () => {
    var mySI = null
    var mockDOMElement = null

    beforeEach(() => {
      mySI = new StrangeItem('foo')
      mockDOMElement = {
        innerHTML: 'bar',
        value: ''
      }
      mySI.autoUpdate = false
      mySI.bind(mockDOMElement)
    })

    it('does not update the DOM element when bind is called and autoUpdate is false', () => {
      assert.strictEqual(mockDOMElement.innerHTML, 'bar')
    })

    it('does not update the DOM element when set is called and autoUpdate is false', () => {
      mySI.set('qux')
      assert.strictEqual(mockDOMElement.innerHTML, 'bar')
    })

    it('updates the DOM element when update is called even with autoUpdate = false', () => {
      mySI.set('qux')
      mySI.update()
      assert.strictEqual(mockDOMElement.innerHTML, 'qux')
    })
  })
})

describe('Strange Item insanity tests', () => {

  it('supports toString', () => {
    var mySI = new StrangeItem('foo')
    assert.strictEqual(mySI.toString(), 'foo')
    assert.strictEqual(mySI + '', 'foo')
  })

  it('supports method chaining', () => {
    var mySI = new StrangeItem('foo')
    assert.deepStrictEqual(mySI.bind({}), mySI)
    assert.deepStrictEqual(mySI.set('bar'), mySI)
    assert.deepStrictEqual(mySI.update(), mySI)
  })
})


text:
//
//  MSContainerView.h
//  YMInfo
//
//  Created by yangshiyu on 2017/2/8.
//  Copyright © 2017年 272789124@qq.com. All rights reserved.
//
//管理多个controller 左右滚动,自带可滚动的menu可用于切换菜单

#import <UIKit/UIKit.h>
#import "MSNavigationView.h"

@interface MSContainerView : UIView
{
    UIView<MSNavigatorView> *_navigationView;
}

@property (nonatomic, strong, readonly) UIView<MSNavigatorView> *navigationView;
@property (assign, nonatomic) NSInteger selectedIndex;

/**
 *
 *
 *  @param viewControllers
 *  @param navigationClass 导航条的类型
 *
 *  @return
 */
- (instancetype)initWithViewControllers:(NSArray *)viewControllers navigationClass:(Class<MSNavigatorView>)navigationClass;

/**
 *  采用默认的navigationView
 *
 *  @param viewControllers 显示的一组controller
 *
 *  @return
 */
- (instancetype)initWithViewControllers:(NSArray *)viewControllers;

/**
 *  获取当前显示的controller
 *
 *  @return
 */
- (UIViewController *)currentController;

@end


text:
/**
 covariance_plate.cpp
 Purpose: This files contains the body for the functions defined in covariance_plate.h

 @author Ignasi Pérez-Ràfols
 @version 1.0 10/02/2014
 */

#include "covariance_plate.h"

CovariancePlate::CovariancePlate(int bad_data){
    /**
     EXPLANATION:
     Constructs a CovariancePlate instance and initializes all its variables

     INPUTS:
     bad_data - a double valued _BAD_DATA_INT_

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     ToStr
     */
    if (bad_data != _BAD_DATA_INT_){
        std::cout << "Error while initializing a CovariancePlate 'bad data' instance" << std::endl;
        std::exit(EXIT_FAILURE);
    }

    plate_number_ = _BAD_DATA_INT_;

}

CovariancePlate::CovariancePlate(const Input& input, const int plate_number, const std::vector<int>& plate_neighbours){
    /**
     EXPLANATION:
     Cosntructs a CovariancePlate instance and initializes all its variables

     INPUTS:
     input - a Input instance
     plate_number - an integer with the plate number
     plate_neighbours - a vector containing the plate numbers of the neighbouring plates

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     ToStr
     */

    // set flags from input
    flag_verbose_covariance_plate_ = input.flag_verbose_covariance_plate();

    plate_number_ = plate_number;
    plate_neighbours_ = plate_neighbours;
    num_bins_ = input.num_bins();
    pairs_file_name_ = ToStr(plate_number_);

    // initialize covariance matrix computation
    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = i; j < num_bins_; j++){
            cov_mat_[std::pair<size_t,size_t>(i,j)] = 0.0;
            //weight_[std::pair<size_t,size_t>(i,j)] = 0.0;
        }
    }
    weight_.resize(num_bins_, 0.0);

}

CovariancePlate::CovariancePlate(const int plate_number, const int num_bins, const std::vector<int>& plate_neighbours, size_t flag_verbose_covariance_plate){
    /**
     EXPLANATION:
     Cosntructs a CovariancePlate instance and initializes all its variables

     INPUTS:
     input - a Input instance
     plate_number - an integer with the plate number
     plate_neighbours - a vector containing the plate numbers of the neighbouring plates
     flag_verbose_covariance_plate_ - correlation_plate verbose flag

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     ToStr
     */

    flag_verbose_covariance_plate_ = flag_verbose_covariance_plate;

    plate_number_ = plate_number;
    plate_neighbours_ = plate_neighbours;
    num_bins_ = num_bins;

    // initialize covariance matrix computation
    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = i; j < num_bins_; j++){
            cov_mat_[std::pair<size_t,size_t>(i,j)] = 0.0;
            //weight_[std::pair<size_t,size_t>(i,j)] = 0.0;
        }
    }
    weight_.resize(num_bins_, 0.0);
}

double CovariancePlate::weight(size_t i) const{
    /**
     EXPLANATION:
     Access function for weight_

     INPUTS:
     index - index of the selected weight_ element

     OUTPUTS:
     the weight for the selected bin

     CLASSES USED:
     CorrelationPlate

     FUNCITONS USED:
     NONE
     */
    if (i < weight_.size()){
        return weight_[i];
    }
    else{
        std::cout << "Warining: in CovariancePlate::set_weight(i, value): The given index is out of bouds, returning BAD_DATA..." << std::endl;
        return _BAD_DATA_;
    }
}

void CovariancePlate::set_cov_mat(size_t i, size_t j, double value){
    /**
     EXPLANATION:
     Set function for cov_mat_

     INPUTS:
     i,j - indexs of the selected cov_mat_ element
     value - element's new value

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     NONE
     */

    CovMat::iterator it = cov_mat_.find(std::pair<size_t, size_t>(i,j));
    if (it != cov_mat_.end()){
        (*it).second = value;
    }
    else{
        std::cout << "Warining: in CovariancePlate::set_cov_mat(i, j, value): The given index is out of bouds, ignoring..." << std::endl;
    }
}

//void CovariancePlate::set_weight(size_t i, size_t j, double value){
void CovariancePlate::set_weight(size_t i, double value){
    /**
     EXPLANATION:
     Set function for weight_

     INPUTS:
     index - index of the selected weight_ element
     value - element's new value

     OUTPUTS:
     NONE

     CLASSES USED:
     CorrelationPlate

     FUNCITONS USED:
     NONE
     */

    if (i < weight_.size()){
        weight_[i] = value;
    }
    else{
        std::cout << "Warining: in CovariancePlate::set_weight(i, value): The given index is out of bouds, ignoring..." << std::endl;
    }
    /*CovMat::iterator it = weight_.find(std::pair<size_t, size_t>(i,j));
    if (it != weight_.end()){
        (*it).second = value;
    }
    else{
        std::cout << "Warining: in CovariancePlate::set_weight(i, j, value): The given index is out of bouds, ignoring..." << std::endl;
    }*/
}

void CovariancePlate::AddPair(const LyaPixel& pixel1, const LyaPixel& pixel2, const size_t& i, const size_t& j, const LyaAutoInterpolationMap& lya_auto){
    /**
     EXPLANATION:
     Adds pair contribution to the covariance matrix in the specified bin

     INPUTS:
     pixel1,pixel2 - LyaPixel instances to add the contribution from
     i,j - covariance matrix element to add the contributions to
     lya_auto - LyaAutoInterpolationMap for the pixel's separation

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate
     LyaAutoInterpolationMap
     LyaPixel

     FUNCITONS USED:
     NONE
     */

    CovMat::iterator it, it_weight;
    if (i <= j){
        it = cov_mat_.find(std::pair<size_t, size_t>(i, j));
        //it_weight = weight_.find(std::pair<size_t, size_t>(i, j));
    }
    else{
        it = cov_mat_.find(std::pair<size_t, size_t>(j, i));
        //it_weight = weight_.find(std::pair<size_t, size_t>(j, i));
    }
    if (it == cov_mat_.end()){ //or it_weight == weight_.end()){
        std::cout << "Warning : In CovarianceMatrix::ComputeCovMat : Element " << i << ", " << j << " of the covariance matrix not found. Ignoring..."  << std::endl;
        return;
    }

    // add to covariance matrix
    double weight = pixel1.weight()*pixel2.weight();
    double add = lya_auto.LinearInterpolation((pixel1.z()+pixel2.z())/2.0);

    if (add != _BAD_DATA_){
        (*it).second += add*weight;
    }

}

void CovariancePlate::ComputeCovMat(const AstroObjectDataset& object_list, const SpectraDataset& spectra_list, const Input& input, const std::vector<LyaAutoInterpolationMap>& lya_auto){
    /**
     EXPLANATION:
     Computes the covariance matrix

     INPUTS:
     object_list - an AstroObjectDataset instance
     spectra_list - a SpectraDataset instance
     input - a Input instance to load bin settings
     lya_auto - an IntepolationMap containing the 1D Lya forest auto-correlation

     OUTPUTS:
     NONE

     CLASSES USED:
     AstroObjectDataset
     CovariancePlate
     Input
     LyaPixel
     LyaSpectrum
     SpectraDataset

     FUNCITONS USED:
     NONE
     */
    if (plate_number_ == _NORM_){
        #pragma omp critical (cout)
        {
            std::cout << "Warning : In CovariancePlate::ComputeCovMat : Plate number is set to _NORM_. The covariance should not be computed in this CovariancePlate instance. Ignoring..." << std::endl;
        }
        return;
    }

    // load bin settings
    double max_pi = input.max_pi();
    double max_sigma = input.max_sigma();
    double step_pi = input.step_pi();
    double step_sigma = input.step_sigma();
    double num_pi_bins = input.num_pi_bins();
    double num_sigma_bins = input.num_sigma_bins();
    size_t pixels_separation = input.pixels_separation();

    size_t number_of_spectra = spectra_list.num_objects_in_plate(plate_number_);

    if (flag_verbose_covariance_plate_ >= 1){
        #pragma omp critical (cout)
        {
            std::cout << "Computing covariance_matrix in plate " << plate_number_ << ". In this plate there are " << number_of_spectra << " LyaSpectra" << std::endl;
        }
    }
    if (number_of_spectra == 0){
        return;
    }

    // loop over LyaSpectra
    for (size_t lya_spectrum_num = 0; lya_spectrum_num < number_of_spectra; lya_spectrum_num ++){

        LyaSpectrum lya_spectrum = spectra_list.list(plate_number_, lya_spectrum_num);
        // checking that the object was loaded successfully
        if (lya_spectrum.dist() == _BAD_DATA_){
            if (flag_verbose_covariance_plate_ >= 2){
                #pragma omp critical (cout)
                {
                    std::cout << "_BAD_DATA_ LyaSpectrum found. Ignoring..." << std::endl;
                }
            }
            continue;
        }
        std::vector<LyaPixel> spectrum = lya_spectrum.spectrum();

        // loop over neighbouring plates 1
        for (size_t plate_neighbours_num1 = 0; plate_neighbours_num1 < plate_neighbours_.size(); plate_neighbours_num1 ++){

            size_t number_of_objects1 = object_list.num_objects_in_plate(plate_neighbours_[plate_neighbours_num1]);
            if (number_of_objects1 == 0){
                continue;
            }

            // loop over AstroObjects 1
            for (size_t object_num1 = 0; object_num1 < number_of_objects1; object_num1 ++){

                AstroObject object1 = object_list.list(plate_neighbours_[plate_neighbours_num1], object_num1);

                // checking that the object was loaded successfully
                if (object1.dist() == _BAD_DATA_){
                    if (flag_verbose_covariance_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "_BAD_DATA_ AstroObject found. Ignoring..." << std::endl;
                        }
                    }
                    continue;
                }

                double sigma_aux_o_1 = 2.0*object1.dist(); // auxiliar variable to compute sigma values

                // compute angular separation
                double cos_theta1 = object1.angle().CosAngularDistance(lya_spectrum.angle());

                double sigma_aux1;
                if (cos_theta1 == 1.0){
                    sigma_aux1 = 0.0;
                }
                else{
                    sigma_aux1 = sigma_aux_o_1*(1.0-cos_theta1); // auxiliar variable to compute sigma values
                }

                // check if all pixels in the spectrum are too far apart
                double pair_min_sigma1 = sqrt(sigma_aux1*spectrum[0].dist()); // minimum distance obtained for lowest redshift pixel
                if (pair_min_sigma1 > max_sigma){ // if the minimum value for sigma (r_perp) is too large, the whole spectra is discarded
                    if (flag_verbose_covariance_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: min_sigma is too large" << std::endl;
                        }
                        if (flag_verbose_covariance_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "min_sigma = " << pair_min_sigma1 << std::endl;
                                std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                std::cout << object1.angle() << " " << lya_spectrum.angle() << " " << cos_theta1 << " " << acos(cos_theta1) << " " << pair_min_sigma1 << std::endl;
                            }
                        }
                    }
                    continue;
                }
                // if the spectrum is being paired with its quasar, the whole spectra is discarded
                if (pair_min_sigma1 <= 0.1){
                    if (flag_verbose_covariance_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: It is being paired with its origin quasar" << std::endl;
                        }
                    }
                    continue;
                }

                double pair_max_pi1 = spectrum.back().dist() - object1.dist(); // minimum distance obtained for lowest redshift pixel
                if (pair_max_pi1 < -max_pi) { // if maximum value for pi (r_par) is too small, the whole spectra is discarded
                    if (flag_verbose_covariance_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: max_pi is too small" << std::endl;
                        }
                        if (flag_verbose_covariance_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "max_pi = " << pair_max_pi1 << std::endl;
                                std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                std::cout << object1.angle() << " " << lya_spectrum.angle() << " " << cos_theta1 << " " << acos(cos_theta1) << " " << pair_max_pi1 << std::endl;
                            }
                        }
                    }
                    continue;
                }

                double pair_min_pi1 = spectrum[0].dist() - object1.dist(); // maximum distance obtained for highest redshift pixel
                if (pair_min_pi1 > max_pi){ // if minimum value for pi (r_par) is too high, the whole spectrum is discarded
                    if (flag_verbose_covariance_plate_ >= 2){
                        #pragma omp critical (cout)
                        {
                            std::cout << "Spectrum rejected: min_pi is too large" << std::endl;
                        }
                        if (flag_verbose_covariance_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "min_pi = " << pair_min_pi1 << std::endl;
                                std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                std::cout << object1.angle() << " " << lya_spectrum.angle() << " " << cos_theta1 << " " << acos(cos_theta1) << " " << pair_min_pi1 << std::endl;
                            }
                        }
                    }
                    continue;
                }

                // loop over LyaPixels1
                for (int pixel1 = 0; pixel1 < spectrum.size(); pixel1 ++){

                    // cehck that the weight is not zero
                    if (spectrum[pixel1].weight() == 0.0){
                        continue;
                    }

                    // compute pi and sigma
                    double sigma1 = sqrt(sigma_aux1*spectrum[pixel1].dist());
                    if (sigma1 > max_sigma){ // if sigma (r_perp) is too large, discard pixel
                        if (flag_verbose_covariance_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: sigma is too large" << std::endl;
                                std::cout << "sigma = " << sigma1 << std::endl;
                            }
                        }
                        continue;
                    }

                    double pi1 = spectrum[pixel1].dist()-object1.dist();
                    if ((pi1 > max_pi) or (pi1 <- max_pi)){ // if pi (r_par) is too large or too small, discard pixel
                        if (flag_verbose_covariance_plate_ >= 3){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: abs(pi) is too large" << std::endl;
                                std::cout << "pi = " << pi1 << std::endl;
                            }
                        }
                        continue;
                    }

                    // locate pi pixel (i_index)
                    int i_index1 = int(pi1/step_pi)+num_pi_bins/2;
                    if (pi1<0.0){
                        i_index1 -= 1;
                    }
                    if (i_index1 < 0){
                        if (flag_verbose_covariance_plate_ >= 2){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: Bad indexing: i_index = " << i_index1 << std::endl;
                            }
                        }
                        continue;
                    }

                    // locate sigma pixel (j_index)
                    int j_index1 = int(sigma1/step_sigma);
                    if (j_index1 < 0){
                        if (flag_verbose_covariance_plate_ >= 2){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: Bad indexing: j_index = " << j_index1 << std::endl;
                            }
                        }
                        continue;
                    }

                    // locate xi pixel (k)
                    int k_index1 = i_index1*num_sigma_bins+j_index1;
                    if (k_index1 < 0){
                        if (flag_verbose_covariance_plate_ >= 2){
                            #pragma omp critical (cout)
                            {
                                std::cout << "Pixel rejected: Bad indexing: k_index = " << k_index1 << std::endl;
                            }
                        }
                        continue;

                    }

                    // pair found, add weight to denominator
                    weight_[k_index1] += spectrum[pixel1].weight();

                    // loop over neighbouring plates 2
                    for (size_t plate_neighbours_num2 = plate_neighbours_num1; plate_neighbours_num2 < plate_neighbours_.size(); plate_neighbours_num2 ++){

                        size_t number_of_objects2 = object_list.num_objects_in_plate(plate_neighbours_[plate_neighbours_num2]);
                        if (number_of_objects2 == 0){
                            continue;
                        }

                        // loop over AstroObjects 2
                        for (size_t object_num2 = 0; object_num2 < number_of_objects2; object_num2 ++){

                            AstroObject object2 = object_list.list(plate_neighbours_[plate_neighbours_num2], object_num2);

                            // checking that the object was loaded successfully
                            if (object2.dist() == _BAD_DATA_){
                                if (flag_verbose_covariance_plate_ >= 2){
                                    #pragma omp critical (cout)
                                    {
                                        std::cout << "_BAD_DATA_ AstroObject found. Ignoring..." << std::endl;
                                    }
                                }
                                continue;
                            }

                            double sigma_aux_o_2 = 2.0*object2.dist(); // auxiliar variable to compute sigma values

                            // compute angular separation
                            double cos_theta2 = object2.angle().CosAngularDistance(lya_spectrum.angle());

                            double sigma_aux2;
                            if (cos_theta2 == 1.0){
                                sigma_aux2 = 0.0;
                            }
                            else{
                                sigma_aux2 = sigma_aux_o_2*(1.0-cos_theta2); // auxiliar variable to compute sigma values
                            }

                            // check if all pixels in the spectrum are too far apart
                            double pair_min_sigma2 = sqrt(sigma_aux2*spectrum[0].dist()); // minimum distance obtained for lowest redshift pixel
                            if (pair_min_sigma2 > max_sigma){ // if the minimum value for sigma (r_perp) is too large, the whole spectra is discarded
                                if (flag_verbose_covariance_plate_ >= 2){
                                    #pragma omp critical (cout)
                                    {
                                        std::cout << "Spectrum rejected: min_sigma is too large" << std::endl;
                                    }
                                    if (flag_verbose_covariance_plate_ >= 3){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "min_sigma = " << pair_min_sigma2 << std::endl;
                                            std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                            std::cout << object2.angle() << " " << lya_spectrum.angle() << " " << cos_theta2 << " " << acos(cos_theta2) << " " << pair_min_sigma2 << std::endl;
                                        }
                                    }
                                }
                                continue;
                            }
                            // if the spectrum is being paired with its quasar, the whole spectra is discarded
                            if (pair_min_sigma2 <= 0.1){
                                if (flag_verbose_covariance_plate_ >= 2){
                                    #pragma omp critical (cout)
                                    {
                                        std::cout << "Spectrum rejected: It is being paired with its origin quasar" << std::endl;
                                    }
                                }
                                continue;
                            }

                            double pair_max_pi2 = spectrum.back().dist() - object2.dist(); // minimum distance obtained for lowest redshift pixel
                            if (pair_max_pi2 < -max_pi) { // if maximum value for pi (r_par) is too small, the whole spectra is discarded
                                if (flag_verbose_covariance_plate_ >= 2){
                                    #pragma omp critical (cout)
                                    {
                                        std::cout << "Spectrum rejected: max_pi is too small" << std::endl;
                                    }
                                    if (flag_verbose_covariance_plate_ >= 3){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "max_pi = " << pair_max_pi2 << std::endl;
                                            std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                            std::cout << object2.angle() << " " << lya_spectrum.angle() << " " << cos_theta2 << " " << acos(cos_theta2) << " " << pair_max_pi2 << std::endl;
                                        }
                                    }
                                }
                                continue;
                            }

                            double pair_min_pi2 = spectrum[0].dist() - object2.dist(); // maximum distance obtained for highest redshift pixel
                            if (pair_min_pi2 > max_pi){ // if minimum value for pi (r_par) is too high, the whole spectrum is discarded
                                if (flag_verbose_covariance_plate_ >= 2){
                                    #pragma omp critical (cout)
                                    {
                                        std::cout << "Spectrum rejected: min_pi is too large" << std::endl;
                                    }
                                    if (flag_verbose_covariance_plate_ >= 3){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "min_pi = " << pair_min_pi2 << std::endl;
                                            std::cout << "ra_object dec_object ra_spectra dec_spectra cos_theta theta min_sigma" << std::endl;
                                            std::cout << object2.angle() << " " << lya_spectrum.angle() << " " << cos_theta2 << " " << acos(cos_theta2) << " " << pair_min_pi2 << std::endl;
                                        }
                                    }
                                }
                                continue;
                            }

                            // loop over LyaPixels2
                            for (int pixel2 = pixel1; pixel2 < spectrum.size() and pixel2 <= pixel1 + pixels_separation; pixel2 ++){

                                // cehck that the weight is not zero
                                if (spectrum[pixel2].weight() == 0.0){
                                    continue;
                                }

                                // compute pi and sigma
                                double sigma2 = sqrt(sigma_aux2*spectrum[pixel2].dist());
                                if (sigma2 > max_sigma){ // if sigma (r_perp) is too large, discard pixel
                                    if (flag_verbose_covariance_plate_ >= 3){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "Pixel rejected: sigma is too large" << std::endl;
                                            std::cout << "sigma = " << sigma2 << std::endl;
                                        }
                                    }
                                    continue;
                                }

                                double pi2 = spectrum[pixel2].dist()-object2.dist();
                                if ((pi2 > max_pi) or (pi2 <- max_pi)){ // if pi (r_par) is too large or too small, discard pixel
                                    if (flag_verbose_covariance_plate_ >= 3){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "Pixel rejected: abs(pi) is too large" << std::endl;
                                            std::cout << "pi = " << pi2 << std::endl;
                                        }
                                    }
                                    continue;
                                }

                                // locate pi pixel (i_index)
                                int i_index2 = int(pi2/step_pi)+num_pi_bins/2;
                                if (pi2<0.0){
                                    i_index2 -= 1;
                                }
                                if (i_index2 < 0){
                                    if (flag_verbose_covariance_plate_ >= 2){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "Pixel rejected: Bad indexing: i_index = " << i_index2 << std::endl;
                                        }
                                    }
                                    continue;
                                }

                                // locate sigma pixel (j_index)
                                int j_index2 = int(sigma2/step_sigma);
                                if (j_index2 < 0){
                                    if (flag_verbose_covariance_plate_ >= 2){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "Pixel rejected: Bad indexing: j_index = " << j_index2 << std::endl;
                                        }
                                    }
                                    continue;
                                }

                                // locate xi pixel (k)
                                int k_index2 = i_index2*num_sigma_bins+j_index2;
                                if (k_index2 < 0){
                                    if (flag_verbose_covariance_plate_ >= 2){
                                        #pragma omp critical (cout)
                                        {
                                            std::cout << "Pixel rejected: Bad indexing: k_index = " << k_index2 << std::endl;
                                        }
                                    }
                                    continue;

                                }

                                // avoid double counting
                                if (pixel2 == pixel1 and plate_neighbours_num2 == plate_neighbours_num1 and object_num2 < object_num1){
                                    continue;
                                }

                                // compute covariance matrix contribution
                                AddPair(spectrum[pixel1],spectrum[pixel2],k_index1,k_index2, lya_auto[pixel2 - pixel1]);
                            }
                        }
                    }

                }
            }
        }
    }

}

void CovariancePlate::Normalize(){
    /**
     EXPLANATION:
     Normalizes the covariance matrix

     INPUTS:
     NONE

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     NONE
     */

    if (plate_number_ == _NORM_){

        CovMat::iterator it, it_weight;
        for (size_t i = 0; i < num_bins_; i ++){
            for (size_t j = i; j < num_bins_; j ++){
                it = cov_mat_.find(std::pair<size_t,size_t>(i,j));
                if (weight_[i] != 0.0 and weight_[j] != 0.0){
                    (*it).second /= weight_[i];
                    (*it).second /= weight_[j];
                }
                else{
                    (*it).second == 0.0;
                }
                //it_weight = weight_.find(std::pair<size_t,size_t>(i,j));
                //if (it != cov_mat_.end() and it_weight != weight_.end()){
                //    (*it).second /= (*it_weight).second;
                //}
            }
        }

    }
    else{
        // if plate number is not _NORM_, the instance is not supposed to normalize
        std::cout << "Warning : In CovariancePlate::Normalize : Plate number is not set to _NORM_. This CovariancePlate instance should not be normalized. Ignoring..." << std::endl;
    }

}

void CovariancePlate::SaveCovMat(const Input& input){
    /**
     EXPLANATION:
     Saves the covariance matrix measured in a specific plate

     INPUTS:
     input - a Input instance

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     NONE
     */
    if (plate_number_ == _NORM_){
        // if plate number is _NORM_, the instance is not supposed to be saved using this function
        std::cout << "Warning : In CovariancePlate::SaveCovMat : Plate number is not set to _NORM_. This CovariancePlate instance should not be saved using this function. Ignoring..." << std::endl;
    }
    else{
        std::string filename;
        CovMat::iterator it, it_weight;

        if (flag_verbose_covariance_plate_ >= 1){
            std::cout << "Saving covariance matrix from plate " << pairs_file_name_ << std::endl;
        }

        filename = input.results() + "plate_" + pairs_file_name_ + ".cov";
        {
            std::ofstream file(filename.c_str(),std::ofstream::trunc);
            if (file.is_open()){
                if (flag_verbose_covariance_plate_ >= 2){
                    std::cout << "Saving full covariance matrix" << std::endl;
                }
                for (size_t i = 0; i < num_bins_; i ++){
                    for (size_t j = i; j < num_bins_; j ++){
                        it = cov_mat_.find(std::pair<size_t, size_t>(i, j));

                        if (it != cov_mat_.end() and weight_[i] != 0.0 and weight_[j] != 0.0){
                            file << i << " " << j << " " << (*it).second/weight_[i]/weight_[j] << std::endl;
                        }
                        else{
                            file << i << " " << j << " NaN" << std::endl;
                        }
                    }
                }

                file.close();
            }
            else{
                std::cout << "Error : In CovariancePlate::SaveCovMat : Unable to open file:" << std::endl << filename << std::endl;
            }
        }

    }

}

void CovariancePlate::operator+= (const CovariancePlate& other){
    /**
     EXPLANATION:
     Overloads the += operator. Updates the xi_, mean_sigma, mean_pi and weight_ or cov_mat_ values by adding those in other.

     INPUTS:
     other - a CovariancePlate instance to be added

     OUTPUTS:
     NONE

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     NONE
     */

    // check that both instances have the same number of bins
    if (num_bins_ != other.num_bins()){
        std::cout << "Warning : In CovariancePlate::operator+= : Trying to add CovariancePlates with different number of bins. Ignoring..." << std::endl;
        return;
    }

    CovMat::iterator it, it_weight;
    CovMat::const_iterator other_it, other_it_weight;

    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = i; j < num_bins_; j++){
            it = cov_mat_.find(std::pair<size_t, size_t>(i, j));
            //it_weight = weight_.find(std::pair<size_t, size_t>(i, j));
            other_it = other.cov_mat_.find(std::pair<size_t, size_t>(i, j));
            //other_it_weight = other.weight_.find(std::pair<size_t, size_t>(i, j));

            if (it != cov_mat_.end() and other_it != other.cov_mat_.end()){
                (*it).second += (*other_it).second;
            }
            /*if (it_weight != weight_.end() and other_it_weight != other.weight_.end()){
                (*it_weight).second += (*other_it_weight).second;
            }*/
        }
    }
    for (size_t index = 0; index < weight_.size(); index ++){
        weight_[index] += other.weight(index);
    }

}

CovariancePlate CovariancePlate::operator- (const CovariancePlate& other){
    /**
     EXPLANATION:
     Overloads the - operator. Returns a new instance with the xi_, mean_sigma, mean_pi and weight_ values or cov_mat subtracted by those in other.

     INPUTS:
     other - a CovariancePlate instance to be subtracted

     OUTPUTS:
     temp - a CovariancePlate instance

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     NONE
     */

    CovariancePlate temp;
    temp = CovariancePlate(plate_number_, num_bins_, plate_neighbours_, flag_verbose_covariance_plate_);

    // check that both instances have the same number of bins
    if (num_bins_ != other.num_bins()){
        std::cout << "Warning : In CovariancePlate::operator+= : Trying to add CovariancePlates with different number of bins. Returning zero filled CovariancePlates..." << std::endl;
        return temp;
    }

    CovMat::iterator it, it_weight;
    CovMat::const_iterator other_it, other_it_weight;

    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = i; j < num_bins_; j++){
            it = cov_mat_.find(std::pair<size_t, size_t>(i, j));
            //it_weight = weight_.find(std::pair<size_t, size_t>(i, j));
            other_it = other.cov_mat_.find(std::pair<size_t, size_t>(i, j));
            //other_it_weight = other.weight_.find(std::pair<size_t, size_t>(i, j));

            if (it != cov_mat_.end() and other_it != other.cov_mat_.end()){
                temp.set_cov_mat(i, j, (*it).second - (*other_it).second);
            }
            //if (it_weight != weight_.end() and other_it_weight != other.weight_.end()){
            //    temp.set_weight(i, j, (*it_weight).second - (*other_it_weight).second);
            //}
        }
    }

    for (size_t index = 0; index < weight_.size(); index ++){
        temp.set_weight(index, other.weight(index) - weight_[index]);
    }

    return temp;

}

CovariancePlate CovariancePlate::operator* (const CovariancePlate& other){
    /**
     EXPLANATION:
     Overloads the * operator. Returns a new instance with the xi_, mean_sigma, mean_pi and weight_ values multiplied by those in other.

     INPUTS:
     other - a CovariancePlate instance to be subtracted

     OUTPUTS:
     temp - a CovariancePlate instance

     CLASSES USED:
     CovariancePlate

     FUNCITONS USED:
     NONE
     */
    CovariancePlate temp;
    temp = CovariancePlate(plate_number_, num_bins_, plate_neighbours_, flag_verbose_covariance_plate_);

    // check that both instances have the same number of bins
    if (num_bins_ != other.num_bins()){
        std::cout << "Warning : In CovariancePlate::operator+= : Trying to add CovariancePlates with different number of bins. Returning zero filled CovariancePlates..." << std::endl;
        return temp;
    }

    CovMat::iterator it, it_weight;
    CovMat::const_iterator other_it, other_it_weight;

    for (size_t i = 0; i < num_bins_; i++){
        for (size_t j = i; j < num_bins_; j++){
            it = cov_mat_.find(std::pair<size_t, size_t>(i, j));
            //it_weight = weight_.find(std::pair<size_t, size_t>(i, j));
            other_it = other.cov_mat_.find(std::pair<size_t, size_t>(i, j));
            //other_it_weight = other.weight_.find(std::pair<size_t, size_t>(i, j));

            if (it != cov_mat_.end() and other_it != other.cov_mat_.end()){
                temp.set_cov_mat(i, j, (*it).second*(*other_it).second);
            }
            //if (it_weight != weight_.end() and other_it_weight != other.weight_.end()){
            //    temp.set_weight(i, j, (*it_weight).second*(*other_it_weight).second);
            //}
        }
    }
    for (size_t index = 0; index < weight_.size(); index ++){
        temp.set_weight(index, other.weight(index)*weight_[index]);
    }

    return temp;

}

double CovariancePlate::half_gamma_ = 3.8/2.0;
double CovariancePlate::one_plus_z0_to_the_half_gamma_ = pow(1+2.25,CovariancePlate::half_gamma_);


text:
from deluca.lung.devices import I2CDevice, be16_to_native
from abc import ABC, abstractmethod
import random
from collections import deque

import time
import numpy as np

class Sensor(ABC):
    """Abstract base Class describing generalized sensors. Defines a mechanism for limited internal storage of recent
    observations and methods to pull that data out for external use.
    """

    _DEFAULT_STORED_OBSERVATIONS = 128

    def __init__(self):
        """ Upon creation, calls update() to ensure that if get is called there will be something to return."""
        self._maxlen_data = self._DEFAULT_STORED_OBSERVATIONS
        self._data = {
            "timestamp": deque(maxlen=self.maxlen_data),
            "value": deque(maxlen=self.maxlen_data),
        }

    def update(self) -> float:
        """Make a sensor reading, verify that it makes sense and store the result internally. Returns True if reading
        was verified and False if something went wrong.
        """
        value = self._read()
        self._data["timestamp"].append(time.time())
        self._data["value"].append(value)
        return self._verify(value)

    def get(self, average=False) -> float:
        """ Return the most recent sensor reading, or an average of readings since last get(). Clears internal memory so as not to have stale data."""
        # FIXME - timeout decorators for everyone
        if len(self._data["value"]) == 0:
            self.update()
        if average:
            value = np.mean(self._data["value"])
        else:
            value = self._data["value"].pop()
        self._clear()
        return value

    def age(self) -> float:
        """ Returns the time in seconds since the last sensor update, or -1 if never updated."""
        if not self._data["timestamp"]:
            return -1.0
        else:
            return time.time() - self._data["timestamp"][-1]

    def reset(self):
        """Resets the sensors internal memory. May be overloaded by subclasses to extend functionality specific to a
        device.
        """
        self._clear()

    def _clear(self):
        """ Resets the sensors internal memory. """
        for key in self._data.keys():
            self._data[key].clear()

    @property
    def data(self) -> np.array:
        """Returns all Locally-stored observations.

        Returns:
            np.array: An array of timestamped observations arranged oldest to newest.
        """
        result = np.column_stack([self._data["timestamp"], self._data["value"]])
        self._clear()
        return result

    @property
    def maxlen_data(self) -> int:
        """Returns the number of observations kept in the Sensor's internal ndarray. Once the ndarray has been filled,
        the sensor begins overwriting the oldest elements of the ndarray with new observations such that the size of the
        internal storage stays constant.
        """
        return self._maxlen_data

    @maxlen_data.setter
    def maxlen_data(self, new_data_length):
        """Set a new length for stored observations. Clears existing
        observations and resets.

        Args:
            new_data_length (int): The new length of internal observation storage
        """
        if type(new_data_length) != int:
            raise ValueError
        new_data = {
            "value": deque(maxlen=new_data_length),
            "timestamp": deque(maxlen=new_data_length),
        }
        for key in new_data.keys():
            new_data[key].extend(self._data[key])
            self._data[key].clear()
            self._data[key] = new_data[key]
        self._maxlen_data = new_data_length

    def _read(self) -> float:
        """ Calls _raw_read and scales the result before returning it."""
        return self._convert(self._raw_read())

    @abstractmethod
    def _verify(self, value):
        """Validate reading and throw exception/alarm if sensor does not appear to be working correctly."""

    @abstractmethod
    def _convert(self, raw):
        """Converts a raw reading from a sensor in whatever format the device communicates with into a meaningful
        result.
        """

    @abstractmethod
    def _raw_read(self):
        """Requests a new observation from the device and returns the raw result in whatever format/units the device
        communicates with.
        """

class AnalogSensor(Sensor):
    """Generalized class describing an analog sensor attached to the ADS1115 analog to digital converter. Inherits from
    the sensor base class and extends with functionality specific to analog sensors attached to the ADS1115. If
    instantiated without a subclass, conceptually represents a voltmeter with a normalized output.
    """

    # TODO The offset voltage/output span & verify/calibrate stuff needs a rethink.
    _DEFAULT_offset_voltage = 0
    _DEFAULT_output_span = 5
    _DEFAULT_CALIBRATION = {
        "offset_voltage": _DEFAULT_offset_voltage,
        "output_span": _DEFAULT_output_span,
        "conversion_factor": 1,
    }

    def __init__(self, adc, **kwargs):
        """Links analog sensor on the ADC with configuration options specified. If no options are specified, it assumes
        the settings currently on the ADC.

        Args:
            adc (vent.io.devices.ADS1115): The adc object to which the AnalogSensor is attached
            **kwargs: `field=value` - see vent.io.devices.ADS1115 for additional documentation. Strongly suggested to
                specify `MUX=adc_pin` here unless you know what you're doing.
        """
        super().__init__()
        self.adc = adc
        if "MUX" not in (kwargs.keys()):
            raise TypeError("User must specify MUX for AnalogSensor creation")
        kwargs = {key: kwargs[key] for key in kwargs.keys() - ("gpio",)}
        self._check_and_set_attr(**kwargs)

    def calibrate(self, **kwargs):
        """Sets the calibration of the sensor, either to the values contained in the passed tuple or by some routine;
        the current routine is pretty rudimentary and only calibrates offset voltage.

        Args:
            **kwargs: calibration_field=value, where calibration field is one of the following: 'offset_voltage',
                output_span' or 'conversion_factor'
        """
        # FIXME
        if kwargs:
            for fld, val in kwargs.items():
                if fld in self._DEFAULT_CALIBRATION.keys():
                    setattr(self, fld, val)
        else:
            for _ in range(50):
                self.update()
                # PRINT FOR DEBUG / HARDWARE TESTING
                print(
                    "Analog Sensor Calibration @ {:6.4f}".format(self.data[self.data.shape[0] - 1]),
                    end="\r",
                )
                time.sleep(0.1)
            self.offset_voltage = np.min(self.data[-50:])
            # PRINT FOR DEBUG / HARDWARE TESTING
            print("Calibrated low-end of AnalogSensor @", " %6.4f V" % self.offset_voltage)

    def _read(self) -> float:
        """ Returns a value in the range of 0 - 1 corresponding to a fraction of the full input range of the sensor."""
        return self._convert(self._raw_read())

    def _verify(self, value) -> bool:
        """Checks to make sure sensor reading was indeed in [0, 1].

        Args:
            value (float): Sensor reading to validate
        """
        report = bool(-1 <= value / self.conversion_factor <= 1)
        # if not report:
        # FIXME: Right now this just expands the calibration range whenever bounds are exceeded, because we're not
        #  familiar enough with our sensors to know when we should really be rejecting values. This approach should
        #  work for debugging/R&D purposes but really ought to be thought through and/or replaced for production.
        #  For example, negative voltages are probably bad. voltages about VDD (~5V) are also probably bad. There is
        #  some expected drift around offset voltage and output span, however, and that drift is going to change
        #  depending on the sensor in question; i.e., voltages between offset_voltage and zero may or may not be ok,
        #  and voltages above the offset+span that do not exceed VDD may or may not be ok as well.
        #    self.offset_voltage = min(self.offset_voltage, value)
        #    self.output_span = max(self.output_span, value - self.offset_voltage)
        #    print('Warning: AnalogSensor calibration adjusted')
        return report

    def _convert(self, raw) -> float:
        """Scales raw voltage into the range 0 - 1.

        Args:
            raw (float): The raw sensor reading to convert.
        """
        return self.conversion_factor * (
            (raw - getattr(self, "offset_voltage")) / getattr(self, "output_span")
        )

    def _raw_read(self) -> float:
        """Builds kwargs from configured fields to pass along to adc, then calls adc.read_conversion(), which returns
        a raw voltage.
        """
        fields = self.adc.USER_CONFIGURABLE_FIELDS
        kwargs = dict(zip(fields, (getattr(self, field) for field in fields)))
        return self.adc.read_conversion(**kwargs)

    def _fill_attr(self):
        """Examines self to see if there are any fields identified as user configurable or calibration that have not
        been write (i.e. were not passed to __init__ as **kwargs). If a field is missing, grabs the default value either
        from the ADC or from _DEFAULT_CALIBRATION and sets it as an attribute.
        """
        for cfld in self.adc.USER_CONFIGURABLE_FIELDS:
            if not hasattr(self, cfld):
                setattr(self, cfld, getattr(self.adc.config, cfld).unpack(self.adc.cfg))
        for dcal, value in self._DEFAULT_CALIBRATION.items():
            if not hasattr(self, dcal):
                setattr(self, dcal, value)

    def _check_and_set_attr(self, **kwargs):
        """Checks to see if arguments passed to __init__ are recognized as user configurable or calibration fields. If
        so, write the value as an attribute like: self.KEY = VALUE. Keeps track of how many attributes are write in this
        way; if at the end there unknown arguments leftover, raises a TypeError; otherwise, calls _fill_attr() to fill
        in fields that were not passed as arguments.

        Args:
            **kwargs: `field=value` - see vent.io.devices.ADS1115 for additional documentation
        """
        allowed = (
            *self.adc.USER_CONFIGURABLE_FIELDS,
            *self._DEFAULT_CALIBRATION.keys(),
        )
        result = 0
        for fld, val in kwargs.items():
            if fld in allowed:
                setattr(self, fld, val)
                result += 1
        if result != len(kwargs):
            raise TypeError("AnalogSensor was passed unknown field(s)", kwargs.items(), allowed)
        self._fill_attr()

class SFM3200(Sensor, I2CDevice):
    """I2C Inspiratory flow sensor manufactured by Sensirion AG. Range: +/- 250 SLM
    Datasheet:
         https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/ ...
            ... 5_Mass_Flow_Meters/Datasheets/Sensirion_Mass_Flow_Meters_SFM3200_Datasheet.pdf
    """

    _DEFAULT_ADDRESS = 0x40
    _FLOW_OFFSET = 32768
    _FLOW_SCALE_FACTOR = 120

    def __init__(self, address=_DEFAULT_ADDRESS, i2c_bus=1, gpio=None):
        """
        Args:
            address (int): The I2C Address of the SFM3200 (usually 0x40)
            i2c_bus (int): The I2C Bus to use (usually `1` on the Raspberry Pi)
            gpio (PigpioConnection): pigpiod connection to use; if not specified, a new one is established
        """
        I2CDevice.__init__(self, address, i2c_bus, gpio)
        Sensor.__init__(self)
        self.reset()
        self._start()

    def reset(self):
        """ Extended to add device specific behavior: Asks the sensor to perform a soft reset. 80 ms soft reset time."""
        super().reset()
        self.write_device(0x2000)
        time.sleep(0.08)  # TODO: this should be an await

    def _start(self):
        """Device specific:Sends the 'start measurement' command to the sensor. Start-up time once command has been
        recieved is 'less than 100ms'
        """
        self.write_device(0x1000)
        time.sleep(0.1)  # TODO: this should be an await

    def _verify(self, value) -> bool:
        """No further verification needed for this sensor. Onboard chip handles all that. Could throw in a CRC8 checker
        instead of discarding them in _convert().

        Args:
            value (float): The sensor reading to verify.
        """
        return True

    def _convert(self, raw) -> float:
        """Overloaded to replace with device-specific protocol. Convert raw int to a flow reading having type float
        with units slm. Implementation differs from parent for clarity and consistency with source material.

        Source:
          https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/ ...
            ... 5_Mass_Flow_Meters/Application_Notes/Sensirion_Mass_Flo_Meters_SFM3xxx_I2C_Functional_Description.pdf

        Args:
            raw (int): The raw value read from the SFM3200
        """
        return (raw - self._FLOW_OFFSET) / self._FLOW_SCALE_FACTOR

    def _raw_read(self) -> int:
        """Performs an read on the sensor, converts received bytearray, discards the last two bytes (crc values - could
        implement in future), and returns a signed int converted from the big endian two complement that remains.
        """
        return be16_to_native(self.read_device(4))

class DLiteSensor(AnalogSensor):
    """D-Lite flow sensor setup.
    This consists of the GE D-Lite sensor configured with
    vacuum lines running to an analog differential pressure sensor.
    """

    def __init__(self, adc, **kwargs):

        super().__init__(adc, **kwargs)

    def _convert(self, raw) -> float:
        """Converts the raw differential voltage signal to
        a measurement of flow in liters-per-minute (LPM).

        We calibrate the D-Lite flow readings using the
        (pre-calibrated) Sensirion flow sensor (see SFM3200).
        Args:
            raw (float): The raw sensor reading to convert.
        """
        raw = super()._convert(raw)
        if raw >= 0:
            # converted_flow = (-1.0*np.sqrt(raw)/np.sqrt(fit_param))
            converted_flow = 192.6426 * (raw) ** (1 / 1.9128)
        else:
            converted_flow = -192.6426 * (np.abs(raw)) ** (1 / 1.9128)
        return converted_flow

    def calibrate(self, **kwargs):
        """Do not run a calibration routine.
        Overrides attempt to calibrate.
        """
        return


text:
"""
Summation of primes

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.

"""

from utils import *

N = 2000000
print sum(primes(N))
# 142913828922


text:
package org.apache.ignite.internal.processors.cache.store;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Annotation for local {@link org.apache.ignite.cache.store.CacheStore} implementation. "Local" here means that there is no global
 * database behind the grid but each node has an independent one.
 *
 * @deprecated Use Apache Ignite Native Persistence
 * in case of need of distributed persistence store.
 */
@Deprecated
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface CacheLocalStore {
    // No-op.
}


text:
import * as b from 'bobril';
import {Main} from './ui/main';

uibench.init('Bobril', '4.38.0');

document.addEventListener('DOMContentLoaded', function (e) {
    document.body.innerHTML = "

";
    let state = null;
    let samples = null;
    b.init(() => {
        if (state != null) {
            return Main(state);
        } else {
            return { tag: "pre", children: JSON.stringify(samples, null, ' ') };
        }
    }, <HTMLElement>document.querySelector('#App'));
    let cache = null;
    uibench.run(
        function (astate) {
            state = astate;
            samples = null;
            b.invalidate();
            b.syncUpdate();
        },
        function (asamples) {
            state = null;
            samples = asamples;
            b.invalidate();
            b.syncUpdate();
        }
    );
});


text:
<?php

namespace PhpBench\Report\Console\Renderer;

use PhpBench\Report\Console\ObjectRenderer;
use PhpBench\Report\Console\ObjectRendererInterface;
use PhpBench\Report\Model\Text;
use Symfony\Component\Console\Output\OutputInterface;

class TextRenderer implements ObjectRendererInterface
{
    public function render(OutputInterface $output, ObjectRenderer $renderer, object $object): bool
    {
        if (!$object instanceof Text) {
            return false;
        }

        $output->writeln($object->text());

        return true;
    }
}


text:
schema: default
title: >-
  Politician Data: Botswana — National Assembly
organization: EveryPolitician
notes: >-
  Data on the people within the National Assembly legislature of Botswana.
resources:
  - name: How To Use The Data
    url: 'http://docs.everypolitician.org/use_the_data.html'
    format: info
  - name: View on EveryPolitician
    url: 'http://everypolitician.org/botswana/'
    format: info
  - name: All Data as Popolo JSON
    url: >-
      https://cdn.rawgit.com/everypolitician/everypolitician-data/5dc4e4c9863c8fa153c141385e31b57a6865a184/data/Botswana/Assembly/ep-popolo-v1.0.json
    format: json
  - name: >-
      11th Parliament of Botswana: From 2014-10-29
    url: >-
      https://cdn.rawgit.com/everypolitician/everypolitician-data/f188c89b9d17ecd166dae389d42b0d4f981042ff/data/Botswana/Assembly/term-11.csv
    format: csv
  - name: Python
    url: 'https://github.com/everypolitician/everypolitician-popolo-python'
    format: library
  - name: Ruby
    url: 'https://github.com/everypolitician/everypolitician-popolo'
    format: library
  - name: R
    url: 'https://github.com/ajparsons/everypoliticianR'
    format: library
last_modified: 2019-04-23T04:03:09
license: ''
category:
  - Botswana
  - People
  - Groups & Bodies
maintainer: EveryPolitician
maintainer_email: team@everypolitician.org
more_info: http://docs.everypolitician.org
---


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

		<title>Evidence příjmů</title>
		<meta http-equiv="Content-Style-Type" content="text/css"/>
		<link rel="stylesheet" href="dokumentace-gui.css" type="text/css" media="screen"/>

			Evidence příjmů

Tomáš Ježek

Záverečná zpráva

				Moje část práce na projektu spočívala v grafickém rozhraní, tedy v návrhu uspořádání swingových komponent a jejich přizpůsobení pro potřeby aplikace (včetně lokalizace do angličtiny, češtiny a slovenštiny). Dále ošetření vkládaných dat už při jejich vpisování (sloupec s formátovaným datem, na celočíselný vstup a rozbalovací menu + červené zvýraznění a tooltip při chybném zadání). Po přidání několika funckí na ukládání do souboru se na tlačítka pak navazovaly funkce vytvořené ostatními členy týmu.

Zpracování

Prvky grafického rozhraní

Tvorba GUI a jeho uspořádání/upravení tak, aby vyhovovalo požadavkům aplikace

Validace vstupů

Zpracování vstupů a propojení s dalšími funkcemi programu

Lokalizace všech GUI komponent do angličtiny, češtiny a slovenštiny, včetně tooltipů a enumu Jobs

saveTextToFile(...) - Několikrát přetížená metoda na ukládání do souboru


text:
/**
 */
package org.jboss.drools;

import org.eclipse.emf.ecore.EObject;

/**
 *
 * A representation of the model object 'Global Type'.
 *
 *
 *

 * The following features are supported:
 *

 *
{@link org.jboss.drools.GlobalType#getIdentifier Identifier}

 *
{@link org.jboss.drools.GlobalType#getType Type}

 *

 *

 *
 * @see org.jboss.drools.DroolsPackage#getGlobalType()
 * @model extendedMetaData="name='global_._type' kind='empty'"
 * @generated
 */
public interface GlobalType extends EObject {
	/**
	 * Returns the value of the 'Identifier' attribute.
	 *
	 *

	 * If the meaning of the 'Identifier' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Identifier' attribute.
	 * @see #setIdentifier(String)
	 * @see org.jboss.drools.DroolsPackage#getGlobalType_Identifier()
	 * @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
	 *        extendedMetaData="kind='attribute' name='identifier'"
	 * @generated
	 */
	String getIdentifier();

	/**
	 * Sets the value of the '{@link org.jboss.drools.GlobalType#getIdentifier Identifier}' attribute.
	 *
	 *
	 * @param value the new value of the 'Identifier' attribute.
	 * @see #getIdentifier()
	 * @generated
	 */
	void setIdentifier(String value);

	/**
	 * Returns the value of the 'Type' attribute.
	 *
	 *

	 * If the meaning of the 'Type' attribute isn't clear,
	 * there really should be more of a description here...
	 *

	 *
	 * @return the value of the 'Type' attribute.
	 * @see #setType(String)
	 * @see org.jboss.drools.DroolsPackage#getGlobalType_Type()
	 * @model dataType="org.eclipse.emf.ecore.xml.type.String" required="true"
	 *        extendedMetaData="kind='attribute' name='type'"
	 * @generated
	 */
	String getType();

	/**
	 * Sets the value of the '{@link org.jboss.drools.GlobalType#getType Type}' attribute.
	 *
	 *
	 * @param value the new value of the 'Type' attribute.
	 * @see #getType()
	 * @generated
	 */
	void setType(String value);

} // GlobalType


text:
<?php
declare(strict_types=1);

namespace TestApp\View\Helper;

use Cake\Event\EventInterface;
use Cake\View\Helper;

/**
 * Extended HtmlHelper
 */
class HtmlAliasHelper extends Helper
{
    public function afterRender(EventInterface $event, string $viewFile): void
    {
    }
}


text:
var _ = require('underscore');
var BaseAnalysisFormModel = require('./base-analysis-form-model');
var template = require('./area-of-influence-form.tpl');
var DistanceConverter = require('builder/value-objects/distance-converter');
var DialogConstants = require('builder/components/form-components/_constants/_dialogs');

var AREA_OF_INFLUENCE_TYPES = require('./area-of-influence-types');
var TYPE_TO_META_MAP = {};
AREA_OF_INFLUENCE_TYPES.map(function (d) {
  TYPE_TO_META_MAP[d.type] = d;
});

module.exports = BaseAnalysisFormModel.extend({

  parse: function (attrs) {
    return _.defaults(
      _.pick(attrs, 'id', 'source'), // maintain default attrs
      this._typeDef(attrs.type).parse(attrs)
    );
  },

  initialize: function () {
    BaseAnalysisFormModel.prototype.initialize.apply(this, arguments);

    this._setSchema();

    this.on('change:type', this._onTypeChanged, this);
    this.on('change:distance', this._onDistanceChanged, this);
    this.on('change:kind', this._onKindChanged, this);
  },

  getTemplate: function () {
    return template;
  },

  getTemplateData: function () {
    return {parametersDataFields: this._typeDef().parametersDataFields};
  },

  /**
   * @override {BaseAnalysisFormModel.updateNodeDefinition}
   */
  updateNodeDefinition: function (nodeDefModel) {
    var attrs = this._formatAttrs(this.attributes);
    nodeDefModel.clear({silent: true});
    nodeDefModel.set(attrs);
  },

  _formatAttrs: function (formAttrs) {
    var customFormattedFormAttrs = this._typeDef().formatAttrs(formAttrs);
    return BaseAnalysisFormModel.prototype._formatAttrs.call(this, customFormattedFormAttrs);
  },

  /**
   * @override {BaseAnalysisFormModel._setSchema}
   */
  _setSchema: function () {
    BaseAnalysisFormModel.prototype._setSchema.call(this,
      this._filterSchemaFieldsByType({
        source: this._primarySourceSchemaItem(),
        type: {
          type: 'Radio',
          text: _t('editor.layers.analysis-form.type'),
          options: AREA_OF_INFLUENCE_TYPES.map(function (d) {
            var isAnalysisTypeEnabled = this._analyses.isAnalysisValidByType(d.type, { configModel: this._configModel });
            var canChangeToType = this._canChangeToType(d.type);
            var isDisabled = !isAnalysisTypeEnabled || !canChangeToType;
            var helpMessage = !isAnalysisTypeEnabled ? _t('editor.layers.analysis-form.disabled-by-config') : _t('editor.layers.analysis-form.valid-type');

            return {
              val: d.type,
              label: d.label,
              disabled: isDisabled,
              help: isDisabled ? helpMessage : ''
            };
          }, this)
        },
        distance: {
          type: 'Radio',
          title: _t('editor.layers.analysis-form.units'),
          options: _.map(DistanceConverter.OPTIONS, function (d) {
            return {
              val: d.distance,
              label: this._distanceLabel(d.distance)
            };
          }, this)
        },
        radius: {
          type: 'Number',
          label: _t('editor.layers.analysis-form.radius'),
          validators: ['required', this._radiusInterval()]
        },
        kind: {
          type: 'Select',
          title: _t('editor.layers.analysis-form.by'),
          dialogMode: DialogConstants.Mode.FLOAT,
          options: [
            {
              val: 'walk',
              label: _t('editor.layers.analysis-form.by-walk')
            }, {
              val: 'car',
              label: _t('editor.layers.analysis-form.by-car')
            }
          ]
        },
        isolines: {
          type: 'Number',
          title: _t('editor.layers.analysis-form.tracts'),
          help: _t('editor.layers.analysis-form.tracts-help'),
          validators: ['required', {
            type: 'interval',
            min: 1,
            max: 4
          }]
        },
        time: {
          type: 'Number',
          title: _t('editor.layers.analysis-form.time-seconds'),
          validators: ['required', this._timeInterval()]
        },
        dissolved: {
          type: 'Radio',
          title: _t('editor.layers.analysis-form.boundaries'),
          options: [
            {
              val: 'false',
              label: _t('editor.layers.analysis-form.intact'),
              help: _t('editor.layers.analysis-form.intact-help')
            }, {
              val: 'true',
              label: _t('editor.layers.analysis-form.dissolved'),
              help: _t('editor.layers.analysis-form.dissolved-help')
            }
          ]
        }
      })
    );
  },

  _canChangeToType: function (type) {
    if (type === this.get('type')) return true;

    var source = this._layerDefinitionModel.findAnalysisDefinitionNodeModel(this.get('source'));
    return source.isValidAsInputForType(type);
  },

  _filterSchemaFieldsByType: function (schema) {
    // Always include the source field in addition to the type-specific fields
    var fields = ['source'].concat(this._typeDef().parametersDataFields.split(','));
    return _.pick(schema, fields);
  },

  _onTypeChanged: function () {
    this._replaceAttrs();
    this._setSchema();
  },

  _onDistanceChanged: function () {
    this._fitParamToRange('radius', this._radiusInterval());
    this._setSchema();
  },

  _onKindChanged: function () {
    this._fitParamToRange('time', this._timeInterval());
    this._setSchema();
  },

  _fitParamToRange: function (paramName, range) {
    var val = this.get(paramName);
    if (val < range.min) {
      val = range.min;
    } else if (val > range.max) {
      val = range.max;
    }
    this.set(paramName, val, {silent: true});
  },

  _replaceAttrs: function () {
    var attrs = this.parse(this.attributes);
    this.clear({silent: true});
    this.set('type', attrs.type, {silent: true}); // re-set type to avoid change:type event to trigger again
    this.set(attrs);
  },

  _typeDef: function (type) {
    type = type || this.get('type');
    return TYPE_TO_META_MAP[type];
  },

  _radiusInterval: function () {
    switch (this.get('distance')) {
      case 'meters':
        return {
          type: 'interval',
          min: 10,
          max: 10000
        };
      case 'kilometers':
      case 'miles':
        return {
          type: 'interval',
          min: 0.5,
          max: 100,
          step: 0.5
        };
      default:
        return {
          type: 'interval',
          min: 1,
          max: 100
        };
    }
  },

  _timeInterval: function () {
    switch (this.get('kind')) {
      case 'car':
        return {
          type: 'interval',
          min: 60,
          max: 14400,
          step: 10
        };
      case 'walk':
      default:
        return {
          type: 'interval',
          min: 60,
          max: 3600
        };
    }
  },

  _distanceLabel: function (distance) {
    switch (distance) {
      case 'meters':
        return _t('editor.layers.analysis-form.meters');
      case 'kilometers':
        return _t('editor.layers.analysis-form.kilometers');
      case 'miles':
        return _t('editor.layers.analysis-form.miles');
      default:
        return '';
    }
  }

});


text:
using System;

namespace GraphQL.Server.Sample.Repository
{
    public class Human : ICharacter
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int[] Friends { get; set; }
        public Episodes[] AppearsIn { get; set; }
        public string HomePlanet { get; set; }
        public DateTime BirthDate { get; set; }

        public Address Address { get; set; }
    }
}


text:
<!doctype html>
<meta charset=utf-8>
<meta name=timeout content=long>


text:
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>WriteWord</title>

WriteWord()

语法

Result = WriteWord(#File, Number)

概要

Write a word number (2 bytes) to a file.

参数

#File

The file to write to.

Number

The value to write.

返回值

Returns nonzero if the operation was successful and zero if it failed.

备注

Because of file buffering, this function may return successful even if there is not enough
space left on the output device for the write operation.
The file must be opened using a write-capable function (i.e. not with ReadFile()).

For an example see the CreateFile() function - with WriteWord() only a word variable is written, instead of a string.

参阅

ReadWord(), CreateFile(), OpenFile()

已支持操作系统
所有

<- WriteUnicodeCharacter() - File Index


text:
/**
 * RouteErrorBoundary
 */

import React, { useContext } from 'react';
import { useIntl } from 'react-intl';
import PropTypes from 'prop-types';
import { ErrorBoundary } from '@folio/stripes-components';
import events from '../../events';
import { getEventHandlers } from '../../handlerService';
import { ModulesContext } from '../../ModulesContext';
import { StripesContext } from '../../StripesContext';

const RouteErrorBoundary = ({ children, escapeRoute, moduleName, isSettings }) => {
  const intl = useIntl();
  let buttonLabelId;

  const modules = useContext(ModulesContext);
  const stripes = useContext(StripesContext);

  if (moduleName) {
    if (isSettings) {
      buttonLabelId = 'stripes-core.routeErrorBoundary.goToModuleSettingsHomeLabel';
    } else {
      buttonLabelId = 'stripes-core.routeErrorBoundary.goToModuleHomeLabel';
    }
  } else {
    buttonLabelId = 'stripes-core.routeErrorBoundary.goToAppHomeLabel';
  }

  const handleReset = () => {
    window.location.replace(escapeRoute);
  };

  /**
   * handleError
   * Callback from ErrorBoundary's componentDidCatch method. Pass along
   * the values received there to any functions that are registered to
   * listen to events.ERROR.
   */
  const handleError = (error, info) => {
    const handlers = getEventHandlers(events.ERROR, stripes, modules.handler, {});
    handlers.forEach(handleEvent => {
      handleEvent(error, info);
    });
  };

  return (
    <ErrorBoundary
      subTitle={intl.formatMessage({ id: 'stripes-core.routeErrorBoundary.sub' })}
      resetButtonLabel={intl.formatMessage({ id: buttonLabelId }, { name: moduleName })}
      onReset={handleReset}
      onError={handleError}
    >
      {children}
    </ErrorBoundary>
  );
};

RouteErrorBoundary.propTypes = {
  children: PropTypes.node,
  escapeRoute: PropTypes.string,
  moduleName: PropTypes.node,
  isSettings: PropTypes.bool,
};

RouteErrorBoundary.defaultProps = {
  escapeRoute: '/'
};

export default RouteErrorBoundary;


text:
package application;

import javafx.beans.property.SimpleStringProperty;

public class LogRow {
	private final SimpleStringProperty date;
	private final SimpleStringProperty doctorName;
	private final SimpleStringProperty doctorSpecialty;
	private final SimpleStringProperty doctorLocation;
	private final SimpleStringProperty outcome;

	public LogRow(String sDate, String sName, String sSpecialty, String sLocation, String sOutcome) {
		this.date = new SimpleStringProperty(sDate);
		this.doctorName = new SimpleStringProperty(sName);
		this.doctorSpecialty = new SimpleStringProperty(sSpecialty);
		this.doctorLocation = new SimpleStringProperty(sLocation);
		this.outcome = new SimpleStringProperty(sOutcome);
	}
	public String getDate() {
		return date.get();
	}
	public void setDate(String sDate) {
		date.set(sDate);
	}
	public String getDoctorName() {
		return doctorName.get();
	}
	public void setDoctorName(String sName) {
		doctorName.set(sName);
	}
	public String getDoctorSpecialty() {
		return doctorSpecialty.get();
	}
	public void setDoctorSpecialty(String sSpecialty) {
		doctorSpecialty.set(sSpecialty);
	}
	public String getDoctorLocation() {
		return doctorLocation.get();
	}
	public void setDoctorLocation(String sLocation) {
		doctorLocation.set(sLocation);
	}
	public String getOutcome() {
		return outcome.get();
	}
	public void setOutcome(String sOutcome) {
		outcome.set(sOutcome);
	}
}


text:
enum foo { alpha, beta(int) }

fn main() {
    match alpha {
      alpha | beta(i) => {} //~ ERROR variable `i` from pattern #2 is not bound in pattern #1
    }
}