text:
#ifndef VP9_RTCD_H_
#define VP9_RTCD_H_

#ifdef RTCD_C
#define RTCD_EXTERN
#else
#define RTCD_EXTERN extern
#endif

/*
 * VP9
 */

#include "vpx/vpx_integer.h"
#include "vp9/common/vp9_common.h"
#include "vp9/common/vp9_enums.h"

struct macroblockd;

/* Encoder forward decls */
struct macroblock;
struct vp9_variance_vtable;
struct search_site_config;
struct mv;
union int_mv;
struct yv12_buffer_config;

#ifdef __cplusplus
extern "C" {
#endif

int64_t vp9_block_error_c(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz);
#define vp9_block_error vp9_block_error_c

int vp9_denoiser_filter_c(const uint8_t *sig, int sig_stride, const uint8_t *mc_avg, int mc_avg_stride, uint8_t *avg, int avg_stride, int increase_denoising, BLOCK_SIZE bs, int motion_magnitude);
int vp9_denoiser_filter_sse2(const uint8_t *sig, int sig_stride, const uint8_t *mc_avg, int mc_avg_stride, uint8_t *avg, int avg_stride, int increase_denoising, BLOCK_SIZE bs, int motion_magnitude);
RTCD_EXTERN int (*vp9_denoiser_filter)(const uint8_t *sig, int sig_stride, const uint8_t *mc_avg, int mc_avg_stride, uint8_t *avg, int avg_stride, int increase_denoising, BLOCK_SIZE bs, int motion_magnitude);

int vp9_diamond_search_sad_c(const struct macroblock *x, const struct search_site_config *cfg,  struct mv *ref_mv, struct mv *best_mv, int search_param, int sad_per_bit, int *num00, const struct vp9_variance_vtable *fn_ptr, const struct mv *center_mv);
int vp9_diamond_search_sad_avx(const struct macroblock *x, const struct search_site_config *cfg,  struct mv *ref_mv, struct mv *best_mv, int search_param, int sad_per_bit, int *num00, const struct vp9_variance_vtable *fn_ptr, const struct mv *center_mv);
RTCD_EXTERN int (*vp9_diamond_search_sad)(const struct macroblock *x, const struct search_site_config *cfg,  struct mv *ref_mv, struct mv *best_mv, int search_param, int sad_per_bit, int *num00, const struct vp9_variance_vtable *fn_ptr, const struct mv *center_mv);

void vp9_fdct8x8_quant_c(const int16_t *input, int stride, tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *zbin_ptr, const int16_t *round_ptr, const int16_t *quant_ptr, const int16_t *quant_shift_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan);
#define vp9_fdct8x8_quant vp9_fdct8x8_quant_c

void vp9_fht16x16_c(const int16_t *input, tran_low_t *output, int stride, int tx_type);
void vp9_fht16x16_sse2(const int16_t *input, tran_low_t *output, int stride, int tx_type);
RTCD_EXTERN void (*vp9_fht16x16)(const int16_t *input, tran_low_t *output, int stride, int tx_type);

void vp9_fht4x4_c(const int16_t *input, tran_low_t *output, int stride, int tx_type);
void vp9_fht4x4_sse2(const int16_t *input, tran_low_t *output, int stride, int tx_type);
RTCD_EXTERN void (*vp9_fht4x4)(const int16_t *input, tran_low_t *output, int stride, int tx_type);

void vp9_fht8x8_c(const int16_t *input, tran_low_t *output, int stride, int tx_type);
void vp9_fht8x8_sse2(const int16_t *input, tran_low_t *output, int stride, int tx_type);
RTCD_EXTERN void (*vp9_fht8x8)(const int16_t *input, tran_low_t *output, int stride, int tx_type);

void vp9_filter_by_weight16x16_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int src_weight);
void vp9_filter_by_weight16x16_sse2(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int src_weight);
RTCD_EXTERN void (*vp9_filter_by_weight16x16)(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int src_weight);

void vp9_filter_by_weight8x8_c(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int src_weight);
void vp9_filter_by_weight8x8_sse2(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int src_weight);
RTCD_EXTERN void (*vp9_filter_by_weight8x8)(const uint8_t *src, int src_stride, uint8_t *dst, int dst_stride, int src_weight);

int vp9_full_search_sad_c(const struct macroblock *x, const struct mv *ref_mv, int sad_per_bit, int distance, const struct vp9_variance_vtable *fn_ptr, const struct mv *center_mv, struct mv *best_mv);
int vp9_full_search_sadx3(const struct macroblock *x, const struct mv *ref_mv, int sad_per_bit, int distance, const struct vp9_variance_vtable *fn_ptr, const struct mv *center_mv, struct mv *best_mv);
int vp9_full_search_sadx8(const struct macroblock *x, const struct mv *ref_mv, int sad_per_bit, int distance, const struct vp9_variance_vtable *fn_ptr, const struct mv *center_mv, struct mv *best_mv);
RTCD_EXTERN int (*vp9_full_search_sad)(const struct macroblock *x, const struct mv *ref_mv, int sad_per_bit, int distance, const struct vp9_variance_vtable *fn_ptr, const struct mv *center_mv, struct mv *best_mv);

void vp9_fwht4x4_c(const int16_t *input, tran_low_t *output, int stride);
void vp9_fwht4x4_sse2(const int16_t *input, tran_low_t *output, int stride);
RTCD_EXTERN void (*vp9_fwht4x4)(const int16_t *input, tran_low_t *output, int stride);

int64_t vp9_highbd_block_error_c(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz, int bd);
int64_t vp9_highbd_block_error_sse2(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz, int bd);
RTCD_EXTERN int64_t (*vp9_highbd_block_error)(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz, int bd);

int64_t vp9_highbd_block_error_8bit_c(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz);
int64_t vp9_highbd_block_error_8bit_sse2(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz);
int64_t vp9_highbd_block_error_8bit_avx(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz);
RTCD_EXTERN int64_t (*vp9_highbd_block_error_8bit)(const tran_low_t *coeff, const tran_low_t *dqcoeff, intptr_t block_size, int64_t *ssz);

void vp9_highbd_fht16x16_c(const int16_t *input, tran_low_t *output, int stride, int tx_type);
#define vp9_highbd_fht16x16 vp9_highbd_fht16x16_c

void vp9_highbd_fht4x4_c(const int16_t *input, tran_low_t *output, int stride, int tx_type);
#define vp9_highbd_fht4x4 vp9_highbd_fht4x4_c

void vp9_highbd_fht8x8_c(const int16_t *input, tran_low_t *output, int stride, int tx_type);
#define vp9_highbd_fht8x8 vp9_highbd_fht8x8_c

void vp9_highbd_fwht4x4_c(const int16_t *input, tran_low_t *output, int stride);
#define vp9_highbd_fwht4x4 vp9_highbd_fwht4x4_c

void vp9_highbd_iht16x16_256_add_c(const tran_low_t *input, uint8_t *output, int pitch, int tx_type, int bd);
#define vp9_highbd_iht16x16_256_add vp9_highbd_iht16x16_256_add_c

void vp9_highbd_iht4x4_16_add_c(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type, int bd);
#define vp9_highbd_iht4x4_16_add vp9_highbd_iht4x4_16_add_c

void vp9_highbd_iht8x8_64_add_c(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type, int bd);
#define vp9_highbd_iht8x8_64_add vp9_highbd_iht8x8_64_add_c

void vp9_highbd_mbpost_proc_across_ip_c(uint16_t *src, int pitch, int rows, int cols, int flimit);
#define vp9_highbd_mbpost_proc_across_ip vp9_highbd_mbpost_proc_across_ip_c

void vp9_highbd_mbpost_proc_down_c(uint16_t *dst, int pitch, int rows, int cols, int flimit);
#define vp9_highbd_mbpost_proc_down vp9_highbd_mbpost_proc_down_c

void vp9_highbd_post_proc_down_and_across_c(const uint16_t *src_ptr, uint16_t *dst_ptr, int src_pixels_per_line, int dst_pixels_per_line, int rows, int cols, int flimit);
#define vp9_highbd_post_proc_down_and_across vp9_highbd_post_proc_down_and_across_c

void vp9_highbd_quantize_fp_c(const tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *zbin_ptr, const int16_t *round_ptr, const int16_t *quant_ptr, const int16_t *quant_shift_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan);
#define vp9_highbd_quantize_fp vp9_highbd_quantize_fp_c

void vp9_highbd_quantize_fp_32x32_c(const tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *zbin_ptr, const int16_t *round_ptr, const int16_t *quant_ptr, const int16_t *quant_shift_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan);
#define vp9_highbd_quantize_fp_32x32 vp9_highbd_quantize_fp_32x32_c

void vp9_highbd_temporal_filter_apply_c(uint8_t *frame1, unsigned int stride, uint8_t *frame2, unsigned int block_width, unsigned int block_height, int strength, int filter_weight, unsigned int *accumulator, uint16_t *count);
#define vp9_highbd_temporal_filter_apply vp9_highbd_temporal_filter_apply_c

void vp9_iht16x16_256_add_c(const tran_low_t *input, uint8_t *output, int pitch, int tx_type);
void vp9_iht16x16_256_add_sse2(const tran_low_t *input, uint8_t *output, int pitch, int tx_type);
RTCD_EXTERN void (*vp9_iht16x16_256_add)(const tran_low_t *input, uint8_t *output, int pitch, int tx_type);

void vp9_iht4x4_16_add_c(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type);
void vp9_iht4x4_16_add_sse2(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type);
RTCD_EXTERN void (*vp9_iht4x4_16_add)(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type);

void vp9_iht8x8_64_add_c(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type);
void vp9_iht8x8_64_add_sse2(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type);
RTCD_EXTERN void (*vp9_iht8x8_64_add)(const tran_low_t *input, uint8_t *dest, int dest_stride, int tx_type);

void vp9_quantize_fp_c(const tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *zbin_ptr, const int16_t *round_ptr, const int16_t *quant_ptr, const int16_t *quant_shift_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan);
#define vp9_quantize_fp vp9_quantize_fp_c

void vp9_quantize_fp_32x32_c(const tran_low_t *coeff_ptr, intptr_t n_coeffs, int skip_block, const int16_t *zbin_ptr, const int16_t *round_ptr, const int16_t *quant_ptr, const int16_t *quant_shift_ptr, tran_low_t *qcoeff_ptr, tran_low_t *dqcoeff_ptr, const int16_t *dequant_ptr, uint16_t *eob_ptr, const int16_t *scan, const int16_t *iscan);
#define vp9_quantize_fp_32x32 vp9_quantize_fp_32x32_c

void vp9_temporal_filter_apply_c(uint8_t *frame1, unsigned int stride, uint8_t *frame2, unsigned int block_width, unsigned int block_height, int strength, int filter_weight, unsigned int *accumulator, uint16_t *count);
void vp9_temporal_filter_apply_sse2(uint8_t *frame1, unsigned int stride, uint8_t *frame2, unsigned int block_width, unsigned int block_height, int strength, int filter_weight, unsigned int *accumulator, uint16_t *count);
RTCD_EXTERN void (*vp9_temporal_filter_apply)(uint8_t *frame1, unsigned int stride, uint8_t *frame2, unsigned int block_width, unsigned int block_height, int strength, int filter_weight, unsigned int *accumulator, uint16_t *count);

void vp9_rtcd(void);

