text:
@implementation AnnotateViewController
@synthesize filteredListContent;
@synthesize sections;
@synthesize dataArray=_dataArray;
@synthesize noteTableView;

#pragma mark -
#pragma mark User Loading  methods

-(void)viewDidAppear:(BOOL)animated
{
    noteSearchBar.text = @"";

    [self getDataForAnnotateTable];
}

- (void)viewDidLoad
{
    self.filteredListContent = [[NSMutableArray alloc] init];
    self.sections = [[NSMutableDictionary alloc] init];
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(filterContentforText) name:UITextFieldTextDidChangeNotification object:nil];
    // text Font/Color Setting
    UIFont* myFont = FONT_TAHOMA_REGULAR(13);
    [titleLabel setFont:myFont];
    titleLabel.textColor = kColor(255, 154, 4, 1);
    noteTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

-(NSUInteger)supportedInterfaceOrientations
{
    return 0;
}
- (BOOL)shouldAutorotate
{
     [self getDataForAnnotateTable];
    return NO;
}

#pragma mark -
#pragma mark User Define  methods

- (void)getDataForAnnotateTable
{
    [self.filteredListContent removeAllObjects];
    DatabaseConnection* dbCon = [DatabaseConnection sharedConnection];
    _dataArray=[dbCon SelectHighlightObjectDetail:[NSString stringWithFormat:@"Select * from HIGHLIGHTOBJECT"]];
    self.filteredListContent = [[dbCon SelectHighlightObjectDetail:[NSString stringWithFormat:@"Select * from HIGHLIGHTOBJECT"]] mutableCopy];
    [self setDataForPlay];
    [self checkStatusOfInfoLabel];
    [noteTableView reloadData];
}

- (void)checkStatusOfInfoLabel
{
    if ([self.filteredListContent count]==0)
        infoLabel.hidden=FALSE;
    else
        infoLabel.hidden=TRUE;
}

- (void)setDataForPlay
{
    self.sections = [[NSMutableDictionary alloc] init];
    BOOL found;
    // Loop through the Play and create our keys
    for (HighlightObject *hghObj in self.filteredListContent)
    {
        NSString *c = [hghObj.playTitle substringToIndex:1];
        found = NO;
        for (NSString *str in [self.sections allKeys])
        {
            if ([str isEqualToString:c])
                found = YES;
        }
        if (!found)
            [self.sections setValue:[[NSMutableArray alloc] init] forKey:c];
    }
    // Loop again and sort the Play into their respective keys
    for (HighlightObject *hghObj in self.filteredListContent)
        [[self.sections objectForKey:[hghObj.playTitle substringToIndex:1]] addObject:hghObj];
    // Sort each section array
    for (NSString *key in [self.sections allKeys])
        [[self.sections objectForKey:key] sortUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"playTitle" ascending:YES]]];
}

- (void)filterContentforText
{
    NSString* string = noteSearchBar.text;
    [self.filteredListContent removeAllObjects]; // First clear the filtered array.
    for (HighlightObject *product in _dataArray)
    {
        NSComparisonResult result = [product.playTitle compare:string options:(NSCaseInsensitiveSearch) range:NSMakeRange(0, string.length)];
        if (result == NSOrderedSame)
            [self.filteredListContent addObject:product];
    }
    [self setDataForPlay];
    [noteTableView reloadData];
    [self checkStatusOfInfoLabel];
}

#pragma mark -
#pragma mark UIButton Event methods

- (IBAction)Back_Clicked:(id)sender
{
    AppDelegate* delegate=[UIApplication sharedApplication].delegate;
    [delegate.nyplMenuViewController showRequiredController:RootTabSelected];
    delegate.nyplMenuViewController.hidden=NO;
    noteSearchBar.text=@"";
}

#pragma mark -
#pragma mark UITableView Datasource methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section]] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellIdentifier = nil;
    cellIdentifier = [NSString stringWithFormat:@"cell%d%d",indexPath.row,indexPath.section];
    PlayCustomCell *cell = (PlayCustomCell*)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil)
    {
        UIViewController* viewController = [[UIViewController alloc] initWithNibName:@"PlayCustomCell" bundle:nil];
        cell = (PlayCustomCell*)viewController.view;
        viewController = nil;
    }
    HighlightObject *hghObj = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]
                                                           objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];

    UIFont* myFont=FONT_TAHOMA_BOLD(15);
    [cell.titleLable setFont:myFont];
    cell.titleLable.textColor = kColor(154, 4, 4, 1);

    myFont=FONT_TAHOMA_REGULAR(13);
    [cell.authorLabel setFont:myFont];
    cell.authorLabel.textColor = kColor(41, 42, 42, 1);

    cell.titleLable.text = hghObj.playTitle;
    cell.authorLabel.text = hghObj.playAuthorName;

    cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero] ;
    cell.selectedBackgroundView.backgroundColor = kColor(106, 5, 5, 1);
    return cell;
}

#pragma mark -
#pragma mark UITableView Delegate methods

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIImage *image = [UIImage imageNamed:@"bar_red.png"];
    UIImageView *imageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, image.size.width, image.size.height)];
    imageview.image = image;
    UILabel *labelTitle = [[UILabel alloc] initWithFrame:CGRectMake(imageview.frame.size.width-20, image.size.height/2-11, 20, 20)];
    labelTitle.text = [[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
    UIFont* myfont=FONT_TAHOMA_BOLD(13);
    [labelTitle setFont:myfont];
    [imageview addSubview:labelTitle];
    labelTitle.backgroundColor = [UIColor clearColor];
    labelTitle.textColor = kColor(255, 154, 4, 1);
    return imageview;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [[self.sections allKeys] count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return [[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)] objectAtIndex:section];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    [noteSearchBar resignFirstResponder];
    MainWebControllerViewController* mainWebControllerViewController=[[MainWebControllerViewController alloc] initWithNibName:@"MainWebControllerViewController" bundle:nil];
    HighlightObject *hghObj = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]
                                                           objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
    currentIndex=hghObj.versionNo;
    mainWebControllerViewController.playID=hghObj.playId;
    [mainWebControllerViewController.baseScrollView manageViewOnMove:((HighlightObject*)[self.filteredListContent objectAtIndex:indexPath.section]).versionNo];
    [self.navigationController pushViewController:mainWebControllerViewController animated:YES];
    noteSearchBar.text=@"";
}

#pragma mark -
#pragma mark UITextfield Delegate methods

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self checkStatusOfInfoLabel];
}

@end


text:
package org.apache.jackrabbit.oak.plugins.metric;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Counting;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import org.apache.jackrabbit.oak.stats.CounterStats;
import org.apache.jackrabbit.oak.stats.HistogramStats;
import org.apache.jackrabbit.oak.stats.MeterStats;
import org.apache.jackrabbit.oak.stats.SimpleStats;
import org.apache.jackrabbit.oak.stats.TimerStats;

/**
 * Stats instances which delegates to both TimeSeries based counter
 * and Metrics based meters so as to allow both systems to collect
 * stats
 */
final class CompositeStats implements CounterStats, MeterStats, TimerStats, HistogramStats {
    private final AtomicLong delegate;
    private final Counter counter;
    private final Timer timer;
    private final Meter meter;
    private final Histogram histogram;
    private final Counting counting;

    public CompositeStats(AtomicLong delegate, Counter counter) {
        this(delegate, counter, null, null, null, counter);
    }

    public CompositeStats(AtomicLong delegate, Timer timer) {
        this(delegate, null, timer, null, null, timer);
    }

    public CompositeStats(AtomicLong delegate, Meter meter) {
        this(delegate, null, null, meter, null, meter);
    }

    public CompositeStats(AtomicLong delegate, Histogram histogram) {
        this(delegate, null, null, null, histogram, histogram);
    }

    private CompositeStats(AtomicLong delegate, Counter counter,
                           Timer timer, Meter meter, Histogram histogram, Counting counting) {
        this.delegate = delegate;
        this.counter = counter;
        this.timer = timer;
        this.meter = meter;
        this.histogram = histogram;
        this.counting = counting;
    }

    @Override
    public long getCount() {
        return counting.getCount();
    }

    @Override
    public void inc() {
        delegate.getAndIncrement();
        counter.inc();
    }

    @Override
    public void dec() {
        delegate.getAndDecrement();
        counter.dec();
    }

    @Override
    public void inc(long n) {
        delegate.getAndAdd(n);
        counter.inc(n);
    }

    @Override
    public void dec(long n) {
        delegate.getAndAdd(-n);
        counter.dec(n);
    }

    @Override
    public void mark() {
        delegate.getAndIncrement();
        meter.mark();
    }

    @Override
    public void mark(long n) {
        delegate.getAndAdd(n);
        meter.mark(n);
    }

    @Override
    public void update(long duration, TimeUnit unit) {
        delegate.getAndAdd(unit.toMillis(duration));
        timer.update(duration, unit);
    }

    @Override
    public void update(long value) {
        delegate.getAndAdd(value);
        histogram.update(value);
    }

    @Override
    public Context time() {
        return new StatsContext(timer.time(), delegate);
    }

    boolean isMeter() {
        return meter != null;
    }

    boolean isTimer() {
        return timer != null;
    }

    boolean isCounter() {
        return counter != null;
    }

    boolean isHistogram(){
        return histogram != null;
    }

    Counter getCounter() {
        return counter;
    }

    Timer getTimer() {
        return timer;
    }

    Meter getMeter() {
        return meter;
    }

    Histogram getHistogram(){
        return histogram;
    }

    private static final class StatsContext implements Context {
        private final Timer.Context context ;
        private final AtomicLong delegate;

        private StatsContext(Timer.Context context, AtomicLong delegate) {
            this.context = context;
            this.delegate = delegate;
        }

        public long stop() {
            long nanos = context.stop();
            delegate.getAndAdd(TimeUnit.NANOSECONDS.toMillis(nanos));
            return nanos;
        }