#ifdef RTCD_C
#include "vpx_ports/x86.h"
static void setup_rtcd_internal(void)
{
    int flags = x86_simd_caps();

    (void)flags;

    vp9_denoiser_filter = vp9_denoiser_filter_c;
    if (flags & HAS_SSE2) vp9_denoiser_filter = vp9_denoiser_filter_sse2;
    vp9_diamond_search_sad = vp9_diamond_search_sad_c;
    if (flags & HAS_AVX) vp9_diamond_search_sad = vp9_diamond_search_sad_avx;
    vp9_fht16x16 = vp9_fht16x16_c;
    if (flags & HAS_SSE2) vp9_fht16x16 = vp9_fht16x16_sse2;
    vp9_fht4x4 = vp9_fht4x4_c;
    if (flags & HAS_SSE2) vp9_fht4x4 = vp9_fht4x4_sse2;
    vp9_fht8x8 = vp9_fht8x8_c;
    if (flags & HAS_SSE2) vp9_fht8x8 = vp9_fht8x8_sse2;
    vp9_filter_by_weight16x16 = vp9_filter_by_weight16x16_c;
    if (flags & HAS_SSE2) vp9_filter_by_weight16x16 = vp9_filter_by_weight16x16_sse2;
    vp9_filter_by_weight8x8 = vp9_filter_by_weight8x8_c;
    if (flags & HAS_SSE2) vp9_filter_by_weight8x8 = vp9_filter_by_weight8x8_sse2;
    vp9_full_search_sad = vp9_full_search_sad_c;
    if (flags & HAS_SSE3) vp9_full_search_sad = vp9_full_search_sadx3;
    if (flags & HAS_SSE4_1) vp9_full_search_sad = vp9_full_search_sadx8;
    vp9_fwht4x4 = vp9_fwht4x4_c;
    if (flags & HAS_SSE2) vp9_fwht4x4 = vp9_fwht4x4_sse2;
    vp9_highbd_block_error = vp9_highbd_block_error_c;
    if (flags & HAS_SSE2) vp9_highbd_block_error = vp9_highbd_block_error_sse2;
    vp9_highbd_block_error_8bit = vp9_highbd_block_error_8bit_c;
    if (flags & HAS_SSE2) vp9_highbd_block_error_8bit = vp9_highbd_block_error_8bit_sse2;
    if (flags & HAS_AVX) vp9_highbd_block_error_8bit = vp9_highbd_block_error_8bit_avx;
    vp9_iht16x16_256_add = vp9_iht16x16_256_add_c;
    if (flags & HAS_SSE2) vp9_iht16x16_256_add = vp9_iht16x16_256_add_sse2;
    vp9_iht4x4_16_add = vp9_iht4x4_16_add_c;
    if (flags & HAS_SSE2) vp9_iht4x4_16_add = vp9_iht4x4_16_add_sse2;
    vp9_iht8x8_64_add = vp9_iht8x8_64_add_c;
    if (flags & HAS_SSE2) vp9_iht8x8_64_add = vp9_iht8x8_64_add_sse2;
    vp9_temporal_filter_apply = vp9_temporal_filter_apply_c;
    if (flags & HAS_SSE2) vp9_temporal_filter_apply = vp9_temporal_filter_apply_sse2;
}
#endif

#ifdef __cplusplus
}  // extern "C"
#endif

#endif


text:
<?php

namespace Sonata\CacheBundle\Invalidation;

/**
 * @deprecated use Sonata\Cache\Invalidation\InvalidationInterface
 */
interface InvalidationInterface extends \Sonata\Cache\Invalidation\InvalidationInterface
{
}

redpajama_set_name: RedPajamaGithub


text:
'use strict';

const async = require("async");
const lib = {
    "mail": null,
    "pin": require("../../lib/pin.js")
};

let bl = null;
let local = (soajs, inputmaskData, options, cb) => {
    inputmaskData = inputmaskData || {};
    if (!inputmaskData.users) {
        return cb(bl.user.handleError(soajs, 530, null));
    }

    if (!inputmaskData.tenant) {
        inputmaskData.tenant = soajs.tenant;
    }

    let modelObj = bl.user.mt.getModel(soajs);
    options = {};
    options.mongoCore = modelObj.mongoCore;

    let data = {
        //"status": "active"
    };

    let records = {"succeeded": [], "failed": []};
    async.eachLimit(inputmaskData.users, 20, function (oneUser, callback) {

        let goInvite = (error, userRecord, responseObj) => {
            if (error) {
                records.failed.push(responseObj);
                return callback();
            }
            if (userRecord.tenant.id === inputmaskData.tenant.id) {
                responseObj.reason = bl.user.localConfig.errors[536];//"User is already in the tenant tenancy.";
                responseObj.id = userRecord._id;
                records.failed.push(responseObj);
                return callback();
            }
            if (!userRecord.config) {
                userRecord.config = {};
            }
            if (!userRecord.config.allowedTenants) {
                userRecord.config.allowedTenants = [];
            }
            let found = false;
            if (userRecord.config.allowedTenants.length > 0) {
                userRecord.config.allowedTenants.forEach((oneTenant) => {
                    if (oneTenant.tenant && oneTenant.tenant.id && oneTenant.tenant.id === inputmaskData.tenant.id) {
                        found = true;
                    }
                });
            }
            if (found) {
                responseObj.reason = bl.user.localConfig.errors[529];//"User has already been invited.";
                responseObj.id = userRecord._id;
                records.failed.push(responseObj);
                return callback();
            }
            let obj = {
                "tenant": {
                    "id": inputmaskData.tenant.id,
                    "code": inputmaskData.tenant.code
                }
            };
            obj.tenant.pin = {};
            if (oneUser.groups) {
                obj.groups = oneUser.groups;
            } else if (oneUser.membership) {
                let membershipConfig = null;
                if (soajs.servicesConfig && soajs.servicesConfig.urac && soajs.servicesConfig.urac.membership) {
                    if (soajs.servicesConfig.urac.membership[oneUser.membership]) {
                        membershipConfig = soajs.servicesConfig.urac.membership[oneUser.membership];
                    }
                }
                if (!membershipConfig && soajs.registry && soajs.registry.custom && soajs.registry.custom.urac && soajs.registry.custom.urac.value && soajs.registry.custom.urac.value.membership) {
                    if (soajs.registry.custom.urac.value.membership[oneUser.membership]) {
                        membershipConfig = soajs.registry.custom.urac.value.membership[oneUser.membership];
                    }
                }
                if (membershipConfig) {
                    if (membershipConfig.groups) {
                        if (Array.isArray(membershipConfig.groups) && membershipConfig.groups.length > 0) {
                            obj.groups = membershipConfig.groups;
                        } else {
                            soajs.log.warn("Skipping [" + oneUser.membership + "] membership setting, groups must be an array of at least one group");
                        }
                    }
                } else {
                    soajs.log.debug("Skipping [" + oneUser.membership + "] membership, unable to find any setting for it");
                }
            }

            let generatedPin = null;
            if (oneUser.pin && oneUser.pin.code) {
                let pinConfig = lib.pin.config(soajs, bl.user.localConfig);
                try {
                    generatedPin = lib.pin.generate(pinConfig);
                    obj.tenant.pin.code = generatedPin;
                    obj.tenant.pin.allowed = !!oneUser.pin.allowed;
                    if (!userRecord.tenant.pin) {
                        userRecord.tenant.pin = {};
                    }
                    userRecord.tenant.pin.allowed = !!oneUser.pin.allowed;
                } catch (e) {
                    responseObj.reason = "Failed to generate pin at this.";
                    records.failed.push(responseObj);
                    return callback();
                }
            }
            userRecord.config.allowedTenants.push(obj);

            modelObj.save(userRecord, (err, response) => {
                if (err) {
                    responseObj.reason = err.message;
                    records.failed.push(responseObj);
                    return callback();
                }
                if (response && generatedPin) {
                    userRecord.pin = generatedPin;
                    lib.mail.send(soajs, 'invitePin', userRecord, null, function (error) {
                        if (error) {
                            soajs.log.info('invitePin: No Mail was sent: ' + error.message);
                        }
                    });
                }
                records.succeeded.push(responseObj);
                return callback();
            });
        };

        if (oneUser.user.id) {
            let responseObj = {"id": oneUser.user.id};
            data.id = oneUser.user.id;
            data.keep = {"pin": true};
            data.ignoreStatus = true;
            bl.user.getUser(soajs, data, options, (error, userRecord) => {
                return goInvite(error, userRecord, responseObj);
            });
        } else if (oneUser.user.username) {
            let responseObj = {"username": oneUser.user.username};
            data.username = oneUser.user.username;
            data.keep = {"pin": true};
            bl.user.getUserByUsername(soajs, data, options, (error, userRecord) => {
                return goInvite(error, userRecord, responseObj);
            });
        } else if (oneUser.user.email) {
            let responseObj = {"email": oneUser.user.email};
            data.username = oneUser.user.email;
            data.keep = {"pin": true};
            bl.user.getUserByUsername(soajs, data, options, (error, userRecord) => {
                return goInvite(error, userRecord, responseObj);
            });
        } else {
            let responseObj = {"reason": "Cannot invite a user without providing its id or username."};
            records.failed.push(responseObj);
            return callback();
        }
    }, function () {
        //close model
        bl.user.mt.closeModel(modelObj);
        return cb(null, records);
    });
};

module.exports = function (_bl) {
    bl = _bl;
    lib.mail = require("../../lib/mail.js")(bl);
    return local;
};


text:
package com.senacor.core.manager;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import junit.framework.TestCase;

public abstract class ManagerTest<T extends Manager> extends TestCase {
	protected final T manager;
	protected final ManagerFactory managerFactory;

	public ManagerTest() {
		Type[] types = ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments();
		Class<T> clazz = (Class<T>) types[0];
		managerFactory = LocalManagerFactory.getManagerFactory();
		assertNotNull(managerFactory);
		manager = managerFactory.getManager(clazz);
	}
}


text:
<?php
/**
 * Orm
 * @author Petr Procházka (petr@petrp.cz)
 * @license "New" BSD License
 */

namespace Orm;

use RuntimeException;

/**
 * Container is frozen. You can't add or remove his service.
 * @author Petr Procházka
 * @package Orm
 * @subpackage DI\Exceptions
 */
class FrozenContainerException extends RuntimeException
{

}


text:
package eu.hyvar.feature.expression.resource.hyexpression.mopp;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;

public class HyexpressionNewFileContentProvider {

	public eu.hyvar.feature.expression.resource.hyexpression.IHyexpressionMetaInformation getMetaInformation() {
		return new eu.hyvar.feature.expression.resource.hyexpression.mopp.HyexpressionMetaInformation();
	}

	public String getNewFileContent(String newFileName) {
		return getExampleContent(new EClass[] {
			eu.hyvar.feature.expression.HyExpressionPackage.eINSTANCE.getHyExpression(),
		}, getMetaInformation().getClassesWithSyntax(), newFileName);
	}

	protected String getExampleContent(EClass[] startClasses, EClass[] allClassesWithSyntax, String newFileName) {
		String content = "";
		for (EClass next : startClasses) {
			content = getExampleContent(next, allClassesWithSyntax, newFileName);
			if (content.trim().length() > 0) {
				break;
			}
		}
		return content;
	}

	protected String getExampleContent(EClass eClass, EClass[] allClassesWithSyntax, String newFileName) {
		// create a minimal model
		EObject root = new eu.hyvar.feature.expression.resource.hyexpression.util.HyexpressionMinimalModelHelper().getMinimalModel(eClass, allClassesWithSyntax, newFileName);
		if (root == null) {
			// could not create a minimal model. returning an empty document is the best we
			// can do.
			return "";
		}
		// use printer to get text for model
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		eu.hyvar.feature.expression.resource.hyexpression.IHyexpressionTextPrinter printer = getPrinter(buffer);
		try {
			printer.print(root);
		} catch (IOException e) {
			new eu.hyvar.feature.expression.resource.hyexpression.util.HyexpressionRuntimeUtil().logError("Exception while generating example content.", e);
		}
		return buffer.toString();
	}

	public eu.hyvar.feature.expression.resource.hyexpression.IHyexpressionTextPrinter getPrinter(OutputStream outputStream) {
		return getMetaInformation().createPrinter(outputStream, new eu.hyvar.feature.expression.resource.hyexpression.mopp.HyexpressionResource());
	}

}


text:
package br.com.les.calculadora.servlets;

import br.com.les.calculadora.servelets.exceptions.CalculadoraException;

public class BuilderCalculo {

	public static ExecutaCalculo build(String operacao) throws CalculadoraException{
		if ("soma".equals(operacao)) {
			return new Soma();
		} else if ("subtracao".equals(operacao)) {
			return new Subtracao();
		} else if ("divisao".equals(operacao)) {
			return new Divisao();
		} else if ("multiplicacao".equals(operacao)) {
			return new Multiplicao();
		} else if ("exp".equals(operacao)) {
			return new Exponenciacao();
		} else {
			throw new CalculadoraException("Operacao invalida!!!");
		}
	}

}


text:
using System;
using UnityEngine;

#if UNITY_EDITOR
using UnityEditor;
using System.Reflection;
#endif

/// <summary>
/// Abstract controller class
/// It has all the functionality needed to implement your own controls
/// It also has a lot of commentary so you won't get missed
///
/// Also chech the CNAbstractControllerInspector.cs class in the Editor folder, as it uses a custom inspector
/// </summary>
[Serializable]
public abstract class CNAbstractController : MonoBehaviour
{
    // Constants for optimization. We don't need separate strings for every control object
    private const string AxisNameHorizontal = "Horizontal";
    private const string AxisNameVertical = "Vertical";

    // Some neat bitwise enums
    [Flags]
    protected enum AnchorsBase
    {
        Left = 1,
        Right = 2,
        Top = 4,
        Bottom = 8,
    }

    // Combined enums
    public enum Anchors
    {
        LeftTop = AnchorsBase.Left | AnchorsBase.Top,
        LeftBottom = AnchorsBase.Left | AnchorsBase.Bottom,
        RightTop = AnchorsBase.Right | AnchorsBase.Top,
        RightBottom = AnchorsBase.Right | AnchorsBase.Bottom
    }

    // --------------------------------
    // Editor visible public properties
    // --------------------------------

    /// <summary>
    /// Anchor is a place where the controls snap
    /// </summary>
    public Anchors Anchor { get { return _anchor; } set { _anchor = value; } }
    /// <summary>
    /// Axis name which is used with the GetAxis(..) method. It's just like Input.GetAxis(..)
    /// </summary>
    public string AxisNameX { get { return _axisNameX; } set { _axisNameX = value; } }
    /// <summary>
    /// Axis name which is used with the GetAxis(..) method. It's just like Input.GetAxis(..)
    /// </summary>
    public string AxisNameY { get { return _axisNameY; } set { _axisNameY = value; } }
    /// <summary>
    /// Margins set the distance to the screen borders in units. Resolution-independent
    /// </summary>
    public Vector2 Margins { get { return _margins; } set { _margins = value; } }

    // TODO: check whether different touch zones intersect (it can be avoided manually, but little things matter)
    /// <summary>
    ///  Touch zone size indicates how big is the sensitive area of the control
    /// </summary>
    public Vector2 TouchZoneSize { get { return _touchZoneSize; } set { _touchZoneSize = value; } }

    // -------------------
    // Event based control
    // -------------------

    /// <summary>
    /// Fires when the user tweaks the control
    /// </summary>
    public event Action<Vector3, CNAbstractController> ControllerMovedEvent;
    /// <summary>
    /// Fires when the user has just touched the control (the control became active)
    /// </summary>
    public event Action<CNAbstractController> FingerTouchedEvent;
    /// <summary>
    /// Fires when the user has just abandoned the control (the control became inactive)
    /// </summary>
    public event Action<CNAbstractController> FingerLiftedEvent;

    /// <summary>
    /// Simple Transform property, used in runtime, it's more fast than getting the .transform property
    /// </summary>
    protected Transform TransformCache { get; set; }
    /// <summary>
    /// Parent camera is an Orthographical camera where all CNControls are stored
    /// </summary>
    protected Camera ParentCamera { get; set; }
    /// <summary>
    /// Runtime calculated Rect, used for touch position checks
    /// </summary>
    protected Rect CalculatedTouchZone { get; set; }
    /// <summary>
    /// Pretty self-explanatory
    /// </summary>
    protected Vector2 CurrentAxisValues { get; set; }
    /// <summary>
    /// Current captured finger ID
    /// </summary>
    protected int CurrentFingerId { get; set; }
    /// <summary>
    /// Nullable Vector3 for optimization. We can check if we've already found it
    /// </summary>
    protected Vector3? CalculatedPosition { get; set; }
    /// <summary>
    /// Whether the control is currently being tweaked
    /// </summary>
    protected bool IsCurrentlyTweaking { get; set; }

    // --------------
    // Private fields
    // We serialize them and hide them in the inspector
    // so it won't show automatically (we use custom inspectors for the CN Controls)
    // --------------

    [SerializeField]
    [HideInInspector]
    private Anchors _anchor = Anchors.LeftBottom;

    [SerializeField]
    [HideInInspector]
    private string _axisNameX = AxisNameHorizontal;

    [SerializeField]
    [HideInInspector]
    private string _axisNameY = AxisNameVertical;

    [SerializeField]
    [HideInInspector]
    private Vector2 _touchZoneSize = new Vector2(6f, 6f);

    [SerializeField]
    [HideInInspector]
    private Vector2 _margins = new Vector2(3f, 3f);

    /// <summary>
    /// Common method for getting CurrentAxisValues
    /// </summary>
    /// <param name="axisName">Name of the axis</param>
    /// <returns>Float value of a given Axis</returns>
    public virtual float GetAxis(string axisName)
    {
        // If we somehow leave axis names
        if (AxisNameX == null || AxisNameY == null || AxisNameX == String.Empty || AxisNameY == String.Empty)
        {
            throw new UnityException("Input Axis " + axisName + " is not setup");
        }

        if (axisName == AxisNameX)
            return CurrentAxisValues.x;

        if (axisName == AxisNameY)
            return CurrentAxisValues.y;

        throw new UnityException("Input Axis " + axisName + " is not setup");
    }

    /// <summary>
    /// Call this method to temporarily disable the control
    /// It will also hide any control objects
    /// Override to change the behaviour
    /// </summary>
    public virtual void Disable()
    {
        CurrentAxisValues = Vector2.zero;

        gameObject.SetActive(false);
        // Unity defined MonoBehaviour property
        enabled = false;
    }

    /// <summary>
    /// Call this method to enable the control back
    /// It will then respond to Unity callbacks
    /// </summary>
    public virtual void Enable()
    {
        gameObject.SetActive(true);
        // Unity defined MonoBehaviour property
        enabled = true;
    }

    /// <summary>
    /// Neat initialization method
    /// </summary>
    public virtual void OnEnable()
    {
        TransformCache = GetComponent<Transform>();

#if UNITY_EDITOR
        // If we've instantiated the prefab but haven't parented it to a camera
        // Editor only issue
        if (TransformCache.parent == null) return;
#endif

        ParentCamera = TransformCache.parent.GetComponent<Camera>();

        TransformCache.localPosition = InitializePosition();
    }

    /// <summary>
    /// Utility method, finds the touch by it's fingerID, which is often different from it's index in .touches
    /// </summary>
    /// <param name="fingerId">The fingerId to find touch for</param>
    /// <returns>null if no touch found, returns a Touch if it's found</returns>
    protected virtual Touch? GetTouchByFingerId(int fingerId)
    {
#if UNITY_EDITOR
        // If we're in the editor, we also take our mouse as input
        // Let's say it's fingerId is 255;
        if (fingerId == 255)
        {
            return ConstructTouchFromMouseInput();
        }
#endif

        int touchCount = Input.touchCount;

        for (int i = 0; i < touchCount; i++)
        {
            var touch = Input.GetTouch(i);
            if (touch.fingerId == fingerId) return touch;
        }

        // If there's no Touch with the specified fingerId, return null
        return null;
    }

    /// <summary>
    /// Event "callback".
    /// We can't use events in the derived classes
    /// So we should use this method instead
    /// </summary>
    /// <param name="input">Input to pass with an event</param>
    protected virtual void OnControllerMoved(Vector2 input)
    {
        if (ControllerMovedEvent != null)
            ControllerMovedEvent(input, this);
    }

    /// <summary>
    /// Event "callback".
    /// We can't use events in the derived classes
    /// So we should use this method instead
    /// </summary>
    protected virtual void OnFingerTouched()
    {
        if (FingerTouchedEvent != null)
            FingerTouchedEvent(this);
    }

    /// <summary>
    /// Event "callback".
    /// We can't use events in the derived classes
    /// So we should use this method instead
    /// </summary>
    protected virtual void OnFingerLifted()
    {
        if (FingerLiftedEvent != null)
            FingerLiftedEvent(this);
    }

    /// <summary>
    /// Calculates local position based on margins and anchor
    /// </summary>
    /// <returns>Calculated position</returns>
    protected Vector3 InitializePosition()
    {
#if !UNITY_EDITOR
        // If we're not in the editor, we don't need to recalculate it every time we call this method
        if (CalculatedPosition != null)
            return CalculatedPosition.Value;
#endif

#if UNITY_EDITOR
        // Editor error "handling"
        // Happens when you duplicate the joystick in the editor window
        // causes a bit of recursion, but it's ok, it will just try to calculate joystick position twice
        if (ParentCamera == null)
            OnEnable();
#endif
        // Camera based calculations (different aspect ratios)
        float halfHeight = ParentCamera.orthographicSize;
        float halfWidth = halfHeight * ParentCamera.aspect;

        var newPosition = new Vector3(0f, 0f, 0f);

        // Bitwise checks
        // Used to simplify the if - else branching
        if (((int)Anchor & (int)AnchorsBase.Left) != 0)
            newPosition.x = -halfWidth + Margins.x;
        else
            newPosition.x = halfWidth - Margins.x;

        if (((int)Anchor & (int)AnchorsBase.Top) != 0)
            newPosition.y = halfHeight - Margins.y;
        else
            newPosition.y = -halfHeight + Margins.y;

        // Now we can calculate the TouchZone position
        // It's visualizes as green gizmo in the scene view
        CalculatedTouchZone = new Rect(
            TransformCache.position.x - TouchZoneSize.x / 2f,
            TransformCache.position.y - TouchZoneSize.y / 2f,
            TouchZoneSize.x,
            TouchZoneSize.y);

        return newPosition;
    }

    /// <summary>
    /// Common method of resetting the control state and position
    /// It means that we've just lifted our finger
    /// </summary>
    protected virtual void ResetControlState()
    {
        // It's no longer tweaking
        IsCurrentlyTweaking = false;
        // Setting our inner axis values back to zero
        CurrentAxisValues = Vector2.zero;
        // Fire our FingerLiftedEvents
        OnFingerLifted();
    }

    /// <summary>
    /// Common tweak method
    /// Used to provide more encapsulation in the derived classes
    /// Automatically calls the TweakControl method
    /// </summary>
    /// <returns>Whether the Tweak has happend</returns>
    protected virtual bool TweakIfNeeded()
    {
        // Check for touches
        if (IsCurrentlyTweaking)
        {
            // Check this method, it also returns a mouse input if we're in the editor
            Touch? touch = GetTouchByFingerId(CurrentFingerId);
            if (touch == null || touch.Value.phase == TouchPhase.Ended)
            {
                ResetControlState();
                return false;
            }
            TweakControl(touch.Value.position);
            return true;
        }
        return false;
    }