        /** Equivalent to calling {@link #stop()}. */
        @Override
        public void close() {
            stop();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.midori.confluence.plugin.mail2news;

import org.apache.log4j.Logger;

import com.atlassian.bandana.BandanaContext;
import com.atlassian.bandana.BandanaManager;
import com.atlassian.confluence.setup.bandana.ConfluenceBandanaContext;
import com.atlassian.spring.container.ContainerManager;
import com.thoughtworks.xstream.XStream;

public class ConfigurationManager {

    /**
     * The bandana key for the configuration of this plugin.
     */
    private static final String BANDANA_KEY = "com.midori.confluence.plugin.mail2news.mail2news.ConfigurationManager";

    /**
     * The bandana context to access the configuration of this plugin.
     */
    private static final BandanaContext bandanaContext = new ConfluenceBandanaContext();

    /**
     * The bandana manager of this confluence instance,
     * used for storing the settings of this plugin.
     */
    private BandanaManager bandanaManager;

    /**
     * The XStream object used for serialisation.
     */
    private XStream xStream;

    /**
     * The configuration object which holds the configuration of this plugin.
     */
    private MailConfiguration mailConfiguration = null;

    /**
     * The log to which we will be logging infos and errors.
     */
    protected final Logger log = Logger.getLogger(this.getClass());

    public ConfigurationManager()
    {
        ContainerManager.autowireComponent(this);
        loadConfig();
    }

    /**
     * This method is automatically called by Confluence to pass the
     * bandana manager of this confluence instance.
     *
     * @param bandanaManager The bandana manager of this confluence manager
     */
    public void setBandanaManager(BandanaManager bandanaManager) {
        this.bandanaManager = bandanaManager;
    }

    /**
     * This method deserializes the configuration object using
     * bandana.
     */
    public void loadConfig() {
        log.info("Loading configuration.");
        try {
            /* check that the bandana manager exists */
            if (this.bandanaManager == null)
            {
                throw new Exception("No bandana manager set.");
            }

            /* get the serialised configuration object */
            Object data = bandanaManager.getValue( bandanaContext, BANDANA_KEY );
            /* check cast and deserialise */
            if (data instanceof String) {
                try {
                    /* Workaround: have to create a new xStream before deserialising */
                    xStream = new XStream();
                    xStream.setClassLoader(getClass().getClassLoader());
                    Object deserialisedData = xStream.fromXML((String)data);
                    if (deserialisedData instanceof MailConfiguration) {
                        mailConfiguration = (MailConfiguration) deserialisedData;
                    }
                } catch (Exception e) {
                    this.log.error("Could not deserialise configuration.", e);
                    /* force the creation of a dummy configuration */
                    mailConfiguration = null;
                }
            }
            /* check if we could load the configuration */
            if (mailConfiguration == null) {
                /* initialise a default configuration */
                mailConfiguration = new MailConfiguration();
            }

        } catch (Exception e) {
            this.log.error("Could not load configuration.", e);
        }
    }

    /**
     * Save the configuration by saving the mailConfiguration object
     * using bandana.
     */
    public void saveConfig() {
        log.info("Saving configuration.");
        try {
            if (mailConfiguration == null)
            {
                log.error("Mail configuration is null, saving dummy configuration.");
                loadConfig();
            }
            /* Workaround: have to create a new xstream before serialising */
            xStream = new XStream();
            xStream.setClassLoader(getClass().getClassLoader());
            bandanaManager.setValue( bandanaContext, BANDANA_KEY, xStream.toXML(mailConfiguration) );

        } catch (Exception e) {
            this.log.error("Could not save configuration.", e);
        } finally {
            this.loadConfig();
        }
    }

    /**
     * Get the mail configuration of this manager
     *
     * @return Returns the mail configuration of this manager
     */
    public MailConfiguration getMailConfiguration()
    {
        return this.mailConfiguration;
    }

    /**
     * Set the mail configuration of this manager.
     * NOTE: This does not yet save the configuration, call saveConfig()
     *       for this.
     *
     * @param mailConfiguration The mail configuration to set.
     */
    public void setMailConfiguration(MailConfiguration mailConfiguration)
    {
        log.info("Setting configuration: " + mailConfiguration.toString());
        this.mailConfiguration = mailConfiguration;
    }
}


text:
import alvision_module from "../bindings";

import * as _mat from './mat'
import * as _matx from './Matx'
//import * as _st from './Constants'
import * as _st from './static'
import * as _types from './types'
import * as _core from './core'
import * as _base from './base'
//import * as _vec from './Vec'
//import * as _point from './Point'
//import * as _algorithm from './Algorithm'
//import * as _size from './Size'
//import * as _scalar from './Scalar'

//#ifndef _OPENCV_FLANN_HPP_
//#define _OPENCV_FLANN_HPP_
//
//#include "opencv2/core.hpp"
//#include "opencv2/flann/miniflann.hpp"
//#include "opencv2/flann/flann_base.hpp"

/**
@defgroup flann Clustering and Search in Multi-Dimensional Spaces

This section documents OpenCV's interface to the FLANN library. FLANN (Fast Library for Approximate
Nearest Neighbors) is a library that contains a collection of algorithms optimized for fast nearest
neighbor search in large datasets and for high dimensional features. More information about FLANN
can be found in @cite Muja2009 .
*/

//namespace cvflann
//{
//    CV_EXPORTS flann_distance_t flann_distance_type();
//    FLANN_DEPRECATED CV_EXPORTS void set_distance_type(flann_distance_t distance_type, int order);
//}

//namespace cv
//{
export module flann
{

//! @addtogroup flann
//! @{

//template <typename T> struct CvType {};
//template <> struct CvType<unsigned char> { static int type() { return CV_8U; } };
//template <> struct CvType<char> { static int type() { return CV_8S; } };
//template <> struct CvType<unsigned short> { static int type() { return CV_16U; } };
//template <> struct CvType<short> { static int type() { return CV_16S; } };
//template <> struct CvType<int> { static int type() { return CV_32S; } };
//template <> struct CvType<float> { static int type() { return CV_32F; } };
//template <> struct CvType<double> { static int type() { return CV_64F; } };

// bring the flann parameters into this namespace
//using ::cvflann::get_param;
//using ::cvflann::print_params;
//
//// bring the flann distances into this namespace
//using ::cvflann::L2_Simple;
//using ::cvflann::L2;
//using ::cvflann::L1;
//using ::cvflann::MinkowskiDistance;
//using ::cvflann::MaxDistance;
//using ::cvflann::HammingLUT;
//using ::cvflann::Hamming;
//using ::cvflann::Hamming2;
//using ::cvflann::HistIntersectionDistance;
//using ::cvflann::HellingerDistance;
//using ::cvflann::ChiSquareDistance;
//using ::cvflann::KL_Divergence;

/** @brief The FLANN nearest neighbor index class. This class is templated with the type of elements for which
the index is built.
 */
//template <typename Distance>
    //        - **KDTreeIndexParams** When passing an object of this type the index constructed will consist of
    //        a set of randomized kd-trees which will be searched in parallel. :
    //        @code
//    class KDTreeIndexParams extends IndexParams {
//        protected trees: _st.int = 4;
//        constructor() {
//            super();
//        };//(int trees = 4 );
//    };
//        @endcode

export class GenericIndex
{
//public:
//        typedef typename Distance::ElementType ElementType;
//        typedef typename Distance::ResultType DistanceType;
//
//        /** @brief Constructs a nearest neighbor search index for a given dataset.
//
//        @param features Matrix of containing the features(points) to index. The size of the matrix is
//        num_features x feature_dimensionality and the data type of the elements in the matrix must
//        coincide with the type of the index.
//        @param params Structure containing the index parameters. The type of index that will be
//        constructed depends on the type of this parameter. See the description.
//        @param distance
//
//        The method constructs a fast search structure from a set of features using the specified algorithm
//        with specified parameters, as defined by params. params is a reference to one of the following class
//        IndexParams descendants:
//
//        - **LinearIndexParams** When passing an object of this type, the index will perform a linear,
//        brute-force search. :
//        @code
//        struct LinearIndexParams : public IndexParams
//        {
//        };
//        @endcode

//        - **KMeansIndexParams** When passing an object of this type the index constructed will be a
//        hierarchical k-means tree. :
//        @code
//        struct KMeansIndexParams : public IndexParams
//        {
//            KMeansIndexParams(
//                int branching = 32,
//                int iterations = 11,
//                flann_centers_init_t centers_init = CENTERS_RANDOM,
//                float cb_index = 0.2 );
//        };
//        @endcode
//        - **CompositeIndexParams** When using a parameters object of this type the index created
//        combines the randomized kd-trees and the hierarchical k-means tree. :
//        @code
//        struct CompositeIndexParams : public IndexParams
//        {
//            CompositeIndexParams(
//                int trees = 4,
//                int branching = 32,
//                int iterations = 11,
//                flann_centers_init_t centers_init = CENTERS_RANDOM,
//                float cb_index = 0.2 );
//        };
//        @endcode
//        - **LshIndexParams** When using a parameters object of this type the index created uses
//        multi-probe LSH (by Multi-Probe LSH: Efficient Indexing for High-Dimensional Similarity Search
//        by Qin Lv, William Josephson, Zhe Wang, Moses Charikar, Kai Li., Proceedings of the 33rd
//        International Conference on Very Large Data Bases (VLDB). Vienna, Austria. September 2007) :
//        @code
//        struct LshIndexParams : public IndexParams
//        {
//            LshIndexParams(
//                unsigned int table_number,
//                unsigned int key_size,
//                unsigned int multi_probe_level );
//        };
//        @endcode
//        - **AutotunedIndexParams** When passing an object of this type the index created is
//        automatically tuned to offer the best performance, by choosing the optimal index type
//        (randomized kd-trees, hierarchical kmeans, linear) and parameters for the dataset provided. :
//        @code
//        struct AutotunedIndexParams : public IndexParams
//        {
//            AutotunedIndexParams(
//                float target_precision = 0.9,
//                float build_weight = 0.01,
//                float memory_weight = 0,
//                float sample_fraction = 0.1 );
//        };
//        @endcode
//        - **SavedIndexParams** This object type is used for loading a previously saved index from the
//        disk. :
//        @code
//        struct SavedIndexParams : public IndexParams
//        {
//            SavedIndexParams( String filename );
//        };
//        @endcode
//         */
//        GenericIndex(const Mat& features, const ::cvflann::IndexParams& params, Distance distance = Distance());
//
//        ~GenericIndex();
//
//        /** @brief Performs a K-nearest neighbor search for a given query point using the index.
//
//        @param query The query point
//        @param indices Vector that will contain the indices of the K-nearest neighbors found. It must have
//        at least knn size.
//        @param dists Vector that will contain the distances to the K-nearest neighbors found. It must have
//        at least knn size.
//        @param knn Number of nearest neighbors to search for.
//        @param params SearchParams
//         */
//        void knnSearch(const std::vector<ElementType>& query, std::vector<int>& indices,
//                       std::vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& params);
//        void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params);
//
//        int radiusSearch(const std::vector<ElementType>& query, std::vector<int>& indices,
//                         std::vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& params);
//        int radiusSearch(const Mat& query, Mat& indices, Mat& dists,
//                         DistanceType radius, const ::cvflann::SearchParams& params);
//
//        void save(String filename) { nnIndex->save(filename); }
//
//        int veclen() const { return nnIndex->veclen(); }
//
//        int size() const { return nnIndex->size(); }
//
//        ::cvflann::IndexParams getParameters() { return nnIndex->getParameters(); }
//
//        FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters() { return nnIndex->getIndexParameters(); }
//
//private:
//        ::cvflann::Index<Distance>* nnIndex;
};

//! @cond IGNORED

//#define FLANN_DISTANCE_CHECK \
//    if ( ::cvflann::flann_distance_type() != cvflann::FLANN_DIST_L2) { \
//        printf("[WARNING] You are using cv::flann::Index (or cv::flann::GenericIndex) and have also changed "\
//        "the distance using cvflann::set_distance_type. This is no longer working as expected "\
//        "(cv::flann::Index always uses L2). You should create the index templated on the distance, "\
//        "for example for L1 distance use: GenericIndex< L1<float> > \n"); \
//    }

//
//template <typename Distance>
//GenericIndex<Distance>::GenericIndex(const Mat& dataset, const ::cvflann::IndexParams& params, Distance distance)
//{
//    CV_Assert(dataset.type() == CvType<ElementType>::type());
//    CV_Assert(dataset.isContinuous());
//    ::cvflann::Matrix<ElementType> m_dataset((ElementType*)dataset.ptr<ElementType>(0), dataset.rows, dataset.cols);
//
//    nnIndex = new ::cvflann::Index<Distance>(m_dataset, params, distance);
//
//    FLANN_DISTANCE_CHECK
//
//    nnIndex->buildIndex();
//}
//
//template <typename Distance>
//GenericIndex<Distance>::~GenericIndex()
//{
//    delete nnIndex;
//}
//
//template <typename Distance>
//void GenericIndex<Distance>::knnSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& searchParams)
//{
//    ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
//    ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
//    ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
//
//    FLANN_DISTANCE_CHECK
//
//    nnIndex->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
//}
//
//
//template <typename Distance>
//void GenericIndex<Distance>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams)
//{
//    CV_Assert(queries.type() == CvType<ElementType>::type());
//    CV_Assert(queries.isContinuous());
//    ::cvflann::Matrix<ElementType> m_queries((ElementType*)queries.ptr<ElementType>(0), queries.rows, queries.cols);
//
//    CV_Assert(indices.type() == CV_32S);
//    CV_Assert(indices.isContinuous());
//    ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
//
//    CV_Assert(dists.type() == CvType<DistanceType>::type());
//    CV_Assert(dists.isContinuous());
//    ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
//
//    FLANN_DISTANCE_CHECK
//
//    nnIndex->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
//}
//
//template <typename Distance>
//int GenericIndex<Distance>::radiusSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
//{
//    ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
//    ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
//    ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
//
//    FLANN_DISTANCE_CHECK
//
//    return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
//}
//
//template <typename Distance>
//int GenericIndex<Distance>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
//{
//    CV_Assert(query.type() == CvType<ElementType>::type());
//    CV_Assert(query.isContinuous());
//    ::cvflann::Matrix<ElementType> m_query((ElementType*)query.ptr<ElementType>(0), query.rows, query.cols);
//
//    CV_Assert(indices.type() == CV_32S);
//    CV_Assert(indices.isContinuous());
//    ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
//
//    CV_Assert(dists.type() == CvType<DistanceType>::type());
//    CV_Assert(dists.isContinuous());
//    ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
//
//    FLANN_DISTANCE_CHECK
//
//    return nnIndex->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
//}

//! @endcond

/**
 * @deprecated Use GenericIndex class instead
 */
//template <typename T>
class
//#ifndef _MSC_VER
// FLANN_DEPRECATED
//#endif
 Index_ {
//public:
//        typedef typename L2<T>::ElementType ElementType;
//        typedef typename L2<T>::ResultType DistanceType;
//
//    Index_(const Mat& features, const ::cvflann::IndexParams& params);
//
//    ~Index_();
//
//    void knnSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& params);
//    void knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& params);
//
//    int radiusSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& params);
//    int radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& params);
//
//    void save(String filename)
//        {
//            if (nnIndex_L1) nnIndex_L1->save(filename);
//            if (nnIndex_L2) nnIndex_L2->save(filename);
//        }
//
//    int veclen() const
//    {
//            if (nnIndex_L1) return nnIndex_L1->veclen();
//            if (nnIndex_L2) return nnIndex_L2->veclen();
//        }
//
//    int size() const
//    {
//            if (nnIndex_L1) return nnIndex_L1->size();
//            if (nnIndex_L2) return nnIndex_L2->size();
//        }
//
//        ::cvflann::IndexParams getParameters()
//        {
//            if (nnIndex_L1) return nnIndex_L1->getParameters();
//            if (nnIndex_L2) return nnIndex_L2->getParameters();
//
//        }
//
//        FLANN_DEPRECATED const ::cvflann::IndexParams* getIndexParameters()
//        {
//            if (nnIndex_L1) return nnIndex_L1->getIndexParameters();
//            if (nnIndex_L2) return nnIndex_L2->getIndexParameters();
//        }
//
//private:
//        // providing backwards compatibility for L2 and L1 distances (most common)
//        ::cvflann::Index< L2<ElementType> >* nnIndex_L2;
//        ::cvflann::Index< L1<ElementType> >* nnIndex_L1;
};

//#ifdef _MSC_VER
//template <typename T>
//class FLANN_DEPRECATED Index_;
//#endif

//! @cond IGNORED

//template <typename T>
//Index_<T>::Index_(const Mat& dataset, const ::cvflann::IndexParams& params)
//{
//    printf("[WARNING] The cv::flann::Index_<T> class is deperecated, use cv::flann::GenericIndex<Distance> instead\n");
//
//    CV_Assert(dataset.type() == CvType<ElementType>::type());
//    CV_Assert(dataset.isContinuous());
//    ::cvflann::Matrix<ElementType> m_dataset((ElementType*)dataset.ptr<ElementType>(0), dataset.rows, dataset.cols);
//
//    if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) {
//        nnIndex_L1 = NULL;
//        nnIndex_L2 = new ::cvflann::Index< L2<ElementType> >(m_dataset, params);
//    }
//    else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) {
//        nnIndex_L1 = new ::cvflann::Index< L1<ElementType> >(m_dataset, params);
//        nnIndex_L2 = NULL;
//    }
//    else {
//        printf("[ERROR] cv::flann::Index_<T> only provides backwards compatibility for the L1 and L2 distances. "
//        "For other distance types you must use cv::flann::GenericIndex<Distance>\n");
//        CV_Assert(0);
//    }
//    if (nnIndex_L1) nnIndex_L1->buildIndex();
//    if (nnIndex_L2) nnIndex_L2->buildIndex();
//}
//
//template <typename T>
//Index_<T>::~Index_()
//{
//    if (nnIndex_L1) delete nnIndex_L1;
//    if (nnIndex_L2) delete nnIndex_L2;
//}
//
//template <typename T>
//void Index_<T>::knnSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, int knn, const ::cvflann::SearchParams& searchParams)
//{
//    ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
//    ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
//    ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
//
//    if (nnIndex_L1) nnIndex_L1->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
//    if (nnIndex_L2) nnIndex_L2->knnSearch(m_query,m_indices,m_dists,knn,searchParams);
//}
//
//
//template <typename T>
//void Index_<T>::knnSearch(const Mat& queries, Mat& indices, Mat& dists, int knn, const ::cvflann::SearchParams& searchParams)
//{
//    CV_Assert(queries.type() == CvType<ElementType>::type());
//    CV_Assert(queries.isContinuous());
//    ::cvflann::Matrix<ElementType> m_queries((ElementType*)queries.ptr<ElementType>(0), queries.rows, queries.cols);
//
//    CV_Assert(indices.type() == CV_32S);
//    CV_Assert(indices.isContinuous());
//    ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
//
//    CV_Assert(dists.type() == CvType<DistanceType>::type());
//    CV_Assert(dists.isContinuous());
//    ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
//
//    if (nnIndex_L1) nnIndex_L1->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
//    if (nnIndex_L2) nnIndex_L2->knnSearch(m_queries,m_indices,m_dists,knn, searchParams);
//}
//
//template <typename T>
//int Index_<T>::radiusSearch(const std::vector<ElementType>& query, std::vector<int>& indices, std::vector<DistanceType>& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
//{
//    ::cvflann::Matrix<ElementType> m_query((ElementType*)&query[0], 1, query.size());
//    ::cvflann::Matrix<int> m_indices(&indices[0], 1, indices.size());
//    ::cvflann::Matrix<DistanceType> m_dists(&dists[0], 1, dists.size());
//
//    if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
//    if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
//}
//
//template <typename T>
//int Index_<T>::radiusSearch(const Mat& query, Mat& indices, Mat& dists, DistanceType radius, const ::cvflann::SearchParams& searchParams)
//{
//    CV_Assert(query.type() == CvType<ElementType>::type());
//    CV_Assert(query.isContinuous());
//    ::cvflann::Matrix<ElementType> m_query((ElementType*)query.ptr<ElementType>(0), query.rows, query.cols);
//
//    CV_Assert(indices.type() == CV_32S);
//    CV_Assert(indices.isContinuous());
//    ::cvflann::Matrix<int> m_indices((int*)indices.ptr<int>(0), indices.rows, indices.cols);
//
//    CV_Assert(dists.type() == CvType<DistanceType>::type());
//    CV_Assert(dists.isContinuous());
//    ::cvflann::Matrix<DistanceType> m_dists((DistanceType*)dists.ptr<DistanceType>(0), dists.rows, dists.cols);
//
//    if (nnIndex_L1) return nnIndex_L1->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
//    if (nnIndex_L2) return nnIndex_L2->radiusSearch(m_query,m_indices,m_dists,radius,searchParams);
//}

//! @endcond

/** @brief Clusters features using hierarchical k-means algorithm.

@param features The points to be clustered. The matrix must have elements of type
Distance::ElementType.
@param centers The centers of the clusters obtained. The matrix must have type
Distance::ResultType. The number of rows in this matrix represents the number of clusters desired,
however, because of the way the cut in the hierarchical tree is chosen, the number of clusters
computed will be the highest number of the form (branching-1)\*k+1 that's lower than the number of
clusters desired, where branching is the tree's branching factor (see description of the
KMeansIndexParams).
@param params Parameters used in the construction of the hierarchical k-means tree.
@param d Distance to be used for clustering.

The method clusters the given feature vectors by constructing a hierarchical k-means tree and
choosing a cut in the tree that minimizes the cluster's variance. It returns the number of clusters
found.
 */
//template <typename Distance>
//int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params,
//                           Distance d = Distance())
//{
//    typedef typename Distance::ElementType ElementType;
//    typedef typename Distance::ResultType DistanceType;
//
//    CV_Assert(features.type() == CvType<ElementType>::type());
//    CV_Assert(features.isContinuous());
//    ::cvflann::Matrix<ElementType> m_features((ElementType*)features.ptr<ElementType>(0), features.rows, features.cols);
//
//    CV_Assert(centers.type() == CvType<DistanceType>::type());
//    CV_Assert(centers.isContinuous());
//    ::cvflann::Matrix<DistanceType> m_centers((DistanceType*)centers.ptr<DistanceType>(0), centers.rows, centers.cols);
//
//    return ::cvflann::hierarchicalClustering<Distance>(m_features, m_centers, params, d);
//}

/** @deprecated
*/
//template <typename ELEM_TYPE, typename DIST_TYPE>
//FLANN_DEPRECATED int hierarchicalClustering(const Mat& features, Mat& centers, const ::cvflann::KMeansIndexParams& params)
//{
//    printf("[WARNING] cv::flann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE> is deprecated, use "
//        "cv::flann::hierarchicalClustering<Distance> instead\n");
//
//    if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L2 ) {
//        return hierarchicalClustering< L2<ELEM_TYPE> >(features, centers, params);
//    }
//    else if ( ::cvflann::flann_distance_type() == cvflann::FLANN_DIST_L1 ) {
//        return hierarchicalClustering< L1<ELEM_TYPE> >(features, centers, params);
//    }
//    else {
//        printf("[ERROR] cv::flann::hierarchicalClustering<ELEM_TYPE,DIST_TYPE> only provides backwards "
//        "compatibility for the L1 and L2 distances. "
//        "For other distance types you must use cv::flann::hierarchicalClustering<Distance>\n");
//        CV_Assert(0);
//    }
//}

//! @} flann

export enum flann_algorithm {
    FLANN_INDEX_LINEAR = 0,
    FLANN_INDEX_KDTREE = 1,
    FLANN_INDEX_KMEANS = 2,
    FLANN_INDEX_COMPOSITE = 3,
    FLANN_INDEX_KDTREE_SINGLE = 4,
    FLANN_INDEX_HIERARCHICAL = 5,
    FLANN_INDEX_LSH = 6,
    FLANN_INDEX_SAVED = 254,
    FLANN_INDEX_AUTOTUNED = 255,

    // deprecated constants, should use the FLANN_INDEX_* ones instead
    LINEAR = 0,
    KDTREE = 1,
    KMEANS = 2,
    COMPOSITE = 3,
    KDTREE_SINGLE = 4,
    SAVED = 254,
    AUTOTUNED = 255
};

enum flann_centers_init {
    FLANN_CENTERS_RANDOM = 0,
    FLANN_CENTERS_GONZALES = 1,
    FLANN_CENTERS_KMEANSPP = 2,
    FLANN_CENTERS_GROUPWISE = 3,

    // deprecated constants, should use the FLANN_CENTERS_* ones instead
    CENTERS_RANDOM = 0,
    CENTERS_GONZALES = 1,
    CENTERS_KMEANSPP = 2
};

enum flann_distance {
    FLANN_DIST_EUCLIDEAN = 1,
    FLANN_DIST_L2 = 1,
    FLANN_DIST_MANHATTAN = 2,
    FLANN_DIST_L1 = 2,
    FLANN_DIST_MINKOWSKI = 3,
    FLANN_DIST_MAX = 4,
    FLANN_DIST_HIST_INTERSECT = 5,
    FLANN_DIST_HELLINGER = 6,
    FLANN_DIST_CHI_SQUARE = 7,
    FLANN_DIST_CS = 7,
    FLANN_DIST_KULLBACK_LEIBLER = 8,
    FLANN_DIST_KL = 8,
    FLANN_DIST_HAMMING = 9,

    // deprecated constants, should use the FLANN_DIST_* ones instead
    EUCLIDEAN = 1,
    MANHATTAN = 2,
    MINKOWSKI = 3,
    MAX_DIST = 4,
    HIST_INTERSECT = 5,
    HELLINGER = 6,
    CS = 7,
    KL = 8,
    KULLBACK_LEIBLER = 8
};

//
export class IndexParams {
    public params: { [key: string]: any; } = {};
    //    IndexParams();
    //    ~IndexParams();
    //
    //    String getString(const String& key, const String& defaultVal=String()) const;
    //    int getInt(const String& key, int defaultVal=-1) const;
    //    double getDouble(const String& key, double defaultVal=-1) const;
    //
    //    void setString(const String& key, const String& value);
    //    void setInt(const String& key, int value);
    //    void setDouble(const String& key, double value);
    //    void setFloat(const String& key, float value);
    //    void setBool(const String& key, bool value);
    //    void setAlgorithm(int value);
    //
    //    void getAll(std::vector<String>& names,
    //                std::vector<int>& types,
    //                std::vector<String>& strValues,
    //                std::vector<double>& numValues) const;
    //
    //    void* params;
};

export class KDTreeIndexParams extends IndexParams {

    constructor(trees: _st.int = 4) {
        super();
        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_KDTREE;
        this.params["trees"] = trees;
    }
}

export class LinearIndexParams extends IndexParams {
    constructor() {
        super();
        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_LINEAR;
    }
};

export class CompositeIndexParams extends IndexParams {
    constructor(trees: _st.int = 4, branching: _st.int = 32, iterations: _st.int = 11,
        centers_init: flann_centers_init = flann_centers_init.FLANN_CENTERS_RANDOM, cb_index: _st.float = 0.2) {
        super();
        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_KMEANS;
        // number of randomized trees to use (for kdtree)
        this.params["trees"] = trees;
        // branching factor
        this.params["branching"] = branching;
        // max iterations to perform in one kmeans clustering (kmeans tree)
        this.params["iterations"] = iterations;
        // algorithm used for picking the initial cluster centers for kmeans tree
        this.params["centers_init"] = centers_init;
        // cluster boundary index. Used when searching the kmeans tree
        this.params["cb_index"] = cb_index;
    }
};

export class AutotunedIndexParams extends IndexParams {
    constructor(target_precision: _st.float  = 0.8, build_weight: _st.float  = 0.01,
        memory_weight: _st.float  = 0, sample_fraction: _st.float  = 0.1) {
        super();
        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_AUTOTUNED;
        // precision desired (used for autotuning, -1 otherwise)
        this.params["target_precision"] = target_precision;
        // build tree time weighting factor
        this.params["build_weight"] = build_weight;
        // index memory weighting factor
        this.params["memory_weight"] = memory_weight;
        // what fraction of the dataset to use for autotuning
        this.params["sample_fraction"] = sample_fraction;

    }
};

export class HierarchicalClusteringIndexParams extends IndexParams {
    constructor(branching: _st.int = 32,
        centers_init: flann_centers_init /*= cvflann::FLANN_CENTERS_RANDOM*/, trees: _st.int /* = 4*/, leaf_size: _st.int /* = 100*/) {
        super();
        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_HIERARCHICAL;
        // The branching factor used in the hierarchical clustering
        this.params["branching"] = branching;
        // Algorithm used for picking the initial cluster centers
        this.params["centers_init"] = centers_init;
        // number of parallel trees to build
        this.params["trees"] = trees;
        // maximum leaf size
        this.params["leaf_size"] = leaf_size;
    }
};

export class KMeansIndexParams extends IndexParams {
    constructor(branching: _st.int  = 32, iterations: _st.int  = 11,
        centers_init: flann_centers_init   = flann_centers_init.FLANN_CENTERS_RANDOM, cb_index: _st.float  = 0.2) {
        super();
        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_KMEANS;
        // branching factor
        this.params["branching"] = branching;
        // max iterations to perform in one kmeans clustering (kmeans tree)
        this.params["iterations"] = iterations;
        // algorithm used for picking the initial cluster centers for kmeans tree
        this.params["centers_init"] = centers_init;
        // cluster boundary index. Used when searching the kmeans tree
        this.params["cb_index"] = cb_index;

    }
};

export class LshIndexParams extends IndexParams {
    constructor(table_number: _st.int, key_size: _st.int, multi_probe_level: _st.int) {
        super();

        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_LSH;
        // The number of hash tables to use
        this.params["table_number"] = table_number;
        // The length of the key in the hash tables
        this.params["key_size"] = key_size;
        // Number of levels to use in multi-probe (0 for standard LSH)
        this.params["multi_probe_level"] = multi_probe_level;
    }
};

export class SavedIndexParams extends IndexParams {
    constructor(filename: string) {
        super();

        this.params["algorithm"] = flann_algorithm.FLANN_INDEX_SAVED;
        this.params["filename"] = filename;
    }
};

export class SearchParams extends IndexParams {
    constructor(checks: _st.int = 32, eps: _st.float = 0, sorted: boolean = true) {
        super();
        // how many leafs to visit when searching for neighbours (-1 for unlimited)
        this.params["checks"] = checks;
        // search for eps-approximate neighbours (default: 0)
        this.params["eps"] = eps;
        // only for radius search, require neighbours sorted by distance (default: true)
        this.params["sorted"] = sorted;
    }
};

enum flann_distance_t {
    FLANN_DIST_EUCLIDEAN = 1,
    FLANN_DIST_L2 = 1,
    FLANN_DIST_MANHATTAN = 2,
    FLANN_DIST_L1 = 2,
    FLANN_DIST_MINKOWSKI = 3,
    FLANN_DIST_MAX = 4,
    FLANN_DIST_HIST_INTERSECT = 5,
    FLANN_DIST_HELLINGER = 6,
    FLANN_DIST_CHI_SQUARE = 7,
    FLANN_DIST_CS = 7,
    FLANN_DIST_KULLBACK_LEIBLER = 8,
    FLANN_DIST_KL = 8,
    FLANN_DIST_HAMMING = 9,

    // deprecated constants, should use the FLANN_DIST_* ones instead
    EUCLIDEAN = 1,
    MANHATTAN = 2,
    MINKOWSKI = 3,
    MAX_DIST = 4,
    HIST_INTERSECT = 5,
    HELLINGER = 6,
    CS = 7,
    KL = 8,
    KULLBACK_LEIBLER = 8
};

enum flann_algorithm_t {
    FLANN_INDEX_LINEAR = 0,
    FLANN_INDEX_KDTREE = 1,
    FLANN_INDEX_KMEANS = 2,
    FLANN_INDEX_COMPOSITE = 3,
    FLANN_INDEX_KDTREE_SINGLE = 4,
    FLANN_INDEX_HIERARCHICAL = 5,
    FLANN_INDEX_LSH = 6,
    FLANN_INDEX_SAVED = 254,
    FLANN_INDEX_AUTOTUNED = 255,

    // deprecated constants, should use the FLANN_INDEX_* ones instead
    LINEAR = 0,
    KDTREE = 1,
    KMEANS = 2,
    COMPOSITE = 3,
    KDTREE_SINGLE = 4,
    SAVED = 254,
    AUTOTUNED = 255
};

    interface IndexStatic {
        new (): Index;
        new (features: _st.InputArray, params: IndexParams, distType?: flann_distance /* = cvflann::FLANN_DIST_L2*/): Index;
    }

export interface Index
{
//public:

    build(features: _st.InputArray, params: IndexParams, distType?: flann_distance_t /*= cvflann::FLANN_DIST_L2*/): void;
    knnSearch(query: _st.InputArray, indices: _st.OutputArray ,
        dists: _st.OutputArray, knn: _st.int, params?: SearchParams /*=SearchParams()*/): void;

    radiusSearch(query: _st.InputArray, indices: _st.OutputArray ,
        dists: _st.OutputArray, radius: _st.double, maxResults: _st.int ,
        params?: SearchParams /*=SearchParams()*/): _st.int;

    save(filename : string): void;
    load(features: _st.InputArray , filename : string): boolean;
    release(): void;
    getDistance() : flann_distance_t;
    getAlgorithm() :flann_algorithm_t;
//
//protected:
//    cvflann::flann_distance_t distType;
//    cvflann::flann_algorithm_t algo;
//    int featureType;
//    void* index;
};

    export var Index: IndexStatic = alvision_module.flann.Index;

}
//} // namespace cv::flann
//
//#endif


text:
import $ = require("./jquery");
import { usingOverride } from "../common/variables";

var override = usingOverride(window, { $, jQuery: $ });

import "./jquery-ui/jquery-ui";
import "./jquery-ui/jquery-ui.css";

override.dispose();


text:
package petablox.analyses.syntax;

import soot.SootClass;
import soot.SootMethod;
import soot.Unit;
import soot.jimple.internal.JIfStmt;

import petablox.program.visitors.IIfInstVisitor;
import petablox.project.Petablox;
import petablox.project.analyses.ProgramRel;

@Petablox(name = "IfInst", sign = "P0,EXPR0,P1:P0_EXPR0xP1")
public class RelIfInst extends ProgramRel implements IIfInstVisitor {
    @Override
    public void visit(SootClass m) { }

    @Override
    public void visit(SootMethod m) { }

    @Override
    public void visit(Unit u) { }

    public void visit(JIfStmt s) {
        add(s, s.getCondition(), s.getTarget());
    }
}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<class name="GLTFNode" inherits="Resource" version="3.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../doc/class.xsd">
	<brief_description>
	</brief_description>
	<description>
		[b]Note:[/b] This class is only compiled in editor builds. Run-time glTF loading and saving is [i]not[/i] available in exported projects. References to [GLTFNode] within a script will cause an error in an exported project.
	</description>
	<tutorials>
	</tutorials>
	<methods>
	</methods>
	<members>
		<member name="camera" type="int" setter="set_camera" getter="get_camera" default="-1">
		</member>
		<member name="children" type="PoolIntArray" setter="set_children" getter="get_children" default="PoolIntArray(  )">
		</member>
		<member name="height" type="int" setter="set_height" getter="get_height" default="-1">
		</member>
		<member name="joint" type="bool" setter="set_joint" getter="get_joint" default="false">
		</member>
		<member name="light" type="int" setter="set_light" getter="get_light" default="-1">
		</member>
		<member name="mesh" type="int" setter="set_mesh" getter="get_mesh" default="-1">
		</member>
		<member name="parent" type="int" setter="set_parent" getter="get_parent" default="-1">
		</member>
		<member name="rotation" type="Quat" setter="set_rotation" getter="get_rotation" default="Quat( 0, 0, 0, 1 )">
		</member>
		<member name="scale" type="Vector3" setter="set_scale" getter="get_scale" default="Vector3( 1, 1, 1 )">
		</member>
		<member name="skeleton" type="int" setter="set_skeleton" getter="get_skeleton" default="-1">
		</member>
		<member name="skin" type="int" setter="set_skin" getter="get_skin" default="-1">
		</member>
		<member name="translation" type="Vector3" setter="set_translation" getter="get_translation" default="Vector3( 0, 0, 0 )">
		</member>
		<member name="xform" type="Transform" setter="set_xform" getter="get_xform" default="Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )">
		</member>
	</members>
	<constants>
	</constants>
</class>


text:
package slamdata.engine.std

import slamdata.Predef._

import scalaz._
import Scalaz._

import slamdata.engine.{Data, Func, LogicalPlan, Type, Mapping, SemanticError}; import LogicalPlan._
import slamdata.engine.analysis.fixplate._
import slamdata.engine.fp._

import SemanticError._
import Validation.{success, failure}
import NonEmptyList.nel

trait StringLib extends Library {
  private def stringApply(f: (String, String) => String): Func.Typer = {
      case Type.Const(Data.Str(a)) :: Type.Const(Data.Str(b)) :: Nil => success(Type.Const(Data.Str(f(a, b))))

      case Type.Str :: Type.Const(Data.Str(_)) :: Nil => success(Type.Str)
      case Type.Const(Data.Str(_)) :: Type.Str :: Nil => success(Type.Str)
      case Type.Str :: Type.Str :: Nil                => success(Type.Str)

      case t :: _ => failure(nel(TypeError(Type.Str, t, None), Nil))
      case Nil    => failure(nel(GenericError("expected arguments"), Nil))
    }

  private val StringUnapply: Func.Untyper = {
    case Type.Str => success(Type.Str :: Type.Str :: Nil)
    case t => failure(nel(TypeError(Type.Str, t, None), Nil))
  }

  // TODO: variable arity
  val Concat = Mapping("concat", "Concatenates two (or more) string values", Type.Str :: Type.Str :: Nil,
    partialSimplifier {
      case List(Term(ConstantF(Data.Str(""))), other) => other
      case List(other, Term(ConstantF(Data.Str("")))) => other
    },
    stringApply(_ + _),
    StringUnapply)

  val Like = Mapping(
    "(like)",
    "Determines if a string value matches a pattern.",
    Type.Str :: Type.Str :: Type.Str :: Nil,
    noSimplification,
    {
      case List(Type.Str, Type.Const(Data.Str(_)), Type.Const(Data.Str(_))) =>
        success(Type.Bool)
      case Type.Str :: _ :: _ :: Nil =>
        failure(nel(GenericError("expected string constant for LIKE"), Nil))
      case t :: Type.Const(Data.Str(_)) :: Nil =>
        failure(nel(TypeError(Type.Str, t, None), Nil))
      case _ =>
        failure(nel(GenericError("expected arguments"), Nil))
    },
    Type.typecheck(_, Type.Bool) map κ(Type.Str :: Type.Str :: Type.Str :: Nil))

  def matchAnywhere(str: String, pattern: String) = java.util.regex.Pattern.compile(pattern).matcher(str).find()

  val Search = Mapping(
    "search",
    "Determines if a string value matches a regular expresssion.",
    Type.Str :: Type.Str :: Nil,
    noSimplification,
    {
      case Type.Const(Data.Str(str)) :: Type.Const(Data.Str(pattern)) :: Nil =>
        success(Type.Const(Data.Bool(matchAnywhere(str, pattern))))
      case strT :: patternT :: Nil =>
        (Type.typecheck(Type.Str, strT) |@| Type.typecheck(Type.Str, patternT))((_, _) => Type.Bool)
      case _ =>
        failure(nel(GenericError("expected arguments"), Nil))
    },
    Type.typecheck(_, Type.Bool) map κ(Type.Str :: Type.Str :: Nil))

  val Length = Mapping(
    "length",
    "Counts the number of characters in a string.",
    Type.Str :: Nil,
    noSimplification,
    {
      case Type.Const(Data.Str(str)) :: Nil =>
        success(Type.Const(Data.Int(str.length)))
      case Type.Str :: Nil => success(Type.Int)
      case t :: Nil => failure(nel(TypeError(Type.Str, t, None), Nil))
      case _ => failure(nel(GenericError("expected arguments"), Nil))
    },
    Type.typecheck(_, Type.Int) map κ(Type.Str :: Nil))

  val Lower = Mapping(
    "lower",
    "Converts the string to lower case.",
    Type.Str :: Nil,
    noSimplification,
    {
      case Type.Const(Data.Str(str)) :: Nil =>
        success(Type.Const (Data.Str(str.toLowerCase)))
      case Type.Str :: Nil => success(Type.Str)
      case t :: Nil => failure(nel(TypeError(Type.Str, t, None), Nil))
      case _ => failure(nel(GenericError("expected arguments"), Nil))
    },
    Type.typecheck(_, Type.Str) map κ(Type.Str :: Nil)
  )

  val Upper = Mapping(
    "upper",
    "Converts the string to upper case.",
    Type.Str :: Nil,
    noSimplification,
    {
      case Type.Const(Data.Str(str)) :: Nil =>
        success(Type.Const (Data.Str(str.toUpperCase)))
      case Type.Str :: Nil => success(Type.Str)
      case t :: Nil => failure(nel(TypeError(Type.Str, t, None), Nil))
      case _ => failure(nel(GenericError("expected arguments"), Nil))
    },
    Type.typecheck(_, Type.Str) map κ(Type.Str :: Nil)
  )

  val Substring: Mapping = Mapping(
    "substring",
    "Extracts a portion of the string",
    Type.Str :: Type.Int :: Type.Int :: Nil,
    partialSimplifier {
      case List(Term(ConstantF(Data.Str(str))), Term(ConstantF(Data.Int(from))), for0) if 0 < from =>
        Substring(
          Constant(Data.Str(str.substring(from.intValue))),
          Constant(Data.Int(0)),
          for0)
    },
    partialTyperV {
      case List(
        Type.Const(Data.Str(str)),
        Type.Const(Data.Int(from)),
        Type.Const(Data.Int(for0))) => {
        success(Type.Const(Data.Str(str.substring(from.intValue, from.intValue + for0.intValue))))
      }
      case List(Type.Const(Data.Str(str)), Type.Const(Data.Int(from)), _)
          if str.length <= from =>
        success(Type.Const(Data.Str("")))
      case List(Type.Const(Data.Str(_)), Type.Const(Data.Int(_)), Type.Int) =>
        success(Type.Str)
      case List(Type.Const(Data.Str(_)), Type.Int, Type.Const(Data.Int(_))) =>
        success(Type.Str)
      case List(Type.Const(Data.Str(_)), Type.Int,                Type.Int) =>
        success(Type.Str)
      case List(Type.Str, Type.Const(Data.Int(_)), Type.Const(Data.Int(_))) =>
        success(Type.Str)
      case List(Type.Str, Type.Const(Data.Int(_)), Type.Int)                =>
        success(Type.Str)
      case List(Type.Str, Type.Int,                Type.Const(Data.Int(_))) =>
        success(Type.Str)
      case List(Type.Str, Type.Int,                Type.Int)                =>
        success(Type.Str)
      case List(Type.Str, _,                       _)                       =>
        failure(nel(GenericError("expected integer arguments for SUBSTRING"), Nil))
      case List(t, _, _) => failure(nel(TypeError(Type.Str, t, None), Nil))
    },
    Type.typecheck(_, Type.Str) map κ(Type.Str :: Type.Int :: Type.Int :: Nil)
  )

  def functions = Concat :: Like :: Search :: Length :: Lower :: Upper :: Substring :: Nil
}
object StringLib extends StringLib


text:
package org.apache.harmony.unpack200.tests;

import junit.framework.TestCase;

import org.apache.harmony.pack200.Pack200Exception;
import org.apache.harmony.unpack200.AttributeLayout;
import org.apache.harmony.unpack200.AttributeLayoutMap;

public class AttributeLayoutMapTest extends TestCase {

    public void testRepeatable() throws Pack200Exception {
        // Check we can retrieve a default layout
        AttributeLayoutMap a = new AttributeLayoutMap();
        AttributeLayout layout = a.getAttributeLayout("SourceFile",
                AttributeLayout.CONTEXT_CLASS);
        assertNotNull(layout);
        assertEquals("RUNH", layout.getLayout());
        assertEquals(17, layout.getIndex());
        // and that we can change it
        a.add(new AttributeLayout("SourceFile", AttributeLayout.CONTEXT_CLASS,
                "FROG", 17));
        layout = a.getAttributeLayout("SourceFile",
                AttributeLayout.CONTEXT_CLASS);
        assertNotNull(layout);
        assertEquals("FROG", layout.getLayout());
        assertTrue(layout.matches(1 << 17));
        assertFalse(layout.matches(1 << 16));
        assertTrue(layout.matches(-1));
        assertFalse(layout.matches(0));
        // and that changes don't affect subsequent defaults
        AttributeLayoutMap b = new AttributeLayoutMap();
        layout = b.getAttributeLayout("SourceFile",
                AttributeLayout.CONTEXT_CLASS);
        assertNotNull(layout);
        assertEquals("RUNH", layout.getLayout());

    }
}


text:
(exports = module.exports = function(house, options){
    house.api = {};
    if(!options) {
        var filter = _.find(house.config.filters, function(f){ return (f.hasOwnProperty('api')); });
        options = (filter && filter.api && filter.api.hasOwnProperty('rest')) ? filter.api.rest : {};
    }

    if(options.hasOwnProperty('endPoints')) {
        house.api.endPoints = require(options.endPoints)(house);
    } else {
        house.api.endPoints = require(process.cwd()+'/endPoints')(house);
    }

    var handleReq = function(req, res, next) {
        var path = req.hasOwnProperty('urlRouted') ? req.urlRouted : req.url;
        //house.log.debug('api req url: '+path);
        req.urlParsed = url.parse(path, true);
        if(req.urlParsed.search) {
          req.query = req.urlParsed.query; //querystring.parse(req.urlParsed.query);
          if(_.size(req.query) === 1) {
              for(var i in req.query) {
                  if(req.query[i] === '') {
                      var json = JSON.parse(i);
                      req.query = json;
                  }
              }
          }
        }
        //
        // endpoints can respond using this method to handle the common rest request,
        // taking the accept type into consideration
        //
        res.data = function(data, fmt){
            var sendResJson = function() {
                res.setHeader('Content-Type', 'application/json');
                res.end(JSON.stringify(data));
            }
            var sendResText = function() {
                if(typeof data !== 'string') {
                    data = JSON.stringify(data, null, 4);
                }
                res.end(data);
            }
            var sendResRss = function() {
                var items = '';
                for(var i in data) {
                    var it = data[i];
                    items += '<item>\
    <title>'+it.title+'</title>\
    <link>'+it.url+'</link>\
    <comments>'+it.url+'</comments>\
    <description><![CDATA['+it.desc+']]></description>\
    <author>'+it.author+'</author>\
    <pubDate>'+it.pubDate+'</pubDate>\
</item>';
                }

                var xml = '<rss version="2.0"><channel><title>'+house.config.site.title+'</title><link>'+house.config.site.url+'</link><description>'+house.config.site.desc+'</description>\
    '+items+'\
</channel></rss>';

                res.setHeader('Content-Type', 'application/rss+xml');
                res.end(xml);
            }

            if(fmt) {
                if(fmt == 'rss') {
                    sendResRss();
                }
            } else if(req.headers.hasOwnProperty('accept')) {
                var acceptType = req.headers.accept;

                if(acceptType.indexOf('json') !== -1) {
                    sendResJson();
                } else {
                    sendResText();
                }
            } else {
                sendResJson();
            }
        }

        //
        // Describe our api endpoints
        //
        if(path === '/') {
            res.data(house.api.endPointsList);
            return;
        }

        // route to known endpoints

        for(var i in house.api.endPoints) {
            for(var routePath in house.api.endPoints[i]) {
                //house.log.debug('api routePath '+routePath);
                if(path.indexOf(routePath) === 1) {

                    //house.log.debug('api endpoint '+path);

                    req.urlRouted = path.substr(routePath.length+1);

                    //house.log.debug('modified req.urlRouted '+req.urlRouted);

                    house.api.endPoints[i][routePath].apply(this, arguments);
                    return;
                }
            }
        }
        next();
    };
    return handleReq;
});


text:
// Copyright (C) 2011 AMEE UK Ltd. - http://www.amee.com
// Released as Open Source Software under the BSD 3-Clause license. See LICENSE.txt for details.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AMEE;

namespace AMEEMaterials
{
    public partial class CarbonSummaryForm : Form
    {
        public CarbonSummaryForm()
        {
            InitializeComponent();
        }

        public void UpdateData(ProfileItem item)
        {
            List<List<string>> results = new List<List<string>>();
            foreach (ProfileItem.Amount x in item.Amounts)
            {
                List<string> cols = new List<string>();
                cols.Add(x.Type);
                cols.Add(x.Value);
                cols.Add(x.Unit);
                results.Add(cols);
            }
            UpdateData(results);
        }

        public void UpdateData(List<List<string>> table)
        {
            listView.Items.Clear();
            foreach (List<string> row in table)
            {
                ListViewItem listViewItem = new ListViewItem();
                listViewItem.Text = row[0];
                listViewItem.SubItems.Add(row[1]);
                listViewItem.SubItems.Add(row[2]);
                listView.Items.Add(listViewItem);
            }
        }

    }
}


text:
package com.microsoft.azure.management.netapp.v2020_06_01;

import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;

/**
 * Defines values for RelationshipStatus.
 */
public final class RelationshipStatus extends ExpandableStringEnum<RelationshipStatus> {
    /** Static value Idle for RelationshipStatus. */
    public static final RelationshipStatus IDLE = fromString("Idle");

    /** Static value Transferring for RelationshipStatus. */
    public static final RelationshipStatus TRANSFERRING = fromString("Transferring");

    /**
     * Creates or finds a RelationshipStatus from its string representation.
     * @param name a name to look for
     * @return the corresponding RelationshipStatus
     */
    @JsonCreator
    public static RelationshipStatus fromString(String name) {
        return fromString(name, RelationshipStatus.class);
    }

    /**
     * @return known RelationshipStatus values
     */
    public static Collection<RelationshipStatus> values() {
        return values(RelationshipStatus.class);
    }
}


text:
package nl.knaw.huygens.timbuctoo.crud.conversion.json;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.collect.Lists;
import nl.knaw.huygens.timbuctoo.core.dto.ReadEntityImpl;
import nl.knaw.huygens.timbuctoo.core.dto.RelationRef;
import nl.knaw.huygens.timbuctoo.core.dto.dataset.Collection;
import nl.knaw.huygens.timbuctoo.core.dto.property.HyperLinksProperty;
import nl.knaw.huygens.timbuctoo.core.dto.property.StringProperty;
import nl.knaw.huygens.timbuctoo.core.dto.property.TimProperty;
import nl.knaw.huygens.timbuctoo.crud.conversion.EntityToJsonMapper;
import nl.knaw.huygens.timbuctoo.model.Change;
import nl.knaw.huygens.timbuctoo.v5.security.dto.User;
import nl.knaw.huygens.timbuctoo.v5.security.UserValidator;
import org.junit.Before;
import org.junit.Test;

import java.net.URI;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Optional;
import java.util.UUID;

import static nl.knaw.huygens.timbuctoo.util.JsonBuilder.jsn;
import static nl.knaw.huygens.timbuctoo.util.JsonBuilder.jsnA;
import static nl.knaw.huygens.timbuctoo.util.JsonBuilder.jsnO;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static uk.co.datumedge.hamcrest.json.SameJSONAs.sameJSONAs;

// TODO before refactoring this class improve coverage
public class EntityToJsonMapperTest {

  public static final String USER_ID = "userId";
  public static final String USER_NAME = "User Name";
  private UserValidator userValidator;
  private EntityToJsonMapper instance;

  @Before
  public void setUp() throws Exception {
    userValidator = mock(UserValidator.class);
    when(userValidator.getUserFromUserId(USER_ID)).thenReturn(Optional.of(User.create(USER_NAME, "")));
    instance = new EntityToJsonMapper(
      userValidator,
      (collection, id1, rev) -> URI.create("www.example.com")
    );
  }

  @Test
  public void mapEntityMapsTheTypeAndId() throws Exception {
    ReadEntityImpl readEntity = new ReadEntityImpl();
    UUID id = UUID.randomUUID();
    readEntity.setId(id);
    Change change = new Change(Instant.now().toEpochMilli(), USER_ID, null);
    readEntity.setCreated(change);
    readEntity.setModified(change);
    String type = "otherType";
    readEntity.setTypes(Lists.newArrayList("type", type));
    readEntity.setDeleted(false);
    readEntity.setRev(1);
    readEntity.setPid("pid");
    readEntity.setProperties(Lists.newArrayList());

    EntityToJsonMapper instance = new EntityToJsonMapper(
      userValidator,
      (collection, id1, rev) -> URI.create("www.example.com")
    );
    Collection collection = mock(Collection.class);
    when(collection.getEntityTypeName()).thenReturn(type);

    ObjectNode resutlJson = instance.mapEntity(
      collection,
      readEntity,
      false,
      (readEntity1, resultJson) -> {
      },
      (relationRef, resultJson) -> {
      }
    );

    assertThat(
      resutlJson.toString(),
      sameJSONAs(jsnO("_id", jsn(id.toString()), "@type", jsn(type)).toString()).allowingExtraUnexpectedFields()
    );
  }

  @Test
  public void mapEntityMapsTheProperties() throws Exception {
    ReadEntityImpl readEntity = new ReadEntityImpl();
    readEntity.setId(UUID.randomUUID());
    String userId = "userId";
    Change change = new Change(Instant.now().toEpochMilli(), userId, null);
    readEntity.setCreated(change);
    readEntity.setModified(change);
    String type = "otherType";
    readEntity.setTypes(Lists.newArrayList("type", type));
    readEntity.setDeleted(false);
    readEntity.setRev(1);
    readEntity.setPid("pid");
    ArrayList<TimProperty<?>> properties = Lists.newArrayList();
    properties.add(new StringProperty("name", "Name"));
    readEntity.setProperties(properties);
    EntityToJsonMapper instance = new EntityToJsonMapper(
      userValidator,
      (collection, id1, rev) -> URI.create("www.example.com")
    );
    Collection collection = mock(Collection.class);
    when(collection.getEntityTypeName()).thenReturn(type);

    ObjectNode resutlJson = instance.mapEntity(
      collection,
      readEntity,
      false,
      (readEntity1, resultJson) -> {
      },
      (relationRef, resultJson) -> {
      }
    );

    assertThat(
      resutlJson.toString(),
      sameJSONAs(jsnO("name", jsn("Name")).toString()).allowingExtraUnexpectedFields()
    );
  }

  @Test
  public void doesNotAddNonConvertableProperties() {
    ReadEntityImpl readEntity = new ReadEntityImpl();
    readEntity.setId(UUID.randomUUID());
    String userId = "userId";
    Change change = new Change(Instant.now().toEpochMilli(), userId, null);
    readEntity.setCreated(change);
    readEntity.setModified(change);
    String type = "otherType";
    readEntity.setTypes(Lists.newArrayList("type", type));
    readEntity.setDeleted(false);
    readEntity.setRev(1);
    readEntity.setPid("pid");
    ArrayList<TimProperty<?>> properties = Lists.newArrayList();
    properties.add(new HyperLinksProperty("nonParsableProp", "Name"));
    readEntity.setProperties(properties);
    EntityToJsonMapper instance = new EntityToJsonMapper(
      userValidator,
      (collection, id1, rev) -> URI.create("www.example.com")
    );
    Collection collection = mock(Collection.class);
    when(collection.getEntityTypeName()).thenReturn(type);

    ObjectNode resutlJson = instance.mapEntity(
      collection,
      readEntity,
      false,
      (readEntity1, resultJson) -> {
      },
      (relationRef, resultJson) -> {
      }
    );

    assertThat(Lists.newArrayList(resutlJson.fieldNames()), not(hasItem("nonParsableProp")));
  }

  @Test
  public void mapEntityMapsTheRelations() throws Exception {
    ReadEntityImpl readEntity = new ReadEntityImpl();
    UUID id = UUID.randomUUID();
    readEntity.setId(id);
    String userId = "userId";
    Change change = new Change(Instant.now().toEpochMilli(), userId, null);
    readEntity.setCreated(change);
    readEntity.setModified(change);
    String type = "otherType";
    readEntity.setTypes(Lists.newArrayList("type", type));
    readEntity.setDeleted(false);
    readEntity.setRev(1);
    readEntity.setPid("pid");
    readEntity.setProperties(Lists.newArrayList());
    String otherEntity = UUID.randomUUID().toString();
    String relType = "relType";
    readEntity.setRelations(
      Lists.newArrayList(new RelationRef(otherEntity, "rdfUri", new String[]{"origUri"}, "otherColl", "otherType",
        true, "relId", "rdfUri", 1, relType, "displayName")));
    Collection collection = mock(Collection.class);
    when(collection.getEntityTypeName()).thenReturn(type);

    ObjectNode resutlJson = instance.mapEntity(
      collection,
      readEntity,
      true,
      (readEntity1, resultJson) -> {
      },
      (relationRef, resultJson) -> {
      }
    );

    assertThat(resutlJson.toString(), sameJSONAs(jsnO(
      "@relationCount", jsn(1),
      "@relations", jsnO(
        relType, jsnA(
          jsnO(
            "id", jsn(otherEntity)
          )
        )
      )
    ).toString()).allowingExtraUnexpectedFields());
  }

  @Test
  public void mapEntityDoesNotAddADisplayPropertyWhenTheDisplayNameIsNull() {
    ReadEntityImpl readEntity = new ReadEntityImpl();
    UUID id = UUID.randomUUID();
    readEntity.setId(id);
    String userId = "userId";
    Change change = new Change(Instant.now().toEpochMilli(), userId, null);
    readEntity.setCreated(change);
    readEntity.setModified(change);
    String type = "otherType";
    readEntity.setTypes(Lists.newArrayList("type", type));
    readEntity.setDeleted(false);
    readEntity.setRev(1);
    readEntity.setPid("pid");
    readEntity.setProperties(Lists.newArrayList());
    readEntity.setRelations(Lists.newArrayList());
    Collection collection = mock(Collection.class);
    when(collection.getEntityTypeName()).thenReturn(type);

    ObjectNode resutlJson = instance.mapEntity(
      collection,
      readEntity,
      true,
      (readEntity1, resultJson) -> {
      },
      (relationRef, resultJson) -> {
      }
    );

    assertThat(resutlJson.has("@displayName"), is(false));
  }

  @Test
  public void mapEntityAddsADisplayNameWhenItIsKnown() {
    ReadEntityImpl readEntity = new ReadEntityImpl();
    UUID id = UUID.randomUUID();
    readEntity.setId(id);
    String userId = "userId";
    Change change = new Change(Instant.now().toEpochMilli(), userId, null);
    readEntity.setCreated(change);
    readEntity.setModified(change);
    String type = "otherType";
    readEntity.setTypes(Lists.newArrayList("type", type));
    readEntity.setDeleted(false);
    readEntity.setRev(1);
    readEntity.setPid("pid");
    readEntity.setProperties(Lists.newArrayList());
    readEntity.setRelations(Lists.newArrayList());
    String displayName = "displayName";
    readEntity.setDisplayName(displayName);
    Collection collection = mock(Collection.class);
    when(collection.getEntityTypeName()).thenReturn(type);

    ObjectNode resutlJson = instance.mapEntity(
      collection,
      readEntity,
      true,
      (readEntity1, resultJson) -> {
      },
      (relationRef, resultJson) -> {
      }
    );

    assertThat(resutlJson.has("@displayName"), is(true));
    assertThat(resutlJson.get("@displayName"), is(jsn(displayName)));
  }

}


text:
"""Language datasets."""

import functools
from typing import Tuple

import gin
import haiku as hk
import jax
import jax.numpy as jnp
from learned_optimization.tasks.datasets import base
import seqio
import tensorflow.compat.v2 as tf
import tensorflow_datasets as tfds

DEFAULT_SPM_PATH = 'gs://t5-data/vocabs/cc_all.32000/sentencepiece.model'
DEFAULT_EXTRA_IDS = 100

@functools.lru_cache(maxsize=None)
def get_32k_sentence_piece_vocab():
  return seqio.SentencePieceVocabulary(DEFAULT_SPM_PATH, DEFAULT_EXTRA_IDS)

@functools.lru_cache(maxsize=None)
def get_bytes_vocab():
  return seqio.vocabularies.ByteVocabulary()

def _crop_or_pad(value, size, pad_token):
  """Either crop or pad value to be of size size."""
  val_size = tf.size(value)
  pad = lambda: tf.pad(  # pylint: disable=g-long-lambda
      value, [[0, size - val_size]],
      'CONSTANT',
      constant_values=pad_token)
  return tf.cond(val_size < size, pad, lambda: value[:size])

def _load(name, tokenizer, batch_size: int, sequence_length: int,
          split) -> Tuple[tf.data.Dataset, int]:
  """Load tfds tf.data.Dataset in a streaming fashion."""
  ds = tfds.load(name, split=split, shuffle_files=True)

  crop_size = sequence_length + 1
  ds = ds.repeat()
  ds = ds.map(lambda x: tokenizer.encode_tf(x['text']))
  ds = ds.map(lambda t: _crop_or_pad(t, crop_size, pad_token=0))
  ds = ds.shuffle(batch_size * 10)

  # Create the language modeling observation/target pairs and batch them up.
  def create_lm_obs_target(t):
    return hk.data_structures.to_immutable_dict(dict(obs=t[:-1], target=t[1:]))

  ds = ds.map(create_lm_obs_target)
  ds = ds.batch(batch_size, drop_remainder=True)
  ds = ds.prefetch(tf.data.experimental.AUTOTUNE)
  ds = tfds.as_numpy(ds)
  return ds

def _make_datasets(tfds_datasetname: str,
                   vocab: seqio.vocabularies.Vocabulary,
                   batch_size: int,
                   sequence_length: int,
                   has_test: bool = True) -> base.Datasets:
  """Make Datasets object from tokenized tfds dataset."""
  if has_test:
    splits = ['train[2%:100%]', 'train[0%:1%]', 'train[1%:2%]', 'test']
  else:
    splits = ['train[3%:100%]', 'train[0%:1%]', 'train[1%:2%]', 'train[2%:3%]']

  def make(split):

    def iterator_fn():
      it = _load(tfds_datasetname, vocab, batch_size, sequence_length, split)
      return iter(it)

    return base.ThreadSafeIterator(base.LazyIterator(iterator_fn))

  train, inner_valid, outer_valid, test = [make(split) for split in splits]
  abstract_batch = {
      'obs': jax.ShapedArray((batch_size, sequence_length), jnp.int32),
      'target': jax.ShapedArray((batch_size, sequence_length), jnp.int32),
  }
  return base.Datasets(
      train=train,
      inner_valid=inner_valid,
      outer_valid=outer_valid,
      test=test,
      extra_info={
          'vocab_size': vocab.vocab_size,
          'vocab': vocab
      },
      abstract_batch=abstract_batch)

@gin.configurable
@base.dataset_lru_cache
def lm1b_32k_datasets(batch_size, sequence_length):
  vocab = get_32k_sentence_piece_vocab()
  return _make_datasets('lm1b', vocab, batch_size, sequence_length)

@gin.configurable
@base.dataset_lru_cache
def lm1b_bytes_datasets(batch_size, sequence_length):
  vocab = get_bytes_vocab()
  return _make_datasets('lm1b', vocab, batch_size, sequence_length)

@gin.configurable
@base.dataset_lru_cache
def wikipedia_en_32k_datasets(batch_size, sequence_length):
  vocab = get_32k_sentence_piece_vocab()
  return _make_datasets(
      'wikipedia/20201201.en',
      vocab,
      batch_size,
      sequence_length,
      has_test=False)

@gin.configurable
@base.dataset_lru_cache
def wikipedia_en_bytes_datasets(batch_size, sequence_length):
  vocab = get_bytes_vocab()
  return _make_datasets(
      'wikipedia/20201201.en',
      vocab,
      batch_size,
      sequence_length,
      has_test=False)


text:
class SimSet : public SimObject, public TamlChildren
{
   public:

      typedef SimObject Parent;
      typedef SimObject Children;

      enum SetModification
      {
         SetCleared,
         SetObjectAdded,
         SetObjectRemoved
      };

      /// Signal for letting observers know when objects are added to or removed from
      /// the set.
      ///
      /// @param modification In what way the set has been modified.
      /// @param set The set that has been modified.
      /// @param object If #modification is #SetObjectAdded or #SetObjectRemoved, this is
      ///   the object that has been added or removed.  Otherwise NULL.
      typedef Signal< void( SetModification modification, SimSet* set, SimObject* object ) > SetModificationSignal;

   protected:

      SimObjectList mObjectList;
      void *mMutex;

      /// Signal that is triggered when objects are added or removed from the set.
      SetModificationSignal mSetModificationSignal;

      /// @name Callbacks
      /// @{

      DECLARE_CALLBACK( void, onObjectAdded, ( SimObject* object ) );
      DECLARE_CALLBACK( void, onObjectRemoved, ( SimObject* object ) );

      /// @}

   public:

      SimSet();
      ~SimSet();

      /// Return the signal that is triggered when an object is added to or removed
      /// from the set.
      const SetModificationSignal& getSetModificationSignal() const { return mSetModificationSignal; }
      SetModificationSignal& getSetModificationSignal() { return mSetModificationSignal; }

      /// @name STL Interface
      /// @{

      ///
      typedef SimObjectList::iterator iterator;
      typedef SimObjectList::value_type value;
      SimObject* front() { return mObjectList.front(); }
      SimObject* first() { return mObjectList.first(); }
      SimObject* last()  { return mObjectList.last(); }
      bool       empty() const { return mObjectList.empty();   }
      S32        size() const  { return mObjectList.size(); }
      iterator   begin() { return mObjectList.begin(); }
      iterator   end()   { return mObjectList.end(); }
      value operator[] (S32 index) { return mObjectList[U32(index)]; }

      inline iterator find( iterator first, iterator last, SimObject *obj)
      { return T3D::find(first, last, obj); }
      inline iterator find(SimObject *obj)
      { return T3D::find(begin(), end(), obj); }

      /// Reorder the position of "obj" to either be the last object in the list or, if
      /// "target" is given, to come before "target" in the list of children.
      virtual bool reOrder( SimObject *obj, SimObject *target=0 );

      /// Return the object at the given index.
      SimObject* at(S32 index) const { return mObjectList.at(index); }

      /// Remove all objects from this set.
      virtual void clear();

      /// @}

      /// @name Set Management
      /// @{

      /// Add the given object to the set.
      /// @param object Object to add to the set.
      virtual void addObject( SimObject* object );

      /// Remove the given object from the set.
      /// @param object Object to remove from the set.
      virtual void removeObject( SimObject* object );

      /// Add the given object to the end of the object list of this set.
      /// @param object Object to add to the set.
      virtual void pushObject( SimObject* object );

      /// Return true if this set accepts the given object as a child.
      /// This method should be overridden for set classes that restrict membership.
      virtual bool acceptsAsChild( SimObject* object ) const { return true; }

      /// Deletes all the objects in the set.
      void deleteAllObjects();

      /// Remove an object from the end of the list.
      virtual void popObject();

      void bringObjectToFront(SimObject* obj) { reOrder(obj, front()); }
      void pushObjectToBack(SimObject* obj) { reOrder(obj, NULL); }

      /// Performs a sort of the objects in the set using a script
      /// callback function to do the comparison.
      ///
      /// An example script sort callback:
      ///
      /// @code
      ///   function sortByName( %object1, %object2 )
      ///   {
      ///      return strcmp( %object1.getName(), %object2.getName() );
      ///   }
      /// @endcode
      ///
      /// Note: You should never modify the SimSet itself while in
      /// the sort callback function as it can cause a deadlock.
      ///
      void scriptSort( const String &scriptCallbackFn );

      /// @}

      void callOnChildren( const String &method, S32 argc, ConsoleValue argv[], bool executeOnChildGroups = true );

      /// Return the number of objects in this set as well as all sets that are contained
      /// in this set and its children.
      ///
      /// @note The child sets themselves count towards the total too.
      U32 sizeRecursive();

      virtual SimObject* findObjectByInternalName(StringTableEntry internalName, bool searchChildren = false);
      SimObject* findObjectByLineNumber(const char* fileName, S32 declarationLine, bool searchChildren = false);

      /// Find the given object in this set.  Returns NULL if the object
      /// is not part of this set.
      SimObject* findObject( SimObject* object );

      /// Add all child objects ( including children of children ) to the foundObjects
      /// Vector which are of type T.

      template< class T >
      void findObjectByType( Vector<T*> &foundObjects );

      /// Add all child objects ( including children of children ) to the foundObjects
      /// Vector which are of type T and for which DecideAddObjectCallback return true;

      template< class T >
      void findObjectByCallback( bool ( *fn )( T* ), Vector<T*>& foundObjects );

      SimObject* getRandom();

      inline void lock()
      {
         #ifdef TORQUE_MULTITHREAD
         Mutex::lockMutex(mMutex);
         #endif
      }

      void unlock()
      {
         #ifdef TORQUE_MULTITHREAD
         Mutex::unlockMutex(mMutex);
         #endif
      }

      #ifdef TORQUE_DEBUG_GUARD
      inline void _setVectorAssoc( const char *file, const U32 line )
      {
		  mObjectList.setFileAssociation( file, line );
      }
      #endif

      // SimObject.
      DECLARE_CONOBJECT( SimSet );

      virtual void onRemove();
      virtual void onDeleteNotify(SimObject *object);

      virtual SimObject* findObject( const char* name );

      virtual void write(Stream &stream, U32 tabStop, U32 flags = 0);
      virtual bool writeObject(Stream *stream);
      virtual bool readObject(Stream *stream);

      virtual SimSet* clone();

      // TamlChildren
      virtual U32 getTamlChildCount(void) const
      {
         return (U32)size();
      }

      virtual SimObject* getTamlChild(const U32 childIndex) const
      {
         // Sanity!
         AssertFatal(childIndex < (U32)size(), "SimSet::getTamlChild() - Child index is out of range.");

         // For when the assert is not used.
         if (childIndex >= (U32)size())
            return NULL;

         return at(childIndex);
      }

      virtual void addTamlChild(SimObject* pSimObject)
      {
         // Sanity!
         AssertFatal(pSimObject != NULL, "SimSet::addTamlChild() - Cannot add a NULL child object.");

         addObject(pSimObject);
      }
};

#ifdef TORQUE_DEBUG_GUARD
#  define SIMSET_SET_ASSOCIATION( x ) x._setVectorAssoc( __FILE__, __LINE__ )
#else
#  define SIMSET_SET_ASSOCIATION( x )
#endif

template< class T >
void SimSet::findObjectByType( Vector<T*> &foundObjects )
{
   T *curObj;
   SimSet *curSet;

   lock();

   // Loop through our child objects.

   SimObjectList::iterator itr = mObjectList.begin();

   for ( ; itr != mObjectList.end(); itr++ )
   {
      curObj = dynamic_cast<T*>( *itr );
      curSet = dynamic_cast<SimSet*>( *itr );

      // If child object is a set, call recursively into it.
      if ( curSet && curSet->size() != 0)
         curSet->findObjectByType( foundObjects );

      // Add this child object if appropriate.
      if ( curObj )
         foundObjects.push_back( curObj );
   }

   // Add this object if appropriate.
   curObj = dynamic_cast<T*>(this);
   if ( curObj )
      foundObjects.push_back( curObj );

   unlock();
}

template< class T >
void SimSet::findObjectByCallback(  bool ( *fn )( T* ), Vector<T*> &foundObjects )
{
   T *curObj;
   SimSet *curSet;

   lock();

   // Loop through our child objects.

   SimObjectList::iterator itr = mObjectList.begin();

   for ( ; itr != mObjectList.end(); itr++ )
   {
      curObj = dynamic_cast<T*>( *itr );
      curSet = dynamic_cast<SimSet*>( *itr );

      // If child object is a set, call recursively into it.
      if ( curSet )
         curSet->findObjectByCallback( fn, foundObjects );

      // Add this child object if appropriate.
      if ( curObj && ( fn == NULL || fn( curObj ) ) )
         foundObjects.push_back( curObj );
   }

   // Add this object if appropriate.
   curObj = dynamic_cast<T*>(this);
   if ( curObj && ( fn == NULL || fn( curObj ) ) )
      foundObjects.push_back( curObj );

   unlock();
}

/// An iterator that recursively and exhaustively traverses the contents
/// of a SimSet.
///
/// @see SimSet
class SimSetIterator
{
protected:
   struct Entry {
      SimSet* set;
      SimSet::iterator itr;
   };
   class Stack: public Vector<Entry> {
   public:
      void push_back(SimSet*);
   };
   Stack stack;

public:
   SimSetIterator(SimSet*);
   SimObject* operator++();
   SimObject* operator*() {
      return stack.empty()? 0: *stack.last().itr;
   }
};

//---------------------------------------------------------------------------
/// A group of SimObjects.
///
/// A SimGroup is a stricter form of SimSet. SimObjects may only be a member
/// of a single SimGroup at a time.
///
/// The SimGroup will automatically enforce the single-group-membership rule.
///
/// @code
///      // From engine/sim/simPath.cc - getting a pointer to a SimGroup
///      SimGroup* pMissionGroup = dynamic_cast<SimGroup*>(Sim::findObject("MissionGroup"));
///
///      // From game/trigger.cc:46 - iterating over a SimObject's group.
///      SimObject* trigger = ...;
///      SimGroup* pGroup = trigger->getGroup();
///      for (SimGroup::iterator itr = pGroup->begin(); itr != pGroup->end(); itr++)
///      {
///         // do something with *itr
///      }
/// @endcode
class SimGroup: public SimSet
{
   public:

      typedef SimSet Parent;

      friend class SimManager;
      friend class SimObject;

   private:

      SimNameDictionary mNameDictionary;

      void _addObject( SimObject* object, bool forcePushBack = false );
      void _removeObjectNoLock( SimObject* );

   public:

      ~SimGroup();

      void addObject( SimObject* object, SimObjectId id);
      void addObject( SimObject* object, const char* name );

      // SimSet.
      virtual void addObject( SimObject* object );
      virtual void removeObject( SimObject* object );
      virtual void pushObject( SimObject* object );
      virtual void popObject();
      virtual void clear();

      virtual SimGroup* clone();
      virtual SimGroup* deepClone();

      virtual SimObject* findObject(const char* name);
      virtual void onRemove();

      virtual bool processArguments( S32 argc, ConsoleValue *argv );

      virtual SimObject* getObject(const S32& index);

      DECLARE_CONOBJECT( SimGroup );
};

inline void SimGroup::addObject(SimObject* obj, SimObjectId id)
{
   obj->mId = id;
   dSprintf( obj->mIdString, sizeof( obj->mIdString ), "%u", obj->mId );
   addObject( obj );
}

inline void SimGroup::addObject(SimObject *obj, const char *name)
{
   addObject( obj );
   obj->assignName(name);
}

/// An iterator that recursively and exhaustively traverses all objects
/// in an SimGroup object tree.
class SimGroupIterator: public SimSetIterator
{
public:
   SimGroupIterator(SimGroup* grp): SimSetIterator(grp) {}
   SimObject* operator++();
};

#endif // _SIMSET_H_


text:
package edu.uri.egr.hermessample;

import android.app.Application;

import com.google.android.gms.wearable.Wearable;

import edu.uri.egr.hermes.Hermes;

/**
 * Created by cody on 8/20/15.
 */
public class SampleApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        Hermes.Config config = new Hermes.Config()
                .enableDebug(true)
                .addApi(Wearable.API);

        Hermes.init(this, config);
    }
}


text:
<!doctype html>