    /// <summary>
    /// If the control is not being tweaked, we need to check
    /// if there's any touch that want's to use this control
    /// </summary>
    /// <param name="capturedTouch">Captured touch.
    /// If no touch has been captured, this param has no sence
    /// Check for return value to see whether it was captured
    /// </param>
    /// <returns>Whether any touch was captured</returns>
    protected virtual bool IsTouchCaptured(out Touch capturedTouch)
    {
        // Some optimization things
        int touchCount = Input.touchCount;

#if UNITY_EDITOR
        // If we're in the editor, we add another touch to the list - the mouse cursor
        int actualTouchCount = touchCount;
        touchCount++;
#endif

        // For every touch out there
        for (int i = 0; i < touchCount; i++)
        {
#if UNITY_EDITOR
            // If we got all touches from Input.GetTouch, we need to feed a new touch based on mouse input
            // Check ConstructTouchFromMouseInput() method for more info
            Touch currentTouch = i >= actualTouchCount ? ConstructTouchFromMouseInput() : Input.GetTouch(i);
#else
            // God bless local variables of value types
            Touch currentTouch = Input.GetTouch(i);
#endif
            // Check if we're interested in this touch
            if (currentTouch.phase == TouchPhase.Began && IsTouchInZone(currentTouch.position))
            {
                // If we are, capture the touch and make it ours
                IsCurrentlyTweaking = true;
                // Store it's finger ID so we can find it later
                CurrentFingerId = currentTouch.fingerId;
                // Fire our FingerTouchedEvent
                OnFingerTouched();

                // Initializing OUT param
                capturedTouch = currentTouch;
                // We don't need to check other touches
                // We also captured our touch, so yes, we return true
                return true;
            }
        }

        // To satisfy the compiler. It shouldn't be used
        capturedTouch = new Touch();
        // We didn't capture any touch
        return false;
    }

    /// <summary>
    /// Utility method, chechks whether the touch is inside the touch zone (green rect)
    /// </summary>
    /// <param name="touchPosition">Current touch position in screen pixels
    /// It converts these pixels to units, so it's totally resolution-independent
    /// </param>
    /// <returns>Whether it's inside of the touch zone</returns>
    private bool IsTouchInZone(Vector2 touchPosition)
    {
        return CalculatedTouchZone.Contains(ParentCamera.ScreenToWorldPoint(touchPosition), false);
    }

    /// <summary>
    /// Custom Tweaking method
    /// Implement it to achieve custom tweaking behaviour
    /// </summary>
    /// <param name="touchPosition">Current touch position in screen pixels
    /// It should convert these pixels to units, it should be totally resolution-independent</param>
    protected abstract void TweakControl(Vector2 touchPosition);

    // Some editor-only stuff. It won't compile to any of the builds
#if UNITY_EDITOR
    /// <summary>
    /// Your old DrawGizmosSelected method
    /// It allows you to change properties of the control in the inspector
    /// - it will recalculate all needed properties
    /// </summary>
    protected virtual void OnDrawGizmosSelected()
    {
        TransformCache = GetComponent<Transform>();
        // We don't need to recalculate the base position
        // Tweaking these things in Playmode won't persist anyway
        if (!EditorApplication.isPlaying)
            TransformCache.localPosition = InitializePosition();

        // Store the Gizmos color to restore everything back once we finish
        Color color = Gizmos.color;
        Gizmos.color = Color.green;

        // It's a local variable for more readability
        Vector3 localRectCenter = new Vector3(
                CalculatedTouchZone.x + CalculatedTouchZone.width / 2f,
                CalculatedTouchZone.y + CalculatedTouchZone.height / 2f,
                TransformCache.position.z);

        Gizmos.DrawWireCube(
            localRectCenter,
            new Vector3(TouchZoneSize.x, TouchZoneSize.y, 0f));

        // Perfect time to restore the original color back
        // It's rarely an issue though
        Gizmos.color = color;
    }

    /// <summary>
    /// Utility method. It gets current MouseInput (left mouse button)
    /// and constructs a Touch with it
    /// </summary>
    /// <returns>Constructed touch</returns>
    private Touch ConstructTouchFromMouseInput()
    {
        // Boxing. Or any of the FieldInfo.SetValue won't work
        object mouseAsTouch = new Touch();

        // Some nasty Reflection stuff
        FieldInfo phaseFieldInfo = mouseAsTouch.GetType().
            GetField("m_Phase", BindingFlags.NonPublic | BindingFlags.Instance);
        FieldInfo positionFieldInfo = mouseAsTouch.GetType().
            GetField("m_Position", BindingFlags.NonPublic | BindingFlags.Instance);
        FieldInfo fingerIdFieldInfo = mouseAsTouch.GetType().
            GetField("m_FingerId", BindingFlags.NonPublic | BindingFlags.Instance);

        // Setting touch phase based on mouse button state
        if (Input.GetMouseButtonDown(0))
            phaseFieldInfo.SetValue(mouseAsTouch, TouchPhase.Began);
        else if (Input.GetMouseButtonUp(0))
            phaseFieldInfo.SetValue(mouseAsTouch, TouchPhase.Ended);
        else
            // We don't check if it's actually moved for simplicity, we don't use Moved / Stationary anyway
            phaseFieldInfo.SetValue(mouseAsTouch, TouchPhase.Moved);

        positionFieldInfo.SetValue(mouseAsTouch, new Vector2(Input.mousePosition.x, Input.mousePosition.y));
        // It has a hardcoded fingerId of 255
        fingerIdFieldInfo.SetValue(mouseAsTouch, 255);

        return (Touch)mouseAsTouch;
    }
#endif
}


text:
from setuptools import setup,Command

from dwml import __version__

class TestCommand(Command):
	user_options = []

	def initialize_options(self):
		pass

	def finalize_options(self):
		pass

	def run(self):
		import sys, subprocess
		raise SystemExit(
		    subprocess.call([sys.executable,
		                     '-Wd',
		                     'tests/test_load.py']))

setup(
	name='dwml',
	version=__version__,
	license='http://www.apache.org/licenses/LICENSE-2.0',
	description='ms-office omml to latex converter',
	author='xilei',
	author_email='xilei125@163.com',
	packages=['dwml'],
	keywords=['word','excel','omml','latex'],
	classifiers=[
		'Development Status :: 4 - Beta',
		'Programming Language :: Python :: 2.7',
		'Programming Language :: Python :: 3',
		'Programming Language :: Python :: 3.3',
		'Programming Language :: Python :: 3.4',
		'Programming Language :: Python :: Implementation :: CPython',
		'Programming Language :: Python :: Implementation :: PyPy',
	],
	cmdclass=dict(test=TestCommand)
	)


text:
import React from "react";

export default class SideBar extends React.Component {
    constructor() {
        super();
    }

    render() {
        return (

                an item

        );
    }
}


text:
<?php

class PanelUserStatWidget extends \yupe\widgets\YWidget
{
    public function run()
    {
        $dataProvider = new CActiveDataProvider('User', array(
            'sort'       => array(
                'defaultOrder' => 'id DESC',
            ),
            'pagination' => array(
                'pageSize' => (int)$this->limit,
            ),
        ));

        $cacheTime = Yii::app()->controller->yupe->coreCacheTime;

        $this->render(
            'panel-stat',
            array(
                'usersCount'    => User::model()->cache($cacheTime)->count(
                        'registration_date >= :time AND registration_date < NOW()',
                        array(':time' => time() - 24 * 60 * 60)
                    ),
                'allUsersCnt'   => User::model()->cache($cacheTime)->count(),
                'registeredCnt' => User::model()->cache($cacheTime)->registered()->count(),
                'dataProvider'  => $dataProvider
            )
        );
    }
}


text:
package entity;

import javax.persistence.Basic;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "products")
public class Product {

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Long id;

	@Basic
	private String name;

	@Basic
	private Double price;

	public Product() {  }

	public Product(String name, Double price) {
		super();
		this.name = name;
		this.price = price;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getNama() {
		return name;
	}

	public void setNama(String name) {
		this.name = name;
	}

	public Double getPrice() {
		return price;
	}

	public void setPrice(Double price) {
		this.price = price;
	}

}


text:
//
//  Created by Aleksander Grzyb on 13/01/15.
//  Copyright (c) 2015 Aleksander Grzyb. All rights reserved.
//

#include "AGMosaicStitcher.h"
#include "AGImageBlender.h"

#include <opencv2/nonfree/features2d.hpp>
#include <cmath>
#include <map>

using namespace cv;
using namespace std;
using namespace detail;

#pragma mark -
#pragma mark Initialization

AGMosaicStitcher::AGMosaicStitcher(const AGParameters &parameters)
{
    this->parameters = parameters;
    this->pathDetection = new AGPathDetection(parameters);
}

void AGMosaicStitcher::initTransformsMatrix(int xSize, int ySize)
{
    for (int x = 0; x < xSize; x++) {
        vector<Mat> nextColumn;
        this->transformsMatrix.push_back(nextColumn);
        for (int y = 0; y < ySize; y++) {
            Mat emptyTransform;
            this->transformsMatrix[x].push_back(emptyTransform);
        }
    }
}

void AGMosaicStitcher::initMaskInImagesMatrix(vector<vector<AGImage>> &imagesMatrix)
{
    for (int x = 0; x < imagesMatrix.size(); x++) {
        for (int y = 0; y < imagesMatrix.front().size(); y++) {
            imagesMatrix[x][y].mask = Mat::ones(imagesMatrix[x][y].image.rows,
                                                imagesMatrix[x][y].image.cols, CV_8UC1) * 255;
        }
    }
}

#pragma mark -
#pragma mark Starting Point

int AGMosaicStitcher::stitchMosaic(vector<vector<AGImage>> &imagesMatrix, Mat &outputImage)
{
    if (imagesMatrix.empty()) {
        return EXIT_FAILURE;
    }
    for (int x = 0; x < imagesMatrix.size(); x++) {
        for (int y = 0; y < imagesMatrix[x].size(); y++) {
            if (!imagesMatrix[x][y].image.data) {
                return EXIT_FAILURE;
            }
        }
    }
    this->testingMode = false;
    this->initTransformsMatrix((int)imagesMatrix.size(), (int)imagesMatrix.front().size());
    this->initMaskInImagesMatrix(imagesMatrix);
    this->pathDetection->detectPaths(imagesMatrix);

//    this->testPathDetection(imagesMatrix);

    this->performStitching(imagesMatrix, outputImage);
//    this->testStitchBetweenTwoImages(imagesMatrix[1][8], imagesMatrix[1][7], Up);
//    this->testStitchBetweenTwoImages(imagesMatrix[0][1], imagesMatrix[0][0], Up);
    return EXIT_SUCCESS;
}

void AGMosaicStitcher::performStitching(vector<vector<AGImage>> &imagesMatrix, Mat &outputImage)
{
    int imageWidth = imagesMatrix.front().front().width;
    int imageHeight = imagesMatrix.front().front().height;

    int midXCoor = floor((imagesMatrix.size() - 1) * 0.5);
    int midYCoor = floor((imagesMatrix.front().size() - 1) * 0.5);

    int offset = 0;
    int outputImageWidth = imageWidth * (int)imagesMatrix.size() + 2 * offset;
    int outputImageHeigth = imageHeight * (int)imagesMatrix.front().size() + 2 * offset;

    outputImage = Mat::zeros(outputImageHeigth, outputImageWidth, CV_8UC4);

    this->xShift = midXCoor * imageWidth + offset;
    this->yShift = midYCoor * imageHeight + offset;

    ImageDirection imageDirection;
    if (imagesMatrix.front().size() > imagesMatrix.size()) {
        for (int x = 0; x < midXCoor; x++) {
            imageDirection = Right;
            this->applyStitchingAlgorithm(imagesMatrix[x][midYCoor], imagesMatrix[x + 1][midYCoor],
                                          imageDirection, this->transformsMatrix[x][midYCoor]);
        }

        for (int x = midXCoor + 1; x < imagesMatrix.size(); x++) {
            imageDirection = Left;
            this->applyStitchingAlgorithm(imagesMatrix[x][midYCoor], imagesMatrix[x - 1][midYCoor],
                                          imageDirection, this->transformsMatrix[x][midYCoor]);
        }

        for (int x = 0; x < imagesMatrix.size(); x++) {
            for (int y = midYCoor - 1; y >= 0; y--) {
                imageDirection = Down;
                this->applyStitchingAlgorithm(imagesMatrix[x][y], imagesMatrix[x][y + 1],
                                              imageDirection, this->transformsMatrix[x][y]);
            }
            for (int y = midYCoor + 1; y < imagesMatrix.front().size(); y++) {
                imageDirection = Up;
                this->applyStitchingAlgorithm(imagesMatrix[x][y], imagesMatrix[x][y - 1],
                                              imageDirection, this->transformsMatrix[x][y]);
            }
        }
    } else {
        for (int y = 0; y < midYCoor; y++) {
            imageDirection = Down;
            this->applyStitchingAlgorithm(imagesMatrix[midXCoor][y], imagesMatrix[midXCoor][y + 1],
                                          imageDirection, this->transformsMatrix[midXCoor][y]);
        }

        for (int y = midYCoor + 1; y < imagesMatrix.front().size(); y++) {
            imageDirection = Up;
            this->applyStitchingAlgorithm(imagesMatrix[midXCoor][y], imagesMatrix[midXCoor][y - 1],
                                          imageDirection, this->transformsMatrix[midXCoor][y]);
        }

        for (int y = 0; y < imagesMatrix.front().size(); y++) {
            for (int x = midXCoor - 1; x >= 0; x--) {
                imageDirection = Right;
                this->applyStitchingAlgorithm(imagesMatrix[x][y], imagesMatrix[x + 1][y],
                                              imageDirection, this->transformsMatrix[x][y]);
            }
            for (int x = midXCoor + 1; x < imagesMatrix.size(); x++) {
                imageDirection = Left;
                this->applyStitchingAlgorithm(imagesMatrix[x][y], imagesMatrix[x - 1][y],
                                              imageDirection, this->transformsMatrix[x][y]);
            }
        }
    }

    // All images need to be shifted to the place where reference image is located
    Mat baseShiftTransform;
    AGOpenCVHelper::createShiftMatrix(baseShiftTransform, this->xShift, this->yShift);
    for (int x = 0; x < imagesMatrix.size(); x++) {
        for (int y = 0; y < imagesMatrix.front().size(); y++) {
            cvtColor(imagesMatrix[x][y].image, imagesMatrix[x][y].image, CV_GRAY2BGRA);
            warpAffine(imagesMatrix[x][y].image, imagesMatrix[x][y].image, baseShiftTransform, outputImage.size());
            warpAffine(imagesMatrix[x][y].mask, imagesMatrix[x][y].mask, baseShiftTransform, outputImage.size());
        }
    }

    // Displaying rest of the images

    for (int x = 0; x < imagesMatrix.size(); x++) {
        for (int y = 0; y < imagesMatrix.front().size(); y++) {
            if (x != midXCoor || y != midYCoor) {
                Mat transformedImage = imagesMatrix[x][y].image;
                Mat mask = imagesMatrix[x][y].mask;
                if (imagesMatrix.front().size() > imagesMatrix.size()) {
                    if (y > midYCoor) {
                        for (int yTrans = y; yTrans > midYCoor; yTrans--) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[x][yTrans],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[x][yTrans], outputImage.size());
                        }
                    } else if (y < midYCoor) {
                        for (int yTrans = y; yTrans < midYCoor; yTrans++) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[x][yTrans],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[x][yTrans], outputImage.size());
                        }
                    }

                    if (x > midXCoor) {
                        for (int xTrans = x; xTrans > midXCoor; xTrans--) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[xTrans][midYCoor],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[xTrans][midYCoor], outputImage.size());
                        }
                    } else if (x < midXCoor) {
                        for (int xTrans = x; xTrans < midXCoor; xTrans++) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[xTrans][midYCoor],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[xTrans][midYCoor], outputImage.size());
                        }
                    }
                } else {
                    if (x > midXCoor) {
                        for (int xTrans = x; xTrans > midXCoor; xTrans--) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[xTrans][y],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[xTrans][y], outputImage.size());
                        }
                    } else if (x < midXCoor) {
                        for (int xTrans = x; xTrans < midXCoor; xTrans++) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[xTrans][y],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[xTrans][y], outputImage.size());
                        }
                    }

                    if (y > midYCoor) {
                        for (int yTrans = y; yTrans > midYCoor; yTrans--) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[midXCoor][yTrans],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[midXCoor][yTrans], outputImage.size());
                        }
                    } else if (y < midYCoor) {
                        for (int yTrans = y; yTrans < midYCoor; yTrans++) {
                            warpAffine(transformedImage, transformedImage, transformsMatrix[midXCoor][yTrans],
                                       outputImage.size());
                            warpAffine(mask, mask, transformsMatrix[midXCoor][yTrans], outputImage.size());
                        }
                    }
                }
//                transformedImage.copyTo(outputImage, mask);
//                addWeighted(transformedImage, 1.0, outputImage, 1.0, 0.0, outputImage);
            }
        }
    }
    //  Displaying reference (unchanged) image on the final grid
//    imagesMatrix[midXCoor][midYCoor].image.copyTo(outputImage, imagesMatrix[midXCoor][midYCoor].mask);
//    addWeighted(imagesMatrix[midXCoor][midYCoor].image, 1.0, outputImage, 1.0, 0.0, outputImage);

    vector<AGImage> imagesToBlend;
    for (auto &imageRow : imagesMatrix) {
        for (auto &image : imageRow) {
            imagesToBlend.push_back(image);
        }
    }

    AGError error;
    AGImageBlender::blendImages(imagesToBlend, outputImage, error);
    if (error.isError) {
        cout << error.description << endl;
    }
}

void AGMosaicStitcher::applyStitchingAlgorithm(AGImage &imageOne,
                                               AGImage &imageTwo,
                                               ImageDirection imageDirection,
                                               Mat &transform)
{
    vector<DMatch> filtredMatches;
    if (this->parameters.isAdHoc) {
        Rect firstHalfImageOneROI;
        Rect secondHalfImageOneROI;

        Rect firstHalfImageTwoROI;
        Rect secondHalfImageTwoROI;

        if (imageDirection == Up || imageDirection == Down) {
            firstHalfImageOneROI = Rect(0, 0, imageOne.width * 0.5, imageOne.height);
            secondHalfImageOneROI = Rect(imageOne.width * 0.5, 0, imageOne.width * 0.5, imageOne.height);

            firstHalfImageTwoROI = Rect(0, 0, imageTwo.width * 0.5, imageTwo.height);
            secondHalfImageTwoROI = Rect(imageTwo.width * 0.5, 0, imageTwo.width * 0.5, imageTwo.height);
        }
        else {
            firstHalfImageOneROI = Rect(0, 0, imageOne.width, imageOne.height * 0.5);
            secondHalfImageOneROI = Rect(0, imageOne.height * 0.5, imageOne.width, imageOne.height * 0.5);

            firstHalfImageTwoROI = Rect(0, 0, imageTwo.width, imageTwo.height * 0.5);
            secondHalfImageTwoROI = Rect(0, imageTwo.height * 0.5, imageTwo.width, imageTwo.height * 0.5);
        }

        Mat firstHalfImageOneMat;
        Mat secondHalfImageOneMat;

        Mat firstHalfImageTwoMat;
        Mat secondHalfImageTwoMat;

        imageOne.image(firstHalfImageOneROI).copyTo(firstHalfImageOneMat);
        imageOne.image(secondHalfImageOneROI).copyTo(secondHalfImageOneMat);

        imageTwo.image(firstHalfImageTwoROI).copyTo(firstHalfImageTwoMat);
        imageTwo.image(secondHalfImageTwoROI).copyTo(secondHalfImageTwoMat);

        string firstHalfImageOneName = imageOne.name;
        firstHalfImageOneName += "_first_half";
        AGImage firstHalfImageOne(firstHalfImageOneMat, imageOne.xCoordinate, imageOne.yCoordinate, firstHalfImageOneROI.width, firstHalfImageOneROI.height, firstHalfImageOneName);

        string secondHalfImageOneName = imageOne.name;
        secondHalfImageOneName += "_second_half";
        AGImage secondHalfImageOne(secondHalfImageOneMat, imageOne.xCoordinate, imageOne.yCoordinate, secondHalfImageOneROI.width, secondHalfImageOneROI.height, secondHalfImageOneName);

        string firstHalfImageTwoName = imageTwo.name;
        firstHalfImageTwoName += "_first_half";
        AGImage firstHalfImageTwo(firstHalfImageTwoMat, imageTwo.xCoordinate, imageTwo.yCoordinate, firstHalfImageTwoROI.width, firstHalfImageTwoROI.height, firstHalfImageTwoName);

        string secondHalfImageTwoName = imageTwo.name;
        secondHalfImageTwoName += "_second_half";
        AGImage secondHalfImageTwo(secondHalfImageTwoMat, imageTwo.xCoordinate, imageTwo.yCoordinate, secondHalfImageTwoROI.width, secondHalfImageTwoROI.height, secondHalfImageTwoName);

        vector<ImageFeatures> firstHalfImagesFeatures;
        vector<ImageFeatures> secondHalfImagesFeatures;

        this->findFeatures(firstHalfImageOne, firstHalfImageTwo, firstHalfImagesFeatures, imageDirection);

        firstHalfImageOne.keypoints = firstHalfImagesFeatures[0].keypoints;
        firstHalfImageTwo.keypoints = firstHalfImagesFeatures[1].keypoints;

        MatchesInfo firstHalfMatchesInfo;
        this->findMatchesWithBruteForce(firstHalfImagesFeatures, firstHalfMatchesInfo);

        this->findFeatures(secondHalfImageOne, secondHalfImageTwo, secondHalfImagesFeatures, imageDirection);

        secondHalfImageOne.keypoints = secondHalfImagesFeatures[0].keypoints;
        secondHalfImageTwo.keypoints = secondHalfImagesFeatures[1].keypoints;

        MatchesInfo secondHalfMatchesInfo;
        this->findMatchesWithBruteForce(secondHalfImagesFeatures, secondHalfMatchesInfo);

        vector<DMatch> firstHalfFiltredMatches;
        this->filterMatches(firstHalfImageOne, firstHalfImageTwo, firstHalfMatchesInfo.matches, firstHalfFiltredMatches, imageDirection);

        vector<DMatch> secondHalfFiltredMatches;
        this->filterMatches(secondHalfImageOne, secondHalfImageTwo, secondHalfMatchesInfo.matches, secondHalfFiltredMatches, imageDirection);

        for (int i = 0; i < firstHalfFiltredMatches.size(); i++) {
            filtredMatches.push_back(firstHalfFiltredMatches[i]);
        }

        for (int i = 0; i < secondHalfFiltredMatches.size(); i++) {
            DMatch newMatch = secondHalfFiltredMatches[i];
            newMatch.queryIdx += firstHalfImageOne.keypoints.size();
            newMatch.trainIdx += firstHalfImageTwo.keypoints.size();
            filtredMatches.push_back(newMatch);
        }

        for (int i = 0; i < firstHalfImageOne.keypoints.size(); i++) {
            imageOne.keypoints.push_back(firstHalfImageOne.keypoints[i]);
        }

        for (int i = 0; i < secondHalfImageOne.keypoints.size(); i++) {
            KeyPoint correctedKeyPoint = secondHalfImageOne.keypoints[i];
            if (imageDirection == Up || imageDirection == Down) {
                correctedKeyPoint.pt.x += firstHalfImageOne.width;
            }
            else {
                correctedKeyPoint.pt.y += firstHalfImageOne.height;
            }
            imageOne.keypoints.push_back(correctedKeyPoint);
        }

        for (int i = 0; i < firstHalfImageTwo.keypoints.size(); i++) {
            imageTwo.keypoints.push_back(firstHalfImageTwo.keypoints[i]);
        }

        for (int i = 0; i < secondHalfImageTwo.keypoints.size(); i++) {
            KeyPoint correctedKeyPoint = secondHalfImageTwo.keypoints[i];
            if (imageDirection == Up || imageDirection == Down) {
                correctedKeyPoint.pt.x += firstHalfImageOne.width;
            }
            else {
                correctedKeyPoint.pt.y += firstHalfImageOne.height;
            }
            imageTwo.keypoints.push_back(correctedKeyPoint);
        }

//        Mat mat;
//        AGOpenCVHelper::linkTwoImagesTogetherAndDrawMatches(imageOne, imageTwo, filtredMatches, mat, imageDirection);
//        AGOpenCVHelper::saveImage(mat, "image");

        vector<KeyPoint> shiftedKeyPoints;
        for (int i = 0; i <= imageOne.keypoints.size(); i++) {
            KeyPoint shiftedKeyPoint = imageOne.keypoints[i];
            shiftedKeyPoint.pt.x += this->xShift;
            shiftedKeyPoint.pt.y += this->yShift;
            shiftedKeyPoints.push_back(shiftedKeyPoint);
        }
        imageOne.keypoints = shiftedKeyPoints;

        for (int i = 0; i <= imageTwo.keypoints.size(); i++) {
            KeyPoint shiftedKeyPoint = imageTwo.keypoints[i];
            shiftedKeyPoint.pt.x += this->xShift;
            shiftedKeyPoint.pt.y += this->yShift;
            imageTwo.keypoints[i] = shiftedKeyPoint;
        }

    }
    else {
        // Finding features
        vector<ImageFeatures> imagesFeatures;

        this->findFeatures(imageOne, imageTwo, imagesFeatures, imageDirection);
        imageOne.keypoints = imagesFeatures[0].keypoints;
        imageTwo.keypoints = imagesFeatures[1].keypoints;

        // Matching features
        MatchesInfo matchesInfo;
        this->findMatchesWithBruteForce(imagesFeatures, matchesInfo);

        // Filtering matches (eliminating outliners)
        this->filterMatches(imageOne, imageTwo, matchesInfo.matches, filtredMatches, imageDirection);

//        Mat mat;
//        AGOpenCVHelper::linkTwoImagesTogetherAndDrawMatches(imageOne, imageTwo, filtredMatches, mat, imageDirection);
//        AGOpenCVHelper::saveImage(mat, "image");
    }

    // Finding transform between images
    this->findTransformBetweenImages(imageOne, imageTwo, filtredMatches, transform, imageDirection);
}