    <link rel="stylesheet" type="text/css" href="{{{host}}}/stylesheets/bootstrap.min.css">
    <title>Configure New Relic Application List Tile</title>

Loading...

New Relic Configuration

        Establish connection using API key stored on host middleware ...

    <button class="btn btn-success" id="auth-btn">Submit</button>

    Select the applications you want to monitor ... (future use)

 <button class="btn btn-primary" id="submit">Apply</button>


text:
function VarName1 = importTrace(filename, startRow, endRow)
%IMPORTFILE Import numeric data from a text file as column vectors.
%   VARNAME1 = IMPORTFILE(FILENAME) Reads data from text file FILENAME for
%   the default selection.
%
%   VARNAME1 = IMPORTFILE(FILENAME, STARTROW, ENDROW) Reads data from rows
%   STARTROW through ENDROW of text file FILENAME.
%
% Example:
%   VarName1 = importfile('U1084A001_63323_CH1_125MS_20KPTS.trc',8, 20007);
%
%    See also TEXTSCAN.

% Auto-generated by MATLAB on 2015/07/22 09:45:10

%% Initialize variables.
delimiter = ' ';
if nargin<=2
    startRow = 8;
    endRow = inf;
end

%% Format string for each line of text:
%   column1: double (%f)
% For more information, see the TEXTSCAN documentation.
formatSpec = '%f%*s%[^\n\r]';

%% Open the text file.
fileID = fopen(filename,'r');

%% Read columns of data according to format string.
% This call is based on the structure of the file used to generate this
% code. If an error occurs for a different file, try regenerating the code
% from the Import Tool.
dataArray = textscan(fileID, formatSpec, endRow(1)-startRow(1)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'EmptyValue' ,NaN,'HeaderLines', startRow(1)-1, 'ReturnOnError', false);
for block=2:length(startRow)
    frewind(fileID);
    dataArrayBlock = textscan(fileID, formatSpec, endRow(block)-startRow(block)+1, 'Delimiter', delimiter, 'MultipleDelimsAsOne', true, 'EmptyValue' ,NaN,'HeaderLines', startRow(block)-1, 'ReturnOnError', false);
    dataArray{1} = [dataArray{1};dataArrayBlock{1}];
end

%% Close the text file.
fclose(fileID);

%% Post processing for unimportable data.
% No unimportable data rules were applied during the import, so no post
% processing code is included. To generate code which works for
% unimportable data, select unimportable cells in a file and regenerate the
% script.

%% Allocate imported array to column variable names
VarName1 = dataArray{:, 1};