#pragma mark -
#pragma mark Matching Features

void AGMosaicStitcher::findMatchesWithBruteForce(vector<ImageFeatures> &imagesFeatures, MatchesInfo &matchesInfo)
{
    /*
    * Brute Force Matcher is called twice, because he gives different results that depends on which image
    * is passed as train, and which as query. Probably this is because he iterates through all keypoints from query
    * image and makes 1-many relationship to keypoints from train image (we want many-many relationships). As a
    * solution we combine the result from both calls to bfMatcher and later in algorithm we are removing duplicates.
    */

    BFMatcher bfMatcherOne;
    MatchesInfo matchesInfoOne;
    bfMatcherOne.match(imagesFeatures[0].descriptors, imagesFeatures[1].descriptors, matchesInfoOne.matches);

    BFMatcher bfMatcherTwo;
    MatchesInfo matchesInfoTwo;
    bfMatcherTwo.match(imagesFeatures[1].descriptors, imagesFeatures[0].descriptors, matchesInfoTwo.matches);

    for (int i = 0; i < matchesInfoOne.matches.size(); i++) {
        DMatch match;
        match.queryIdx = matchesInfoOne.matches[i].queryIdx;
        match.trainIdx = matchesInfoOne.matches[i].trainIdx;
        match.distance = matchesInfoOne.matches[i].distance;
        matchesInfo.matches.push_back(match);
    }

    for (int i = 0; i < matchesInfoTwo.matches.size(); i++) {
        DMatch match;
        match.queryIdx = matchesInfoTwo.matches[i].trainIdx;
        match.trainIdx = matchesInfoTwo.matches[i].queryIdx;
        match.distance = matchesInfoTwo.matches[i].distance;
        matchesInfo.matches.push_back(match);
    }
}

#pragma mark -
#pragma mark Matches Filtering

void AGMosaicStitcher::filterMatches(AGImage &imageOne,
                                     AGImage &imageTwo,
                                     vector<DMatch> &matches,
                                     vector<DMatch> &filtredMatches,
                                     ImageDirection imageDirection)
{
    if (this->parameters.angleParameter < 0 || this->parameters.angleParameter > 90
        || matches.empty() || !imageOne.image.data || !imageTwo.image.data) {
        return;
    }

    AGError error;
    Mat outputImage;
    if (this->testingMode) {
        AGOpenCVHelper::linkTwoImagesTogetherAndDrawMatches(imageOne,
                                                            imageTwo,
                                                            matches,
                                                            outputImage,
                                                            imageDirection,
                                                            error);
        AGOpenCVHelper::saveImage(outputImage, "no_filtering", this->parameters.mosaicsSaveAbsolutePath, error);
    }

    vector<DMatch> matchesWithinRange;
    this->filterMatchesBasedOnPlacement(imageOne, imageTwo, matches, matchesWithinRange, imageDirection);

    if (this->testingMode) {
        AGOpenCVHelper::linkTwoImagesTogetherAndDrawMatches(imageOne,
                                                            imageTwo,
                                                            matchesWithinRange,
                                                            outputImage,
                                                            imageDirection,
                                                            error);
        AGOpenCVHelper::saveImage(outputImage, "after_on_placement", this->parameters.mosaicsSaveAbsolutePath, error);
    }

    vector<DMatch> matchesWithNoRepetitions;
    this->deleteMatchesFromMultipleKeypointsToMultiple(matchesWithinRange, matchesWithNoRepetitions);

    if (this->testingMode) {
        AGOpenCVHelper::linkTwoImagesTogetherAndDrawMatches(imageOne,
                                                            imageTwo,
                                                            matchesWithNoRepetitions,
                                                            outputImage,
                                                            imageDirection,
                                                            error);
        AGOpenCVHelper::saveImage(outputImage, "after_repetitions", this->parameters.mosaicsSaveAbsolutePath, error);
    }

    vector<DMatch> matchesAfterRANSAC;
    this->filterMatchesUsingRANSAC(imageOne, imageTwo, matchesWithNoRepetitions, matchesAfterRANSAC);

    if (this->testingMode) {
        AGOpenCVHelper::linkTwoImagesTogetherAndDrawMatches(imageOne,
                                                            imageTwo,
                                                            matchesAfterRANSAC,
                                                            outputImage,
                                                            imageDirection,
                                                            error);
        AGOpenCVHelper::saveImage(outputImage, "after_ransac", this->parameters.mosaicsSaveAbsolutePath, error);
    }

    this->filterMatchesBasedOnSlopeAndLength(imageOne, imageTwo, matchesAfterRANSAC, filtredMatches, imageDirection);

    if (this->testingMode) {
        AGOpenCVHelper::linkTwoImagesTogetherAndDrawMatches(imageOne,
                                                            imageTwo,
                                                            filtredMatches,
                                                            outputImage,
                                                            imageDirection,
                                                            error);
        AGOpenCVHelper::saveImage(outputImage,
                                  "after_slope_and_length",
                                  this->parameters.mosaicsSaveAbsolutePath,
                                  error);
    }
}

// Calculates angle between matches and x axis, then calculates the median angle of all matches, and deletes that ones that have angle greater than angleParameter
void AGMosaicStitcher::filterMatchesBasedOnSlopeAndLength(AGImage &imageOne,
                                                          AGImage &imageTwo,
                                                          vector<DMatch> &matches,
                                                          vector<DMatch> &filtredMatches,
                                                          ImageDirection imageDirection)
{
    if (matches.empty() || imageOne.keypoints.empty() || imageTwo.keypoints.empty()) {
        return;
    }
    vector<double> angles;
//    vector<double> lengths;
    vector<pair<int, double>> matchIndexAnglePair;
    for (int i = 0; i < matches.size(); i++) {
        Point pointOne = imageOne.keypoints[matches[i].queryIdx].pt;
        Point pointTwo = imageTwo.keypoints[matches[i].trainIdx].pt;
        if (imageDirection == Up || imageDirection == Down) {
            pointTwo.y += imageOne.height;
        }
        else {
            pointTwo.x += imageOne.width;
        }
        pointTwo.y *= -1;
        pointOne.y *= -1;

        vector<double> coeff;
        AGOpenCVHelper::linearFunctionCoeffsUsingPoints(pointOne, pointTwo, coeff);
//        lengths.push_back(AGOpenCVHelper::distanceBetweenPoints(pointOne, pointTwo));
        double angle = atan(coeff[A_COEFF]) * 180 / M_PI;
        if (angle < 0) {
            angle += 180;
        }
        else if (angle == 0) {
            angle = 90;
        }
        angles.push_back(angle);
    }

    if (this->parameters.clustering) {
        vector<double> lengthsCluster;
        vector<double> anglesCluster;
//        this->clusterArrayWithinRange(lengths, lengthsCluster, this->parameters.lengthParameter);
        this->clusterArrayWithinRange(angles, anglesCluster, this->parameters.angleParameter);

        //        cout << "Angle Cluster" << endl;
        //        for (int i = 0; i < anglesCluster.size(); i++) {
        //            cout << i << ": " << anglesCluster[i] << endl;
        //        }
        //        cout << "-------" << endl;
        //        cout << "Length Cluster" << endl;
        //        for (int i = 0; i < lengthsCluster.size(); i++) {
        //            cout << i << ": " << lengthsCluster[i] << endl;
        //        }
        //        cout << "-------" << endl;

        for (int i = 0; i < matches.size(); i++) {
            for (int a = 0; a < anglesCluster.size(); a++) {
                if (angles[i] == anglesCluster[a]) {
                    for (int b = 0; b < lengthsCluster.size(); b++) {
//                        if (lengths[i] == lengthsCluster[b]) {
                            //                            cout << "Angle " << angles[i] << " Length " << lengths[i] << endl;
                        filtredMatches.push_back(matches[i]);
//                        }
                    }
                }
            }
        }
    }
    else {
        vector<double> anglesCopy = angles;
        sort(anglesCopy.begin(), anglesCopy.end());
        double medianAngle = anglesCopy[floor(angles.size() * 0.5)];

//        vector<double> lengthCopy = lengths;
//        sort(lengthCopy.begin(), lengthCopy.end());
//        double medianLength = lengthCopy[floor(lengths.size() * 0.5)];

        //        cout << "Median both" << endl;
        for (int i = 0; i < matches.size(); i++) {
            if (angles[i] > medianAngle - this->parameters.angleParameter
                && angles[i] < medianAngle + this->parameters.angleParameter) {
//                if (lengths[i] > medianLength - this->parameters.lengthParameter && lengths[i] < medianLength + this->parameters.lengthParameter) {
                    //                    cout << "Angle " << angles[i] << " Length " << lengths[i] << endl;
                    filtredMatches.push_back(matches[i]);
//                }
            }
        }
        //        cout << "Median angle: " << medianAngle << endl;
        //        cout << "Median length: " << medianLength << endl;
    }

    //    for (int i = 0; i < lengths.size(); i++) {
    //        cout << i << ": " << lengths[i] << ";" << angles[i] << endl;
    //    }
}

// Filtering matches based on coordinates x or y. The main idea is that images cannot be shifted too far from each other. You can control the allowed shift by error paramter (expressed in percentage)
void AGMosaicStitcher::filterMatchesBasedOnPlacement(AGImage &imageOne,
                                                     AGImage &imageTwo,
                                                     vector<DMatch> &matches,
                                                     vector<DMatch> &filtredMatches,
                                                     ImageDirection imageDirection)
{
    if (matches.empty() || !imageOne.image.data || !imageTwo.image.data
        || this->parameters.shiftParameter > 1.0 || this->parameters.shiftParameter < 0.0) {
        return;
    }
    for (int i = 0; i < matches.size(); i++) {
        Point pointOne = imageOne.keypoints[matches[i].queryIdx].pt;
        Point pointTwo = imageTwo.keypoints[matches[i].trainIdx].pt;
        bool inRange = false;
        if (imageDirection == Up || imageDirection == Down) {
            if (abs(pointOne.x - pointTwo.x) < imageOne.width * this->parameters.shiftParameter) {
                inRange = true;
            }
        }
        else {
            if (abs(pointOne.y - pointTwo.y) < imageOne.height * this->parameters.shiftParameter) {
                inRange = true;
            }
        }
        if (inRange) {
            double distance = 0.0;
            switch (imageDirection) {
                case Up:
                    distance = sqrt(pow(abs(pointTwo.x - pointOne.x), 2.0) +
                                    pow(abs((pointOne.y + imageTwo.height) -pointTwo.y), 2.0));
                    break;

                case Down:
                    distance = sqrt(pow(abs(pointTwo.x - pointOne.x), 2.0) +
                                    pow(abs((pointTwo.y + imageOne.height) - pointOne.y), 2.0));
                    break;

                case Left:
                    distance = sqrt(pow(abs((pointOne.x + imageTwo.width) - pointTwo.x), 2.0) +
                                    pow(abs(pointTwo.y - pointOne.y), 2.0));
                    break;

                case Right:
                    distance = sqrt(pow(abs((pointTwo.x + imageOne.width) - pointOne.x), 2.0) +
                                    pow(abs(pointTwo.y - pointOne.y), 2.0));
                    break;
            }
            if (distance < imageOne.height * this->parameters.percentOverlap * 2.5) {
                filtredMatches.push_back(matches[i]);
            }
        }
    }
}

// Finding features that were matched to more than one feature and chosing the one with the minimum distance
void AGMosaicStitcher::deleteMatchesFromMultipleKeypointsToMultiple(vector<DMatch> &matches,
                                                                    vector<DMatch> &filtredMatches)
{
    if (matches.empty()) {
        return;
    }

    // Firstly we need to delete multiple matches from keypoints from first image and then we
    // need to delete multiple matches from keypoints from second image.
    vector<DMatch> matchesAfterFirstDeletion;

    // First deletion
    map<int, vector<DMatch>> repetitions;
    for (int i = 0; i < matches.size(); i++) {
        repetitions[matches[i].trainIdx].push_back(matches[i]);
    }
    map<int, vector<DMatch>>::iterator it = repetitions.begin();
    for (it = repetitions.begin(); it != repetitions.end(); ++it) {
        if (it->second.size() > 1) {
            float minDistance = 1000;
            int minIndex = 0;
            for (int i = 0; i < it->second.size(); i++) {
                if (minDistance < it->second[i].distance) {
                    minDistance = it->second[i].distance;
                    minIndex = i;
                }
            }
            matchesAfterFirstDeletion.push_back(it->second[minIndex]);
        }
        else {
            matchesAfterFirstDeletion.push_back(it->second.front());
        }
    }

    // Second deletion
    repetitions.clear();
    for (int i = 0; i < matchesAfterFirstDeletion.size(); i++) {
        repetitions[matchesAfterFirstDeletion[i].queryIdx].push_back(matchesAfterFirstDeletion[i]);
    }
    it = repetitions.begin();
    for (it = repetitions.begin(); it != repetitions.end(); ++it) {
        if (it->second.size() > 1) {
            float minDistance = 1000;
            int minIndex = 0;
            for (int i = 0; i < it->second.size(); i++) {
                if (minDistance < it->second[i].distance) {
                    minDistance = it->second[i].distance;
                    minIndex = i;
                }
            }
            filtredMatches.push_back(it->second[minIndex]);
        }
        else {
            filtredMatches.push_back(it->second.front());
        }
    }
}

void AGMosaicStitcher::filterMatchesUsingRANSAC(AGImage &imageOne,
                                                AGImage &imageTwo,
                                                vector<DMatch> &matches,
                                                vector<DMatch> &filtredMatches)
{
    if (matches.empty()) {
//        cerr << "Couldn't perform RANSAC. Matches vector is empty." << endl;
        return;
    }
    vector<Point2f> imageOneKeypoints;
    vector<Point2f> imageTwoKeypoints;
    for (int i = 0; i < matches.size(); i++) {
        Point2f pointOne = imageOne.keypoints[matches[i].queryIdx].pt;
        imageOneKeypoints.push_back(pointOne);
        Point2f pointTwo = imageTwo.keypoints[matches[i].trainIdx].pt;
        imageTwoKeypoints.push_back(pointTwo);
    }
    Mat mask;
    if (imageTwoKeypoints.size() >= 4 && imageOneKeypoints.size() >= 4) {
        Mat homography = findHomography(imageTwoKeypoints, imageOneKeypoints, CV_RANSAC, 3, mask);
        for (int i = 0; i < matches.size(); i++) {
            if((unsigned int)mask.at<uchar>(i)) {
                filtredMatches.push_back(matches[i]);
            }
        }
    }
    else {
        for (int i = 0; i < matches.size(); i++) {
            filtredMatches.push_back(matches[i]);
        }
    }
}

#pragma mark -
#pragma mark Features Extraction

void AGMosaicStitcher::findFeatures(AGImage &imageOne,
                                    AGImage &imageTwo,
                                    vector<ImageFeatures> &imagesFeatures,
                                    ImageDirection imageDirection)
{
    Rect roiImageOne, roiImageTwo;
    ImageFeatures imageOneFeatures, imageTwoFeatures;
    imagesFeatures.clear();

    switch (imageDirection) {
        case Up:
            roiImageOne = Rect(0, 0, imageOne.width, (double)imageOne.height * this->parameters.percentOverlap);
            roiImageTwo = Rect(0, (double)imageTwo.height * (1.0 - this->parameters.percentOverlap),
                               imageTwo.width, (double)imageTwo.height * this->parameters.percentOverlap);
            break;

        case Down:
            roiImageOne = Rect(0, (double)imageOne.height * (1.0 - this->parameters.percentOverlap),
                               imageOne.width, imageOne.height * this->parameters.percentOverlap);
            roiImageTwo = Rect(0, 0, imageTwo.width, (double)imageTwo.height * this->parameters.percentOverlap);
            break;

        case Left:
            roiImageOne = Rect(0, 0, (double)imageTwo.width * this->parameters.percentOverlap, imageTwo.height);
            roiImageTwo = Rect((double)imageTwo.width * (1.0 - this->parameters.percentOverlap),
                               0, (double)imageTwo.width * this->parameters.percentOverlap, imageTwo.height);
            break;

        case Right:
            roiImageOne = Rect((double)imageTwo.width * (1.0 - this->parameters.percentOverlap),
                               0, (double)imageOne.width * this->parameters.percentOverlap, imageOne.height);
            roiImageTwo = Rect(0, 0, (double)imageTwo.width * this->parameters.percentOverlap, imageTwo.height);
            break;
    }

    this->findFeaturesWithSIFT(imageOne, imageOneFeatures, roiImageOne);
    this->findFeaturesWithSIFT(imageTwo, imageTwoFeatures, roiImageTwo);

    if (!this->parameters.isAdHoc) {
        for (int i = 0; i <= imageOneFeatures.keypoints.size(); i++) {
            KeyPoint keyPoint = imageOneFeatures.keypoints[i];
            keyPoint.pt.x = keyPoint.pt.x + this->xShift;
            keyPoint.pt.y = keyPoint.pt.y + this->yShift;
            imageOneFeatures.keypoints[i] = keyPoint;
        }

        for (int i = 0; i <= imageTwoFeatures.keypoints.size(); i++) {
            KeyPoint keyPoint = imageTwoFeatures.keypoints[i];
            keyPoint.pt.x = keyPoint.pt.x + this->xShift;
            keyPoint.pt.y = keyPoint.pt.y + this->yShift;
            imageTwoFeatures.keypoints[i] = keyPoint;
        }
    }

    imagesFeatures.push_back(imageOneFeatures);
    imagesFeatures.push_back(imageTwoFeatures);
}

void AGMosaicStitcher::findFeaturesWithSIFT(AGImage &inputImage, ImageFeatures &imageFeatures, Rect &roi)
{
    SIFT featuresFinder = SIFT::SIFT(0, 3, 0.02, 10, 1.5);
//    SiftFeatureDetector featuresFinder = SiftFeatureDetector(0, 3, 0.04, 10, 1.5);
    Mat mask = Mat::zeros(inputImage.image.size(), CV_8UC1);
    Mat roin(mask, roi);
    roin = Scalar(255, 255, 255);
    featuresFinder(inputImage.image, mask, imageFeatures.keypoints, imageFeatures.descriptors);
}

#pragma mark -
#pragma mark Computing Transform

void AGMosaicStitcher::findTransformBetweenImages(AGImage &imageOne,
                                                  AGImage &imageTwo,
                                                  vector<DMatch> &matches,
                                                  Mat &transform,
                                                  ImageDirection imageDirection)
{
    vector<Point2f> imageOneSelectedKeypoints;
    vector<Point2f> imageTwoSelectedKeypoints;
    for (int i = 0; i < matches.size(); i++) {
        Point2f pointOne = imageOne.keypoints[matches[i].queryIdx].pt;
        imageOneSelectedKeypoints.push_back(pointOne);

        Point2f pointTwo = imageTwo.keypoints[matches[i].trainIdx].pt;
        imageTwoSelectedKeypoints.push_back(pointTwo);
    }

    // finding transform between images based on detected blood vessels paths
    if (this->parameters.usePaths && this->findTransformBasedOnPaths(imageOne, imageTwo, transform, imageDirection)) {
        AGError error;
        cout << "Path based transform between images: " << endl;
        cout << "1. " << AGOpenCVHelper::getDescriptionOfImage(imageOne, error) << endl;
        cout << "2. " << AGOpenCVHelper::getDescriptionOfImage(imageTwo, error) << endl << endl;
        return;
    }

    // simply shifting image when there is no keypoints detected
    if ((imageOneSelectedKeypoints.empty() || imageTwoSelectedKeypoints.empty())) {
        AGError error;
        cout << "Lack of keypoints in one of the images. Shifting images:" << endl;
        cout << "1. " << AGOpenCVHelper::getDescriptionOfImage(imageOne, error) << endl;
        cout << "2. " << AGOpenCVHelper::getDescriptionOfImage(imageTwo, error) << endl << endl;
        this->findShiftTransform(imageOne, imageTwo, transform, imageDirection);
        return;
    }

    // there are two ways of finding right transform, the first one is to use OpenCV method called
    // estimateRigitTransform(), and the second one just transform image based on mean Y difference and
    // mean X difference
    if (this->parameters.simplerTransform) {
        double meanXDiff = 0.0, meanYDiff = 0.0;
        double sumXDiff = 0.0, sumYDiff = 0.0;
        for (int i = 0; i < matches.size(); i++) {
            sumXDiff += imageTwoSelectedKeypoints[i].x - imageOneSelectedKeypoints[i].x;
            sumYDiff += imageTwoSelectedKeypoints[i].y - imageOneSelectedKeypoints[i].y;
        }
        meanXDiff = sumXDiff / matches.size();
        meanYDiff = sumYDiff / matches.size();
        AGOpenCVHelper::createShiftMatrix(transform, meanXDiff, meanYDiff);
        AGError error;
        cout << "Found simpler transform. Transforming images: " << endl;
        cout << "1. " << AGOpenCVHelper::getDescriptionOfImage(imageOne, error) << endl;
        cout << "2. " << AGOpenCVHelper::getDescriptionOfImage(imageTwo, error) << endl << endl;
        return;
    }
    else if (this->parameters.rigidTransform) {
        transform = estimateRigidTransform(imageOneSelectedKeypoints, imageTwoSelectedKeypoints, false);
    }

    if (transform.cols != 3 || transform.rows != 2) {
        AGError error;
        cout << "Found transform is invalid. Shifting images:" << endl;
        cout << "1. " << AGOpenCVHelper::getDescriptionOfImage(imageOne, error) << endl;
        cout << "2. " << AGOpenCVHelper::getDescriptionOfImage(imageTwo, error) << endl << endl;
        this->findShiftTransform(imageOne, imageTwo, transform, imageDirection);
        return;
    }

    AGError error;
    cout << "Found rigid transform. Transforming images:" << endl;
    cout << "1. " << AGOpenCVHelper::getDescriptionOfImage(imageOne, error) << endl;
    cout << "2. " << AGOpenCVHelper::getDescriptionOfImage(imageTwo, error) << endl << endl;
}

bool AGMosaicStitcher::findTransformBasedOnPaths(AGImage &imageOne,
                                                 AGImage &imageTwo,
                                                 Mat &transform,
                                                 ImageDirection imageDirection)
{
    bool transformFound = false;
    if (!imageOne.pathPoints.empty() && !imageTwo.pathPoints.empty()) {
        Point imageOnePoint, imageTwoPoint;
        double deltaX, deltaY;
        switch (imageDirection) {
            case Up:
                if (!selectPointFromPath(imageTwo, Down, imageTwoPoint)
                    || !selectPointFromPath(imageOne, Up, imageOnePoint)) {
                    return false;
                }
                if(abs(double(imageOnePoint.x) - double(imageTwoPoint.x)) > PATH_RANGE) {
                    return false;
                }
                deltaX = -(double(imageOnePoint.x) - double(imageTwoPoint.x));
                deltaY = imageOne.height * (1 - this->parameters.percentOverlap);
                break;

            case Down:
                if (!selectPointFromPath(imageTwo, Up, imageTwoPoint)
                    || !selectPointFromPath(imageOne, Down, imageOnePoint)) {
                    return false;
                }
                if(abs(double(imageOnePoint.x) - double(imageTwoPoint.x)) > PATH_RANGE) {
                    return false;
                }
                deltaX = -(double(imageOnePoint.x) - double(imageTwoPoint.x));
                deltaY = -imageOne.height * (1 - this->parameters.percentOverlap);
                break;

            case Left:
                if (!selectPointFromPath(imageOne, Left, imageOnePoint)
                    || !selectPointFromPath(imageTwo, Right, imageTwoPoint)) {
                    return false;
                }
                if (abs(double(imageOnePoint.y) - double(imageTwoPoint.y)) > PATH_RANGE) {
                    return false;
                }
                deltaX = imageOne.width * (1 - this->parameters.percentOverlap);
                deltaY = -(double(imageOnePoint.y) - double(imageTwoPoint.y));
                break;

            case Right:
                if (!selectPointFromPath(imageOne, Right, imageOnePoint)
                    || !selectPointFromPath(imageTwo, Left, imageTwoPoint)) {
                    return false;
                }
                if (abs(double(imageOnePoint.y) - double(imageTwoPoint.y)) > PATH_RANGE) {
                    return false;
                }
                deltaX = -imageOne.width * (1 - this->parameters.percentOverlap);
                deltaY = -(double(imageOnePoint.y) - double(imageTwoPoint.y));
                break;
        }
        AGOpenCVHelper::createShiftMatrix(transform, deltaX, deltaY);
        transformFound = true;
    }
    return transformFound;
}

bool AGMosaicStitcher::selectPointFromPath(AGImage &image, ImageDirection desiredPlace, Point &point)
{
    bool pointSelected = false;
    point.x = image.width;
    point.y = image.height;
    for (int i = 0; i < image.pathPoints.size(); ++i) {
        switch (desiredPlace) {
            case Up:
                if (image.pathPoints[i].y == 0 && image.pathPoints[i].x < point.x) {
                    point = image.pathPoints[i];
                    pointSelected = true;
                }
                break;

            case Down:
                if (image.pathPoints[i].y == image.height - 1 && image.pathPoints[i].x < point.x) {
                    point = image.pathPoints[i];
                    pointSelected = true;
                }
                break;

            case Left:
                if (image.pathPoints[i].x == 0 && image.pathPoints[i].y < point.y) {
                    point = image.pathPoints[i];
                    pointSelected = true;
                }
                break;

            case Right:
                if (image.pathPoints[i].x == image.width - 1 && image.pathPoints[i].y < point.y) {
                    point = image.pathPoints[i];
                    pointSelected = true;
                }
                break;
        }
    }
    return pointSelected;
}

void AGMosaicStitcher::findShiftTransform(AGImage &imageOne,
                                          AGImage &imageTwo,
                                          Mat &transform,
                                          ImageDirection imageDirection)
{
    switch (imageDirection) {
        case Up:
            AGOpenCVHelper::createShiftMatrix(transform, 0.0, imageOne.height * (1 - this->parameters.percentOverlap));
            break;
        case Down:
            AGOpenCVHelper::createShiftMatrix(transform, 0.0, -imageOne.height * (1 - this->parameters.percentOverlap));
            break;
        case Left:
            AGOpenCVHelper::createShiftMatrix(transform, imageOne.width * (1 - this->parameters.percentOverlap), 0.0);
            break;
        case Right:
            AGOpenCVHelper::createShiftMatrix(transform, -imageOne.width * (1 - this->parameters.percentOverlap), 0.0);
            break;
    }
}

#pragma mark -
#pragma mark Helper Methods

void AGMosaicStitcher::clusterArrayWithinRange(vector<double> &array, vector<double> &output, double rangeParameter)
{
    vector<double> sortedArray = array;
    sort(sortedArray.begin(), sortedArray.end());
    vector<double> actualRange;
    int rangeStartIndex = 0, rangeEndIndex = 0;
    int startIndex = 0, endIndex = 1;

    if (sortedArray.size() == 1) {
        output.push_back(sortedArray[0]);
    }
    while (endIndex < sortedArray.size() && sortedArray.size() > 1) {
        actualRange.clear();
        for (int i = startIndex; i <= endIndex; i++) {
            actualRange.push_back(sortedArray[i]);
        }
        double maximumElement = 0;
        double minimumElement = 180;

        for (int i = 0; i < actualRange.size(); i++) {
            if (actualRange[i] >= maximumElement) {
                maximumElement = actualRange[i];
            }
        }

        for (int i = 0; i < actualRange.size(); i++) {
            if (actualRange[i] <= minimumElement) {
                minimumElement = actualRange[i];
            }
        }

        if (maximumElement - minimumElement <= rangeParameter) {
            if (endIndex - startIndex > rangeEndIndex - rangeStartIndex) {
                rangeStartIndex = startIndex;
                rangeEndIndex = endIndex;
            }
            endIndex++;
        }
        else {
            startIndex++;
            endIndex = startIndex + 1;
        }
    }

    for (int i = startIndex; i < endIndex; i++) {
        output.push_back(sortedArray[i]);
    }
}

#pragma mark -
#pragma mark Testing

void AGMosaicStitcher::testStitchBetweenTwoImages(AGImage &imageOne, AGImage &imageTwo, ImageDirection imageDirection)
{
    this->xShift = 0;
    this->yShift = 0;
    this->testingMode = false;

    Mat output, transform;
    this->applyStitchingAlgorithm(imageOne, imageTwo, imageDirection, transform);

    switch (imageDirection) {
        case Up:
        {
            output = Mat::zeros(imageOne.image.rows * 2, imageOne.image.cols, imageOne.image.type());
            warpAffine(imageOne.image, output, transform, output.size());
            imageTwo.image.copyTo(output(Rect(0, 0, imageTwo.image.cols, imageTwo.image.rows)));
        }
        break;
        case Down:
        {
            output = Mat::zeros(imageOne.image.rows * 2, imageOne.image.cols, imageOne.image.type());
            int rows = imageOne.image.rows;
            Mat baseShiftTransform;
            AGOpenCVHelper::createShiftMatrix(baseShiftTransform, 0, imageOne.height);
            warpAffine(imageOne.image, imageOne.image, baseShiftTransform, output.size());
            warpAffine(imageOne.image, output, transform, output.size());
            imageTwo.image.copyTo(output(Rect(0, rows, imageTwo.image.cols, imageTwo.image.rows)));
        }
        break;
        case Left:
        {
            output = Mat::zeros(imageOne.image.rows, imageOne.image.cols * 2, imageOne.image.type());
            warpAffine(imageOne.image, output, transform, output.size());
            imageTwo.image.copyTo(output(Rect(0, 0, imageTwo.image.cols, imageTwo.image.rows)));
        }
        break;
        case Right:
        {
            output = Mat::zeros(imageOne.image.rows, imageOne.image.cols * 2, imageOne.image.type());
            int cols = imageOne.image.cols;
            Mat baseShiftTransform;
            AGOpenCVHelper::createShiftMatrix(baseShiftTransform, imageOne.width, 0);
            warpAffine(imageOne.image, imageOne.image, baseShiftTransform, output.size());
            warpAffine(imageOne.image, output, transform, output.size());
            imageTwo.image.copyTo(output(Rect(cols, 0, imageTwo.image.cols, imageTwo.image.rows)));
        }
        break;
    }
    string windowName = "Stitch testing. Transformed ";
    windowName += imageOne.name;
    windowName += " reference ";
    windowName += imageTwo.name;
    AGError error;
    AGOpenCVHelper::saveImage(output, windowName.c_str(), this->parameters.mosaicsSaveAbsolutePath, error);
}

void AGMosaicStitcher::testPathDetection(vector<vector<AGImage>> &imagesMatrix)
{
    for (int x = 0; x < imagesMatrix.size(); x++) {
        for (int y = 0; y < imagesMatrix.front().size(); y++) {
            Mat outputImage;
            this->pathDetection->prepareForPathDetecting(imagesMatrix[x][y].image, outputImage);
            string imageName = to_string(x) + to_string(y);
            AGError error;
            AGOpenCVHelper::saveImage(outputImage, imageName, this->parameters.mosaicsSaveAbsolutePath, error);
        }
    }
}


text:
import * as L from 'leaflet';
import { IGeocoder, GeocoderOptions, GeocodingCallback } from './api';
export interface ArcGisOptions extends GeocoderOptions {
}
/**
 * Implementation of the [ArcGIS geocoder](https://developers.arcgis.com/features/geocoding/)
 */
export declare class ArcGis implements IGeocoder {
    options: ArcGisOptions;
    constructor(options?: Partial<ArcGisOptions>);
    geocode(query: string, cb: GeocodingCallback, context?: any): void;
    suggest(query: string, cb: GeocodingCallback, context?: any): void;
    reverse(location: L.LatLngLiteral, scale: number, cb: GeocodingCallback, context?: any): void;
}
/**
 * [Class factory method](https://leafletjs.com/reference.html#class-class-factories) for {@link ArcGis}
 * @param options the options
 */
export declare function arcgis(options?: Partial<ArcGisOptions>): ArcGis;


text:
package xmlrpc

import (
	"fmt"
)

// xmlrpcError represents errors returned on xmlrpc request.
type xmlrpcError struct {
	code int
	err  string
}

// Error() method implements Error interface
func (e *xmlrpcError) Error() string {
	return fmt.Sprintf("error: \"%s\" code: %d", e.err, e.code)
}

// Base64 represents value in base64 encoding
type Base64 string