text:
#ifndef _LIBELF_H
#define _LIBELF_H 1

#include <stdint.h>
#include <sys/types.h>

/* Get the ELF types.  */
#include <elf.h>

#ifndef SHF_COMPRESSED
 /* Older glibc elf.h might not yet define the ELF compression types.  */
 #define SHF_COMPRESSED      (1 << 11)  /* Section with compressed data. */

 /* Section compression header.  Used when SHF_COMPRESSED is set.  */

 typedef struct
 {
   Elf32_Word   ch_type;        /* Compression format.  */
   Elf32_Word   ch_size;        /* Uncompressed data size.  */
   Elf32_Word   ch_addralign;   /* Uncompressed data alignment.  */
 } Elf32_Chdr;

 typedef struct
 {
   Elf64_Word   ch_type;        /* Compression format.  */
   Elf64_Word   ch_reserved;
   Elf64_Xword  ch_size;        /* Uncompressed data size.  */
   Elf64_Xword  ch_addralign;   /* Uncompressed data alignment.  */
 } Elf64_Chdr;

 /* Legal values for ch_type (compression algorithm).  */
 #define ELFCOMPRESS_ZLIB       1          /* ZLIB/DEFLATE algorithm.  */
 #define ELFCOMPRESS_LOOS       0x60000000 /* Start of OS-specific.  */
 #define ELFCOMPRESS_HIOS       0x6fffffff /* End of OS-specific.  */
 #define ELFCOMPRESS_LOPROC     0x70000000 /* Start of processor-specific.  */
 #define ELFCOMPRESS_HIPROC     0x7fffffff /* End of processor-specific.  */
#endif

/* Known translation types.  */
typedef enum
{
  ELF_T_BYTE,                   /* unsigned char */
  ELF_T_ADDR,                   /* Elf32_Addr, Elf64_Addr, ... */
  ELF_T_DYN,                    /* Dynamic section record.  */
  ELF_T_EHDR,                   /* ELF header.  */
  ELF_T_HALF,                   /* Elf32_Half, Elf64_Half, ... */
  ELF_T_OFF,                    /* Elf32_Off, Elf64_Off, ... */
  ELF_T_PHDR,                   /* Program header.  */
  ELF_T_RELA,                   /* Relocation entry with addend.  */
  ELF_T_REL,                    /* Relocation entry.  */
  ELF_T_SHDR,                   /* Section header.  */
  ELF_T_SWORD,                  /* Elf32_Sword, Elf64_Sword, ... */
  ELF_T_SYM,                    /* Symbol record.  */
  ELF_T_WORD,                   /* Elf32_Word, Elf64_Word, ... */
  ELF_T_XWORD,                  /* Elf32_Xword, Elf64_Xword, ... */
  ELF_T_SXWORD,                 /* Elf32_Sxword, Elf64_Sxword, ... */
  ELF_T_VDEF,                   /* Elf32_Verdef, Elf64_Verdef, ... */
  ELF_T_VDAUX,                  /* Elf32_Verdaux, Elf64_Verdaux, ... */
  ELF_T_VNEED,                  /* Elf32_Verneed, Elf64_Verneed, ... */
  ELF_T_VNAUX,                  /* Elf32_Vernaux, Elf64_Vernaux, ... */
  ELF_T_NHDR,                   /* Elf32_Nhdr, Elf64_Nhdr, ... */
  ELF_T_SYMINFO,		/* Elf32_Syminfo, Elf64_Syminfo, ... */
  ELF_T_MOVE,			/* Elf32_Move, Elf64_Move, ... */
  ELF_T_LIB,			/* Elf32_Lib, Elf64_Lib, ... */
  ELF_T_GNUHASH,		/* GNU-style hash section.  */
  ELF_T_AUXV,			/* Elf32_auxv_t, Elf64_auxv_t, ... */
  ELF_T_CHDR,			/* Compressed, Elf32_Chdr, Elf64_Chdr, ... */
  /* Keep this the last entry.  */
  ELF_T_NUM
} Elf_Type;

/* Descriptor for data to be converted to or from memory format.  */
typedef struct
{
  void *d_buf;			/* Pointer to the actual data.  */
  Elf_Type d_type;		/* Type of this piece of data.  */
  unsigned int d_version;	/* ELF version.  */
  size_t d_size;		/* Size in bytes.  */
  int64_t d_off;		/* Offset into section.  */
  size_t d_align;		/* Alignment in section.  */
} Elf_Data;

/* Commands for `...'.  */
typedef enum
{
  ELF_C_NULL,			/* Nothing, terminate, or compute only.  */
  ELF_C_READ,			/* Read .. */
  ELF_C_RDWR,			/* Read and write .. */
  ELF_C_WRITE,			/* Write .. */
  ELF_C_CLR,			/* Clear flag.  */
  ELF_C_SET,			/* Set flag.  */
  ELF_C_FDDONE,			/* Signal that file descriptor will not be
				   used anymore.  */
  ELF_C_FDREAD,			/* Read rest of data so that file descriptor
				   is not used anymore.  */
  /* The following are extensions.  */
  ELF_C_READ_MMAP,		/* Read, but mmap the file if possible.  */
  ELF_C_RDWR_MMAP,		/* Read and write, with mmap.  */
  ELF_C_WRITE_MMAP,		/* Write, with mmap.  */
  ELF_C_READ_MMAP_PRIVATE,	/* Read, but memory is writable, results are
				   not written to the file.  */
  ELF_C_EMPTY,			/* Copy basic file data but not the content. */
  /* Keep this the last entry.  */
  ELF_C_NUM
} Elf_Cmd;

/* Flags for the ELF structures.  */
enum
{
  ELF_F_DIRTY = 0x1,
#define ELF_F_DIRTY		ELF_F_DIRTY
  ELF_F_LAYOUT = 0x4,
#define ELF_F_LAYOUT		ELF_F_LAYOUT
  ELF_F_PERMISSIVE = 0x8
#define ELF_F_PERMISSIVE	ELF_F_PERMISSIVE
};

/* Flags for elf_compress[_gnu].  */
enum
{
  ELF_CHF_FORCE = 0x1
#define ELF_CHF_FORCE ELF_CHF_FORCE
};

/* Identification values for recognized object files.  */
typedef enum
{
  ELF_K_NONE,			/* Unknown.  */
  ELF_K_AR,			/* Archive.  */
  ELF_K_COFF,			/* Stupid old COFF.  */
  ELF_K_ELF,			/* ELF file.  */
  /* Keep this the last entry.  */
  ELF_K_NUM
} Elf_Kind;

/* Archive member header.  */
typedef struct
{
  char *ar_name;		/* Name of archive member.  */
  time_t ar_date;		/* File date.  */
  uid_t ar_uid;			/* User ID.  */
  gid_t ar_gid;			/* Group ID.  */
  mode_t ar_mode;		/* File mode.  */
  int64_t ar_size;		/* File size.  */
  char *ar_rawname;		/* Original name of archive member.  */
} Elf_Arhdr;

/* Archive symbol table entry.  */
typedef struct
{
  char *as_name;		/* Symbol name.  */
  size_t as_off;		/* Offset for this file in the archive.  */
  unsigned long int as_hash;	/* Hash value of the name.  */
} Elf_Arsym;

/* Descriptor for the ELF file.  */
typedef struct Elf Elf;

/* Descriptor for ELF file section.  */
typedef struct Elf_Scn Elf_Scn;

#ifdef __cplusplus
extern "C" {
#endif

/* Return descriptor for ELF file to work according to CMD.  */
extern Elf *elf_begin (int __fildes, Elf_Cmd __cmd, Elf *__ref);

/* Create a clone of an existing ELF descriptor.  */
  extern Elf *elf_clone (Elf *__elf, Elf_Cmd __cmd);

/* Create descriptor for memory region.  */
extern Elf *elf_memory (char *__image, size_t __size);

/* Advance archive descriptor to next element.  */
extern Elf_Cmd elf_next (Elf *__elf);

/* Free resources allocated for ELF.  */
extern int elf_end (Elf *__elf);

/* Update ELF descriptor and write file to disk.  */
extern int64_t elf_update (Elf *__elf, Elf_Cmd __cmd);

/* Determine what kind of file is associated with ELF.  */
extern Elf_Kind elf_kind (Elf *__elf) __attribute__ ((__pure__));

/* Get the base offset for an object file.  */
extern int64_t elf_getbase (Elf *__elf);

/* Retrieve file identification data.  */
extern char *elf_getident (Elf *__elf, size_t *__nbytes);

/* Retrieve class-dependent object file header.  */
extern Elf32_Ehdr *elf32_getehdr (Elf *__elf);
/* Similar but this time the binary calls is ELFCLASS64.  */
extern Elf64_Ehdr *elf64_getehdr (Elf *__elf);

/* Create ELF header if none exists.  */
extern Elf32_Ehdr *elf32_newehdr (Elf *__elf);
/* Similar but this time the binary calls is ELFCLASS64.  */
extern Elf64_Ehdr *elf64_newehdr (Elf *__elf);

/* Get the number of program headers in the ELF file.  If the file uses
   more headers than can be represented in the e_phnum field of the ELF
   header the information from the sh_info field in the zeroth section
   header is used.  */
extern int elf_getphdrnum (Elf *__elf, size_t *__dst);

/* Retrieve class-dependent program header table.  */
extern Elf32_Phdr *elf32_getphdr (Elf *__elf);
/* Similar but this time the binary calls is ELFCLASS64.  */
extern Elf64_Phdr *elf64_getphdr (Elf *__elf);

/* Create ELF program header.  */
extern Elf32_Phdr *elf32_newphdr (Elf *__elf, size_t __cnt);
/* Similar but this time the binary calls is ELFCLASS64.  */
extern Elf64_Phdr *elf64_newphdr (Elf *__elf, size_t __cnt);

/* Get section at INDEX.  */
extern Elf_Scn *elf_getscn (Elf *__elf, size_t __index);

/* Get section at OFFSET.  */
extern Elf_Scn *elf32_offscn (Elf *__elf, Elf32_Off __offset);
/* Similar bug this time the binary calls is ELFCLASS64.  */
extern Elf_Scn *elf64_offscn (Elf *__elf, Elf64_Off __offset);

/* Get index of section.  */
extern size_t elf_ndxscn (Elf_Scn *__scn);

/* Get section with next section index.  */
extern Elf_Scn *elf_nextscn (Elf *__elf, Elf_Scn *__scn);

/* Create a new section and append it at the end of the table.  */
extern Elf_Scn *elf_newscn (Elf *__elf);

/* Get the section index of the extended section index table for the
   given symbol table.  */
extern int elf_scnshndx (Elf_Scn *__scn);

/* Get the number of sections in the ELF file.  If the file uses more
   sections than can be represented in the e_shnum field of the ELF
   header the information from the sh_size field in the zeroth section
   header is used.  */
extern int elf_getshdrnum (Elf *__elf, size_t *__dst);
/* Sun messed up the implementation of 'elf_getshnum' in their implementation.
   It was agreed to make the same functionality available under a different
   name and obsolete the old name.  */
extern int elf_getshnum (Elf *__elf, size_t *__dst)
     __attribute__ ((__deprecated__));

/* Get the section index of the section header string table in the ELF
   file.  If the index cannot be represented in the e_shnum field of
   the ELF header the information from the sh_link field in the zeroth
   section header is used.  */
extern int elf_getshdrstrndx (Elf *__elf, size_t *__dst);
/* Sun messed up the implementation of 'elf_getshnum' in their implementation.
   It was agreed to make the same functionality available under a different
   name and obsolete the old name.  */
extern int elf_getshstrndx (Elf *__elf, size_t *__dst)
     __attribute__ ((__deprecated__));

/* Retrieve section header of ELFCLASS32 binary.  */
extern Elf32_Shdr *elf32_getshdr (Elf_Scn *__scn);
/* Similar for ELFCLASS64.  */
extern Elf64_Shdr *elf64_getshdr (Elf_Scn *__scn);

/* Returns compression header for a section if section data is
   compressed.  Returns NULL and sets elf_errno if the section isn't
   compressed or an error occurred.  */
extern Elf32_Chdr *elf32_getchdr (Elf_Scn *__scn);
extern Elf64_Chdr *elf64_getchdr (Elf_Scn *__scn);

/* Compress or decompress the data of a section and adjust the section
   header.

   elf_compress works by setting or clearing the SHF_COMPRESS flag
   from the section Shdr and will encode or decode a Elf32_Chdr or
   Elf64_Chdr at the start of the section data.  elf_compress_gnu will
   encode or decode any section, but is traditionally only used for
   sections that have a name starting with ".debug" when
   uncompressed or ".zdebug" when compressed and stores just the
   uncompressed size.  The GNU compression method is deprecated and
   should only be used for legacy support.

   elf_compress takes a compression type that should be either zero to
   decompress or an ELFCOMPRESS algorithm to use for compression.
   Currently only ELFCOMPRESS_ZLIB is supported.  elf_compress_gnu
   will compress in the traditional GNU compression format when
   compress is one and decompress the section data when compress is
   zero.

   The FLAGS argument can be zero or ELF_CHF_FORCE.  If FLAGS contains
   ELF_CHF_FORCE then it will always compress the section, even if
   that would not reduce the size of the data section (including the
   header).  Otherwise elf_compress and elf_compress_gnu will compress
   the section only if the total data size is reduced.

   On successful compression or decompression the function returns
   one.  If (not forced) compression is requested and the data section
   would not actually reduce in size, the section is not actually
   compressed and zero is returned.  Otherwise -1 is returned and
   elf_errno is set.

   It is an error to request compression for a section that already
   has SHF_COMPRESSED set, or (for elf_compress) to request
   decompression for an section that doesn't have SHF_COMPRESSED set.
   It is always an error to call these functions on SHT_NOBITS
   sections or if the section has the SHF_ALLOC flag set.
   elf_compress_gnu will not check whether the section name starts
   with ".debug" or .zdebug".  It is the responsibilty of the caller
   to make sure the deprecated GNU compression method is only called
   on correctly named sections (and to change the name of the section
   when using elf_compress_gnu).

   All previous returned Shdrs and Elf_Data buffers are invalidated by
   this call and should no longer be accessed.

   Note that although this changes the header and data returned it
   doesn't mark the section as dirty.  To keep the changes when
   calling elf_update the section has to be flagged ELF_F_DIRTY.  */
extern int elf_compress (Elf_Scn *scn, int type, unsigned int flags);
extern int elf_compress_gnu (Elf_Scn *scn, int compress, unsigned int flags);

/* Set or clear flags for ELF file.  */
extern unsigned int elf_flagelf (Elf *__elf, Elf_Cmd __cmd,
				 unsigned int __flags);
/* Similarly for the ELF header.  */
extern unsigned int elf_flagehdr (Elf *__elf, Elf_Cmd __cmd,
				  unsigned int __flags);
/* Similarly for the ELF program header.  */
extern unsigned int elf_flagphdr (Elf *__elf, Elf_Cmd __cmd,
				  unsigned int __flags);
/* Similarly for the given ELF section.  */
extern unsigned int elf_flagscn (Elf_Scn *__scn, Elf_Cmd __cmd,
				 unsigned int __flags);
/* Similarly for the given ELF data.  */
extern unsigned int elf_flagdata (Elf_Data *__data, Elf_Cmd __cmd,
				  unsigned int __flags);
/* Similarly for the given ELF section header.  */
extern unsigned int elf_flagshdr (Elf_Scn *__scn, Elf_Cmd __cmd,
				  unsigned int __flags);

/* Get data from section while translating from file representation to
   memory representation.  The Elf_Data d_type is set based on the
   section type if known.  Otherwise d_type is set to ELF_T_BYTE.  If
   the section contains compressed data then d_type is always set to
   ELF_T_CHDR.  */
extern Elf_Data *elf_getdata (Elf_Scn *__scn, Elf_Data *__data);

/* Get uninterpreted section content.  */
extern Elf_Data *elf_rawdata (Elf_Scn *__scn, Elf_Data *__data);

/* Create new data descriptor for section SCN.  */
extern Elf_Data *elf_newdata (Elf_Scn *__scn);

/* Get data translated from a chunk of the file contents as section data
   would be for TYPE.  The resulting Elf_Data pointer is valid until
   elf_end (ELF) is called.  */
extern Elf_Data *elf_getdata_rawchunk (Elf *__elf,
				       int64_t __offset, size_t __size,
				       Elf_Type __type);

/* Return pointer to string at OFFSET in section INDEX.  */
extern char *elf_strptr (Elf *__elf, size_t __index, size_t __offset);

/* Return header of archive.  */
extern Elf_Arhdr *elf_getarhdr (Elf *__elf);

/* Return offset in archive for current file ELF.  */
extern int64_t elf_getaroff (Elf *__elf);

/* Select archive element at OFFSET.  */
extern size_t elf_rand (Elf *__elf, size_t __offset);

/* Get symbol table of archive.  */
extern Elf_Arsym *elf_getarsym (Elf *__elf, size_t *__narsyms);

/* Control ELF descriptor.  */
extern int elf_cntl (Elf *__elf, Elf_Cmd __cmd);

/* Retrieve uninterpreted file contents.  */
extern char *elf_rawfile (Elf *__elf, size_t *__nbytes);

/* Return size of array of COUNT elements of the type denoted by TYPE
   in the external representation.  The binary class is taken from ELF.
   The result is based on version VERSION of the ELF standard.  */
extern size_t elf32_fsize (Elf_Type __type, size_t __count,
			   unsigned int __version)
       __attribute__ ((__const__));
/* Similar but this time the binary calls is ELFCLASS64.  */
extern size_t elf64_fsize (Elf_Type __type, size_t __count,
			   unsigned int __version)
       __attribute__ ((__const__));

/* Convert data structure from the representation in the file represented
   by ELF to their memory representation.  */
extern Elf_Data *elf32_xlatetom (Elf_Data *__dest, const Elf_Data *__src,
				 unsigned int __encode);
/* Same for 64 bit class.  */
extern Elf_Data *elf64_xlatetom (Elf_Data *__dest, const Elf_Data *__src,
				 unsigned int __encode);

/* Convert data structure from to the representation in memory
   represented by ELF file representation.  */
extern Elf_Data *elf32_xlatetof (Elf_Data *__dest, const Elf_Data *__src,
				 unsigned int __encode);
/* Same for 64 bit class.  */
extern Elf_Data *elf64_xlatetof (Elf_Data *__dest, const Elf_Data *__src,
				 unsigned int __encode);

/* Return error code of last failing function call.  This value is kept
   separately for each thread.  */
extern int elf_errno (void);

/* Return error string for ERROR.  If ERROR is zero, return error string
   for most recent error or NULL is none occurred.  If ERROR is -1 the
   behaviour is similar to the last case except that not NULL but a legal
   string is returned.  */
extern const char *elf_errmsg (int __error);

/* Coordinate ELF library and application versions.  */
extern unsigned int elf_version (unsigned int __version);

/* Set fill bytes used to fill holes in data structures.  */
extern void elf_fill (int __fill);

/* Compute hash value.  */
extern unsigned long int elf_hash (const char *__string)
       __attribute__ ((__pure__));

/* Compute hash value using the GNU-specific hash function.  */
extern unsigned long int elf_gnu_hash (const char *__string)
       __attribute__ ((__pure__));

/* Compute simple checksum from permanent parts of the ELF file.  */
extern long int elf32_checksum (Elf *__elf);
/* Similar but this time the binary calls is ELFCLASS64.  */
extern long int elf64_checksum (Elf *__elf);

#ifdef __cplusplus
}
#endif

#endif  /* libelf.h */


text:
#if NET40 || NET45
using System;

namespace DotNetCasClient.State
{///<summary>
    /// An IProxyTicketManager implementation that relies on the System.Runtime.Caching caching model for ticket
    /// storage.  Generally this implies that the ticket storage is maintained locally on the web
    /// server (either in memory or on disk).  A limitation of this model is that it will not
    /// support clustered, load balanced, or round-robin style configurations.
    ///</summary>
    /// <author>Jason Kanaris</author>
    public class MemoryCacheProxyTicketManager : IProxyTicketManager
    {
        private static readonly TimeSpan DefaultExpiration = new TimeSpan(0, 0, 3, 0); // 180 seconds

        /// <summary>
        /// You retrieve CasAuthentication properties in the constructor or else you will cause
        /// a StackOverflow.  CasAuthentication.Initialize() will call Initialize() on all
        /// relevant controls when its initialization is complete.  In Initialize(), you can
        /// retrieve properties from CasAuthentication.
        /// </summary>
        public void Initialize()
        {
            // Do nothing
        }

        /// <summary>
        /// Removes expired PGTIOU-PGT from the ticket store
        /// </summary>
        public void RemoveExpiredMappings()
        {
            // No-op.  The System.Runtime.Caching.ObjectCache provider removes expired entries automatically.
        }

        /// <summary>
        /// Method to save the ProxyGrantingTicket to the backing storage facility.
        /// </summary>
        /// <param name="proxyGrantingTicketIou">used as the key</param>
        /// <param name="proxyGrantingTicket">used as the value</param>
        public void InsertProxyGrantingTicketMapping(string proxyGrantingTicketIou, string proxyGrantingTicket)
        {
            MemoryCacheManager.Instance.Set(proxyGrantingTicketIou, proxyGrantingTicket, DefaultExpiration);
        }

        /// <summary>
        /// Method to retrieve a ProxyGrantingTicket based on the
        /// ProxyGrantingTicketIou.  Implementations are not guaranteed to
        /// return the same result if retieve is called twice with the same
        /// proxyGrantingTicketIou.
        /// </summary>
        /// <param name="proxyGrantingTicketIou">used as the key</param>
        /// <returns>the ProxyGrantingTicket Id or null if it can't be found</returns>
        public string GetProxyGrantingTicket(string proxyGrantingTicketIou)
        {

            if (MemoryCacheManager.Instance.Contains(proxyGrantingTicketIou) && !string.IsNullOrWhiteSpace(MemoryCacheManager.Instance.Get<string>(proxyGrantingTicketIou)))
            {
                return MemoryCacheManager.Instance.Get<string>(proxyGrantingTicketIou);
            }

            return null;
        }
    }
}
#endif

redpajama_set_name: RedPajamaGithub


text:
package com.appmetr.hercules.failover;

import me.prettyprint.hector.api.exceptions.HTimedOutException;
import me.prettyprint.hector.api.exceptions.HUnavailableException;
import me.prettyprint.hector.api.exceptions.HectorException;
import org.slf4j.Logger;

public class FailoverQueryProcessor {

    public static <T> T process(FailoverConf conf, Logger logger, FailoverQuery<T> query) throws HectorException {

        if (conf.getMaxRetries() == 0) {
            throw new IllegalArgumentException("Invalid retries count: " + conf.getMaxRetries());
        }

        int retryCount = 0;
        int currSleepBetweenRetries = Math.min(conf.getStartSleepBetweenRetriesMs(), conf.getMaxSleepBetweenRetriesMs());
        while (true) {

            HectorException exception;
            try {
                return query.query();
            } catch (HTimedOutException e) {
                exception = e;
            } catch (HUnavailableException e) {
                exception = e;
            }

            retryCount++;
            if (conf.getMaxRetries() > 0 && retryCount >= conf.getMaxRetries()) {
                throw exception;
            }

            if (logger != null) {
                logger.error(String.format("Failovering: retries count - %1$s, sleep between - %2$s\n", retryCount, currSleepBetweenRetries), exception);
            }
            try {
                Thread.sleep(currSleepBetweenRetries);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            currSleepBetweenRetries = Math.min((int) (currSleepBetweenRetries * conf.getSleepBetweenRetriesIncreaseRatio() + 0.5), conf.getMaxSleepBetweenRetriesMs());
        }
    }

    public static void process(FailoverConf conf, Logger logger, final VoidFailoverQuery query) throws HectorException {
        process(conf, logger, new FailoverQuery<Void>() {
            @Override public Void query() {
                query.query();

                return null;
            }
        });
    }
}


text:
package org.opensmartgridplatform.adapter.protocol.oslp.elster.device.requests;

import org.opensmartgridplatform.adapter.protocol.oslp.elster.device.DeviceRequest;
import org.opensmartgridplatform.dto.valueobjects.EventNotificationMessageDataContainerDto;

public class SetEventNotificationsDeviceRequest extends DeviceRequest {

    private final EventNotificationMessageDataContainerDto eventNotificationsContainer;

    public SetEventNotificationsDeviceRequest(final String organisationIdentification,
            final String deviceIdentification, final String correlationUid, final int messagePriority,
            final EventNotificationMessageDataContainerDto eventNotificationsContainer) {
        super(organisationIdentification, deviceIdentification, correlationUid, messagePriority);
        this.eventNotificationsContainer = eventNotificationsContainer;
    }

    public SetEventNotificationsDeviceRequest(final Builder deviceRequestBuilder,
            final EventNotificationMessageDataContainerDto eventNotificationsContainer) {
        super(deviceRequestBuilder);
        this.eventNotificationsContainer = eventNotificationsContainer;
    }

    public EventNotificationMessageDataContainerDto getEventNotificationsContainer() {
        return this.eventNotificationsContainer;
    }
}


text:
package geometry

const (
	NearlyZero float64 = 1e-12
)

// Clamp f to be between min and max
func Clamp(s, min, max float64) float64 {
	if s < min {
		return min
	}
	if s > max {
		return max
	}
	return s
}

// Linearly interpolate between a and b by t percent (comprise from 0 to 1).
func Lerp(a, b, t float64) float64 {
	return a*(1.0-t) + b*t
}


text:
from oslo_log import log

from ec2api.tests.functional import base
from ec2api.tests.functional import config

CONF = config.CONF
LOG = log.getLogger(__name__)

class InstanceWithEBSTest(base.EC2TestCase):
    @classmethod
    @base.safe_setup
    def setUpClass(cls):
        super(InstanceWithEBSTest, cls).setUpClass()
        if not CONF.aws.ebs_image_id:
            raise cls.skipException('aws EBS image does not provided')
        cls.image_id = CONF.aws.ebs_image_id
        cls.zone = CONF.aws.aws_zone

    def test_create_get_delete_ebs_instance(self):
        """Launch EBS-backed instance, check results, and terminate it."""
        resp, data = self.client.RunInstances(
            ImageId=self.image_id, InstanceType=CONF.aws.instance_type,
            Placement={'AvailabilityZone': self.zone}, MinCount=1, MaxCount=1)
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.assertEqual(1, len(data['Instances']))
        instance_id = data['Instances'][0]['InstanceId']
        res_clean = self.addResourceCleanUp(self.client.TerminateInstances,
                                            InstanceIds=[instance_id])
        self.get_instance_waiter().wait_available(instance_id,
                                                  final_set=('running'))

        instance = self.get_instance(instance_id)

        self.assertEqual('ebs', instance.get('RootDeviceType'))
        self.assertIsNotNone(instance.get('RootDeviceName'))
        bdms = instance.get('BlockDeviceMappings')
        self.assertIsNotNone(bdms)
        rdn = instance['RootDeviceName']
        bdt = [bdt for bdt in bdms if bdt['DeviceName'] == rdn]
        self.assertEqual(1, len(bdt))
        ebs = bdt[0]['Ebs']
        self.assertIsNotNone(ebs)
        volume_id = ebs.get('VolumeId')
        self.assertIsNotNone(volume_id)
        self.assertEqual('attached', ebs.get('Status'))
        if CONF.aws.run_incompatible_tests:
            self.assertTrue(ebs.get('AttachTime'))
            self.assertTrue(ebs.get('DeleteOnTermination'))

        resp, data = self.client.DescribeVolumes(VolumeIds=[volume_id])
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.assertEqual(1, len(data['Volumes']))

        resp, data = self.client.TerminateInstances(InstanceIds=[instance_id])
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.cancelResourceCleanUp(res_clean)
        self.get_instance_waiter().wait_delete(instance_id)

    def test_create_root_volume_snapshot(self):
        """Create snapshot of root volume of EBS-backed instance."""
        resp, data = self.client.RunInstances(
            ImageId=self.image_id, InstanceType=CONF.aws.instance_type,
            Placement={'AvailabilityZone': self.zone}, MinCount=1, MaxCount=1)
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.assertEqual(1, len(data['Instances']))
        instance_id = data['Instances'][0]['InstanceId']
        res_clean = self.addResourceCleanUp(self.client.TerminateInstances,
                                            InstanceIds=[instance_id])
        self.get_instance_waiter().wait_available(instance_id,
                                                  final_set=('running'))

        bdt = self.get_instance_bdm(instance_id, None)
        self.assertIsNotNone(bdt)
        volume_id = bdt['Ebs'].get('VolumeId')
        self.assertIsNotNone(volume_id)

        resp, data = self.client.StopInstances(InstanceIds=[instance_id])
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.get_instance_waiter().wait_available(instance_id,
                                                  final_set=('stopped'))

        resp, data = self.client.DescribeVolumes(VolumeIds=[volume_id])
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.assertEqual(1, len(data['Volumes']))

        kwargs = {
            'VolumeId': data['Volumes'][0]['VolumeId'],
            'Description': 'Description'
        }
        resp, data = self.client.CreateSnapshot(*[], **kwargs)
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        snapshot_id = data['SnapshotId']
        res_clean_s = self.addResourceCleanUp(self.client.DeleteSnapshot,
                                              SnapshotId=snapshot_id)
        self.get_snapshot_waiter().wait_available(snapshot_id,
                                                  final_set=('completed'))

        resp, data = self.client.TerminateInstances(InstanceIds=[instance_id])
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.cancelResourceCleanUp(res_clean)
        self.get_instance_waiter().wait_delete(instance_id)

        resp, data = self.client.DeleteSnapshot(SnapshotId=snapshot_id)
        self.assertEqual(200, resp.status_code, base.EC2ErrorConverter(data))
        self.cancelResourceCleanUp(res_clean_s)
        self.get_snapshot_waiter().wait_delete(snapshot_id)


text:
package org.jtheque.filmstobuy.services.impl.file;

import org.jtheque.core.managers.file.able.BackupWriter;
import org.jtheque.core.utils.file.XMLWriter;
import org.jtheque.filmstobuy.persistence.od.able.FilmToBuy;
import org.jtheque.filmstobuy.services.able.IFilmsToBuyService;

import javax.annotation.Resource;

/**
 * A backup writer for a XML Backup.
 *
 * @author Baptiste Wicht
 */
public final class XMLBackupWriter implements BackupWriter {
    @Resource
    private IFilmsToBuyService filmsToBuyService;

    @Override
    public void write(Object object) {
        XMLWriter writer = (XMLWriter) object;

        writer.add("filmsToBuy");

        for (FilmToBuy film : filmsToBuyService.getFilmsToBuy()) {
            writer.add("film");

            writer.addOnly("id", film.getId());
            writer.addOnly("date", film.getDate().intValue());
            writer.addOnly("title", film.getTitle());

            writer.switchToParent();
        }

        writer.switchToParent();
    }
}


text:
var mongoose   = require('mongoose');
var nodemailer = require("nodemailer");
var https      = require('https');
var fs         = require('fs');
var url        = require('url');
var md5        = require('md5');

var MACRO = require('./model/macro.js');

var Users = mongoose.model('Users');
var Repo  = mongoose.model('Repo');
var Notifications = mongoose.model('Notifications');
var Challenges    = mongoose.model('Challenges');

var nextUserId = 0;
global.usersById = {};
var usersByGhId = {};

exports.send_mail = function (destination, type, body, subject) {
  if (!global.config.mail_user || !global.config.mail_pass) {
    console.log('Missing user/pass for SMTP connection. Cannot send email.')
    return;
  }

  // Create reusable transport method (opens pool of SMTP connections)
  var smtpURL = 'smtps://' + global.config.mail_user + ':'
  smtpURL += global.config.mail_pass + '@smtp.gmail.com'
  var smtpTransport = nodemailer.createTransport(smtpURL);

  fs.readFile(__dirname + '/public/emails/' + type + '.html', 'utf8', function (err, html) {
    // Default email source and destiantion
    var mailOpt = {
      'from': 'ROSEdu Challenge <challenge@lists.rosedu.org>',
      'to':   destination
    }

    // Handle different types of emails
    if (type == 'welcome') {
      mailOpt['subject'] = 'Welcome to Challenge by ROSEdu',
      mailOpt['text']    = '',
      mailOpt['html']    = html;
    } else if (type == 'feedback') {
      mailOpt['to']      = 'challenge@lists.rosedu.org',
      mailOpt['subject'] = 'Feedback: ' + body.email,
      mailOpt['text']    = body.msg
    } else if (type == 'challenge') {
      mailOpt['subject'] = subject,
      mailOpt['text']    = body
    }

    // Send mail using previously defined transport object
    smtpTransport.sendMail(mailOpt, function(err, response){
      if (err) console.log(err);
      else console.log("* " + type + " email sent to " + mailOpt['to']);
    });
    smtpTransport.close();
  });
}

function addUser (source, sourceUser) {
  var user;
  if (arguments.length === 1) { // password-based
    user = sourceUser = source;
    user.id = ++nextUserId;
    return usersById[nextUserId] = user;
  } else { // non-password-based
    user = usersById[++nextUserId] = {id: nextUserId};
    user[source] = sourceUser;
  }
  return user;
}

exports.get_time_from = function (then) {
  var now = Date.now();

  // interval between time now and db date
  var msec = now - new Date(then).getTime();

  var hh = Math.floor(msec / 1000 / 60 / 60);
  if (hh > 24) { // older that 24 hours
    // return actual date
    return "on " + then.toString().substring(4, 15);

  } else if (hh > 1) { // older than 1 hour
    return hh + " hours ago";

  } else {
    msec -= hh * 1000 * 60 * 60;
    var mm = Math.floor(msec / 1000 / 60);

    if (mm > 1) { // older than 1 mnute
      return mm + " minutes ago";

    } else {
      return "one minute ago";
    }
  }
}

function create_patch_request(ch, pull) {
    var patch_url = pull.url;
    var patch_url_host = url.parse(patch_url, true).host;
    var patch_url_path = url.parse(patch_url, true).pathname;

    var patch_options = {
      host: patch_url_host,
      path: patch_url_path,
      method: "GET",
      headers: { "User-Agent": "github-connect" }
    };

    var patch_request = https.request(patch_options, function(response) {
      var pull_body = '';

      response.on("data", function(chunk) {
        pull_body+=chunk.toString("utf8");
      });

      response.on("end", function() {
        var pull_info = JSON.parse(pull_body);

        // Check if merge date exists
        var merge_date;

        if (!pull.merged_at) merge_date = null;
        else merge_date = new Date(pull.merged_at);

        // Generate unique PR id
        var oid = md5(pull.html_url).substring(0,12)

        Challenges.findOne({'pulls.url': pull.html_url}, function (err, pr) {
          // No updates were made, object did not exist, let's push it
          if (err) console.log(err)

          if (pr) {
            var update = {$set: {
              'pulls.$.title':          pull.title,
              'pulls.$.created':        new Date(pull.created_at),
              'pulls.$.merged':         merge_date,
              'pulls.$.lines_inserted': pull_info.additions,
              'pulls.$.lines_removed':  pull_info.deletions,
              'pulls.$.files_changed':  pull_info.changed_files
            }}
            // Update PR object
            Challenges.update({'pulls.url': pull.html_url}, update, function (err) {
              if (err) console.log('Failed to update PR: ' + err)
            });

          } else {
            var newpr = {
              '_id':            new mongoose.Types.ObjectId(oid),
              'repo':           pull.base.repo.full_name,
              'auth':           pull.user.login,
              'hide':           false,
              'url':            pull.html_url,
              'title':          pull.title,
              'created':        new Date(pull.created_at),
              'merged':         merge_date,
              'score':          0,
              'rating':         0,
              'lines_inserted': pull_info.additions,
              'lines_removed':  pull_info.deletions,
              'files_changed':  pull_info.changed_files
            }
            // Update score if formulae is valid
            if (exports.eval_formulae(ch.formulae))
              newpr['score'] = exports.eval_formulae(ch.formulae, newpr)
            // Update challenge object
            Challenges.update({'link': ch.link}, {$push: {pulls: newpr}}, function (err) {
              if (err) console.log('Failed to add new PR: ' + err)
            });
          }
        })
      });

    });
    patch_request.end();
}

/*
Replace individual constants in formulae with actual values
and supply a result.

If pull argument is missing, test arithmetic expression using a default value
and try to evaluate expression. Returns null if failed.

IL - Inserted lines
RL - Removed lines
FC - Files changed
R  - Rating
*/
exports.eval_formulae = function(formulae, pull) {

  // Default test value, if parameter is missing
  pull = pull || {
    'lines_inserted': 0,
    'lines_removed': 0,
    'files_changed': 0,
    'rating': 0
  }

  // Replace all occurances
  formulae = formulae.replace(/IL/g, pull.lines_inserted)
  formulae = formulae.replace(/RL/g, pull.lines_removed)
  formulae = formulae.replace(/FC/g, pull.files_changed)
  formulae = formulae.replace(/R/g,  pull.rating)

  try {
    score = eval(formulae)
  } catch(err) {
    score = null
  }

  return score
}

/*
Refresh all repos from all challeneges that are active ('live').
*/
exports.refresh_challenges = function() {

  Challenges.find({'status': 'live'}).exec(gotChallenges);

  function gotChallenges(err, all) {

    // For each challenge in pool
    for (var c in all) {

      var ch = all[c];

      // Update last refresh date
      var update = {$set: {'refresh': Date.now()}};
      Challenges.update({'link': ch.link}, update).exec();

      //New request for each repo of challenge
      for (var r=0; r<ch.repos.length; r++) {

        var options = {
          host: "api.github.com",
          path: "/repos/" + ch.repos[r] + "/pulls?state=all",
          method: "GET",
          headers: { "User-Agent": "github-connect" }
        };

        var request = https.request(options, function(response){
          var body = '';

          response.on("data", function(chunk){
            body+=chunk.toString("utf8");
          });

          response.on("end", function(){
            var pulls = JSON.parse(body);

            // Log errors
            if (pulls.message)
              console.log("[ERR] " + pulls.message + " - " + options.path
                + " (" + pulls.documentation_url + ")");

            for (var p in pulls) {

              // Accept only pulls created after challenge start date, before end
              // date and only from registered users
              if (new Date(pulls[p].created_at).getTime() > ch.start.getTime() &&
                  new Date(pulls[p].created_at).getTime() < ch.end.getTime() &&
                  ch.users.indexOf(pulls[p].user.login) > -1) {

                create_patch_request(ch, pulls[p]);
              }
            }
          });
        });
        request.end();

      }
    }
  }
}

exports.update_repo_info = function(ch_link) {
  if (typeof ch_link == 'undefined')
    Challenges.find().exec(gotChallenge);
  else
    Challenges.find({'link': ch_link}).exec(gotChallenge);

  function gotChallenge (err, all) {
    if (err) return console.log('ERR. Cannot update repo info.')

    all.forEach(function(ch) {
      ch.repos.forEach(function(repo) {
        // Request repo info from Github
        var options = {
          host: "api.github.com",
          path: "/repos/" + repo,
          method: "GET",
          headers: { "User-Agent": "github-connect" }
        };

        var request = https.request(options, function(response){
          var body = '';

          response.on("data", function(chunk){
            body+=chunk.toString("utf8");
          });

          response.on("end", function() {
            var repo = JSON.parse(body);

            // Log errors
            if (repo.message)
              console.log("[ERR] " + repo.message + " - " + options.path
                + " (" + repo.documentation_url + ")");

            var query = {
              'name': repo.full_name
            }
            var update = {
              'name':        repo.full_name,
              'description': repo.description,
              'link':        repo.homepage
            }
            Repo.update(query, update, {upsert: true}).exec()
          });
        });
        request.end();
      });
    });

  }
}

/*
Adds dummy user with given id and username to db.
This is used during development when multiple users are needed for testing
purposes.
*/
exports.add_user = function(userid, username, callback) {
  var update = {
    'user_id':       userid,
    'user_name':     username,
    'user_fullname': 'Development user',
    'user_email':    'dev@github-connect.com',
    'avatar_url':    'https://avatars.githubusercontent.com/u/0',
    'location':      'Somewhere'
  }

  Users.update({'user_id': userid}, update, {'upsert': true}).exec(function (err) {
    Users.findOne({'user_id': userid}).exec(function (err, user) {
      callback(err, user);
    });
  });
}


text:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>NoFlo web preview</title>

    <script src="./browser/noflo-ui-preview.js"></script>
    <script src="./browser/noflo-noflo-runtime-iframe/runtime/network.js"></script>
    <script src="../bower_components/coffee-script/extras/coffee-script.js"></script>
    <script>
      window.NofloIframeRuntime({
        baseDir: 'noflo-ui-preview'
      });
    </script>
    <script src="../bower_components/requirejs/require.js"></script>
    <script>
      requirejs.config({
        packages: [
          {
            name: 'React',
            location: '../bower_components/react',
            main: 'react'
          }
        ]
      });
    </script>
    <style>
      body {
        padding: 0px;
        margin: 0px;
        background-color: black;
        color: #ffffff;
        font-family: "SourceCodePro",Helvetica,Arial,sans-serif;
        font-family: proxima-nova-regular,"Helvetica Neue",Helvetica,Arial,sans-serif;
      }
    </style>
  </head>
  <body>
  </body>
</html>


text:
package main

import (
	"context"

	eventarc "cloud.google.com/go/eventarc/apiv1"
	eventarcpb "cloud.google.com/go/eventarc/apiv1/eventarcpb"
	"google.golang.org/api/iterator"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := eventarc.NewClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &eventarcpb.ListProvidersRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/eventarc/apiv1/eventarcpb#ListProvidersRequest.
	}
	it := c.ListProviders(ctx, req)
	for {
		resp, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			// TODO: Handle error.
		}
		// TODO: Use resp.
		_ = resp
	}
}

// [END eventarc_v1_generated_Eventarc_ListProviders_sync]


text:
package water.rapids.ast.prims.reducers;

import water.fvec.Frame;
import water.fvec.Vec;
import water.rapids.Env;
import water.rapids.vals.ValNum;
import water.rapids.ast.AstRoot;

/**
 * Optimization for the RollupStats: use them directly
 */
public abstract class AstNaRollupOp extends AstRollupOp {
  @Override
  public ValNum apply(Env env, Env.StackHelp stk, AstRoot asts[]) {
    Frame fr = stk.track(asts[1].exec(env)).getFrame();
    Vec[] vecs = fr.vecs();
    if (vecs.length == 0) return new ValNum(Double.NaN);
    double d = rup(vecs[0]);
    for (int i = 1; i < vecs.length; i++)
      d = op(d, rup(vecs[i]));
    return new ValNum(d);
  }
}


text:
require 'spec_helper'

module ITSF::FundReports
  describe TradeGroup do
    describe 'trade grouping' do
      before do
        @first_open_trade = FactoryGirl.create(:itsf_fund_reports_trades_trade,
          :trade_time  => 1.day.ago,
          :trade_price => 1000,
          :open_close_indicator => 'O',
          :quantity => 2
        )
        @second_open_trade = FactoryGirl.create(:itsf_fund_reports_trades_trade,
          :trade_time  => 1.day.ago + 1.hour,
          :trade_price => 1100,
          :open_close_indicator => 'O',
          :quantity => 2
        )
        @first_close_trade = FactoryGirl.create(:itsf_fund_reports_trades_trade,
          :trade_time  => 1.day.ago + 5.hours,
          :trade_price => 1500,
          :open_close_indicator => 'C',
          :quantity => 2
        )
        @second_close_trade = FactoryGirl.create(:itsf_fund_reports_trades_trade,
          :trade_time  => 1.day.ago + 6.hours,
          :trade_price => 1600,
          :open_close_indicator => 'C',
          :quantity => 2
        )
      end # before

      subject do
        trade_group = FactoryGirl.build(:itsf_fund_reports_trade_group)
        trade_group.trades.delete_all
        trade_group.trades << @first_open_trade
        trade_group.trades << @second_open_trade
        trade_group.trades << @first_close_trade
        trade_group.trades << @second_close_trade
        trade_group.save!
        trade_group
      end # subject

      describe 'first open calculation' do
        it 'should have the correct first open time' do
          subject.first_open_time.should eq(@first_open_trade.trade_time)
        end # it
      end # describe 'first open calculation'

      describe 'last close calculation' do
        it 'should have the correct last close time' do
          subject.last_close_time.should eq(@second_close_trade.trade_time)
        end # it
      end # describe 'last close calculation'

      describe 'p/l points calculation' do
        it 'should calculate the correct p/l in points'
#        it 'should calculate the correct p/l in points' do
#          subject.pnl_points.should eq(2000)
#        end # it
      end # describe 'p/l points calculation'
    end # describe 'trade grouping'

    describe 'associations' do
      it { should belong_to :symbol }
      it { should belong_to :underlying_symbol }
      it { should have_many :trades }
    end # describe 'associations'

    describe 'validations' do
      it 'should validate the equality of open and close quantities' do
      end # it

      it 'should validate the equality of multipliers' do
      end # it

      it 'should validate the equality trade symbols' do
      end # it
#      it { should validate_presence_of :first_open_time }
#      it { should validate_presence_of :last_close_time }
#      it { should validate_presence_of :multiplier }
#      # it { should validate_presence_of :pnl_points }
#      it { should validate_presence_of :symbol }
#      it { should validate_presence_of :underlying_symbol }
    end # describe 'validations'
  end # describe TradeGroup
end # module ITSF::FundReports


text:
package org.apache.camel.component.jpa;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import javax.persistence.EntityManagerFactory;

import org.apache.camel.Endpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.DefaultComponent;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.PropertiesHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * A JPA Component
 */
@Component("jpa")
public class JpaComponent extends DefaultComponent {

    private static final Logger LOG = LoggerFactory.getLogger(JpaComponent.class);

    private ExecutorService pollingConsumerExecutorService;

    @Metadata
    private EntityManagerFactory entityManagerFactory;
    @Metadata
    private PlatformTransactionManager transactionManager;
    @Metadata
    private TransactionStrategy transactionStrategy;
    @Metadata(defaultValue = "true")
    private boolean joinTransaction = true;
    @Metadata
    private boolean sharedEntityManager;
    @Metadata
    private Map<String, Class<?>> aliases = new HashMap<>();

    public JpaComponent() {
    }

    // Properties
    //-------------------------------------------------------------------------
    public EntityManagerFactory getEntityManagerFactory() {
        return entityManagerFactory;
    }

    /**
     * To use the {@link EntityManagerFactory}. This is strongly recommended to configure.
     */
    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
        this.entityManagerFactory = entityManagerFactory;
    }

    public PlatformTransactionManager getTransactionManager() {
        return transactionManager;
    }

    /**
     * To use the {@link PlatformTransactionManager} for managing transactions.
     */
    public void setTransactionManager(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    public TransactionStrategy getTransactionStrategy() {
        return transactionStrategy;
    }

    /**
     * To use the {@link TransactionStrategy} for running the operations in a transaction.
     */
    public void setTransactionStrategy(TransactionStrategy transactionStrategy) {
        this.transactionStrategy = transactionStrategy;
    }

    public boolean isJoinTransaction() {
        return joinTransaction;
    }

    /**
     * The camel-jpa component will join transaction by default. You can use this option to turn this off, for example
     * if you use LOCAL_RESOURCE and join transaction doesn't work with your JPA provider. This option can also be set
     * globally on the JpaComponent, instead of having to set it on all endpoints.
     */
    public void setJoinTransaction(boolean joinTransaction) {
        this.joinTransaction = joinTransaction;
    }

    public boolean isSharedEntityManager() {
        return sharedEntityManager;
    }

    /**
     * Whether to use Spring's SharedEntityManager for the consumer/producer. Note in most cases joinTransaction should
     * be set to false as this is not an EXTENDED EntityManager.
     */
    public void setSharedEntityManager(boolean sharedEntityManager) {
        this.sharedEntityManager = sharedEntityManager;
    }

    public void addAlias(String alias, Class<?> clazz) {
        this.aliases.put(alias, clazz);
    }

    /**
     * Maps an alias to a JPA entity class. The alias can then be used in the endpoint URI (instead of the fully
     * qualified class name).
     */
    public void setAliases(Map<String, Class<?>> aliases) {
        this.aliases = aliases;
    }

    public Map<String, Class<?>> getAliases() {
        return aliases;
    }

    synchronized ExecutorService getOrCreatePollingConsumerExecutorService() {
        if (pollingConsumerExecutorService == null) {
            LOG.debug("Creating thread pool for JpaPollingConsumer to support polling using timeout");
            pollingConsumerExecutorService
                    = getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this, "JpaPollingConsumer");
        }
        return pollingConsumerExecutorService;
    }

    // Implementation methods
    //-------------------------------------------------------------------------

    @Override
    protected Endpoint createEndpoint(String uri, String path, Map<String, Object> options) throws Exception {
        JpaEndpoint endpoint = new JpaEndpoint(uri, this);
        endpoint.setJoinTransaction(isJoinTransaction());
        endpoint.setSharedEntityManager(isSharedEntityManager());

        Map<String, Object> params = PropertiesHelper.extractProperties(options, "parameters.", true);
        if (!params.isEmpty()) {
            endpoint.setParameters(params);
        }

        // lets interpret the next string as an alias or class
        if (ObjectHelper.isNotEmpty(path)) {
            Class<?> type = aliases.get(path);
            if (type == null) {
                // provide the class loader of this component to work in OSGi environments as camel-jpa must be able
                // to resolve the entity classes
                type = getCamelContext().getClassResolver().resolveClass(path, JpaComponent.class.getClassLoader());
            }

            if (type != null) {
                endpoint.setEntityType(type);
            }
        }
        setProperties(endpoint, options);
        return endpoint;
    }

    @Override
    protected void doInit() throws Exception {
        super.doInit();

        // lookup entity manager factory and use it if only one provided
        if (entityManagerFactory == null) {
            Map<String, EntityManagerFactory> map
                    = getCamelContext().getRegistry().findByTypeWithName(EntityManagerFactory.class);
            if (map != null) {
                if (map.size() == 1) {
                    entityManagerFactory = map.values().iterator().next();
                    LOG.info("Using EntityManagerFactory found in registry with id [{}] {}",
                            map.keySet().iterator().next(), entityManagerFactory);
                } else {
                    LOG.debug("Could not find a single EntityManagerFactory in registry as there was {} instances.",
                            map.size());
                }
            }
        } else {
            LOG.info("Using EntityManagerFactory configured: {}", entityManagerFactory);
        }

        if (transactionStrategy != null) {
            LOG.info("Using TransactionStrategy configured: {}", transactionStrategy);
            return;
        }

        // lookup transaction manager and use it if only one provided
        if (transactionManager == null) {
            Map<String, PlatformTransactionManager> map
                    = getCamelContext().getRegistry().findByTypeWithName(PlatformTransactionManager.class);
            if (map != null) {
                if (map.size() == 1) {
                    transactionManager = map.values().iterator().next();
                    LOG.info("Using TransactionManager found in registry with id [{}] {}",
                            map.keySet().iterator().next(), transactionManager);
                } else {
                    LOG.debug("Could not find a single TransactionManager in registry as there was {} instances.", map.size());
                }
            }
        } else {
            LOG.info("Using TransactionManager configured on this component: {}", transactionManager);
        }

        // transaction manager could also be hidden in a template
        if (transactionManager == null) {
            Map<String, TransactionTemplate> map
                    = getCamelContext().getRegistry().findByTypeWithName(TransactionTemplate.class);
            if (map != null) {
                if (map.size() == 1) {
                    transactionManager = map.values().iterator().next().getTransactionManager();
                    LOG.info("Using TransactionManager found in registry with id [{}] {}",
                            map.keySet().iterator().next(), transactionManager);
                } else {
                    LOG.debug("Could not find a single TransactionTemplate in registry as there was {} instances.", map.size());
                }
            }
        }

        // warn about missing configuration
        if (entityManagerFactory == null) {
            LOG.warn(
                    "No EntityManagerFactory has been configured on this JpaComponent. Each JpaEndpoint will auto create their own EntityManagerFactory.");
        }
        if (transactionManager == null) {
            LOG.warn(
                    "No TransactionManager has been configured on this JpaComponent. Each JpaEndpoint will auto create their own JpaTransactionManager.");
        }
    }

    @Override
    protected void doStop() throws Exception {
        super.doStop();

        if (pollingConsumerExecutorService != null) {
            getCamelContext().getExecutorServiceManager().shutdown(pollingConsumerExecutorService);
            pollingConsumerExecutorService = null;
        }
    }
}


text:
#region License
//
// Copyright Tony Beveridge 2015. All rights reserved.
// MIT license applies.
//
#endregion

namespace ControlCentre.Models {

    public class TargetRequestModel : BaseRequestModel {
        public string Name { get; set; }
    }
}


text:
import './init';
import * as fs from 'fs';
import * as path from 'path';

import {MultipleComponentsMyComp} from '../src/a/multiple_components';
import {BasicComp} from '../src/basic';
import {createComponent} from './util';

describe('template codegen output', () => {
  const outDir = 'src';

  it('should be able to lower annotations as static fields', () => {
    const basicFilePath = path.join(outDir, 'basic.js');
    expect(fs.existsSync(basicFilePath)).toBeTruthy();
    const fileContent = fs.readFileSync(basicFilePath, 'utf8');
    expect(fileContent).not.toContain('Reflect.decorate');
    expect(fileContent).toContain('BasicComp.decorators = [');
  });

  it('should produce metadata.json outputs', () => {
    const metadataOutput = path.join(outDir, 'basic.metadata.json');
    expect(fs.existsSync(metadataOutput)).toBeTruthy();
    const output = fs.readFileSync(metadataOutput, {encoding: 'utf-8'});
    expect(output).toContain('"decorators":');
    expect(output).toContain('"module":"@angular/core","name":"Component"');
  });

  it('should write .d.ts files', () => {
    const dtsOutput = path.join(outDir, 'basic.d.ts');
    expect(fs.existsSync(dtsOutput)).toBeTruthy();
    expect(fs.readFileSync(dtsOutput, {encoding: 'utf-8'})).toContain('Basic');
  });

  it('should write .ngfactory.js for .d.ts inputs', () => {
    const factoryOutput = path.join('node_modules', '@angular', 'common', 'common.ngfactory.js');
    expect(fs.existsSync(factoryOutput)).toBeTruthy();
  });

  it('should be able to create the basic component', () => {
    const compFixture = createComponent(BasicComp);
    expect(compFixture.componentInstance).toBeTruthy();
  });

  it('should support ngIf', () => {
    const compFixture = createComponent(BasicComp);
    const debugElement = compFixture.debugElement;
    expect(debugElement.children.length).toBe(3);

    compFixture.componentInstance.ctxBool = true;
    compFixture.detectChanges();
    expect(debugElement.children.length).toBe(4);
    expect(debugElement.children[2].injector.get(MultipleComponentsMyComp)).toBeTruthy();
  });

  it('should support ngFor', () => {
    const compFixture = createComponent(BasicComp);
    const debugElement = compFixture.debugElement;
    expect(debugElement.children.length).toBe(3);

    // test NgFor
    compFixture.componentInstance.ctxArr = [1, 2];
    compFixture.detectChanges();
    expect(debugElement.children.length).toBe(5);
    expect(debugElement.children[2].attributes['value']).toBe('1');
    expect(debugElement.children[3].attributes['value']).toBe('2');
  });

  describe('i18n', () => {
    it('should inject the locale into the component', () => {
      const compFixture = createComponent(BasicComp);
      expect(compFixture.componentInstance.localeId).toEqual('fi');
    });

    it('should inject the translations format into the component', () => {
      const compFixture = createComponent(BasicComp);
      expect(compFixture.componentInstance.translationsFormat).toEqual('xlf');
    });

    it('should support i18n for content tags', () => {
      const containerElement = createComponent(BasicComp).nativeElement;
      const pElement = containerElement.querySelector('p');
      const pText = pElement.textContent;
      expect(pText).toBe('tervetuloa');
    });

    it('should have removed i18n markup', () => {
      const containerElement = createComponent(BasicComp).debugElement.children[0];
      expect(containerElement.attributes['title']).toBe('käännä teksti');
      expect(containerElement.attributes['i18n-title']).toBeUndefined();
    });
  });
});


text:
This executor type is used by default, it uses [Apache JMeter](http://jmeter.apache.org/) as underlying tool.

## JMeter Location & Auto-Installation

If there is no JMeter installed at the configured `path`, Taurus will attempt to install latest JMeter and Plugins into
this location, by default `~/.bzt/jmeter-taurus/bin/jmeter`. You can change this setting to your preferred JMeter location (consider putting it into `~/.bzt-rc` file). All module settings that relates to JMeter path and auto-installing are listed below:
```yaml
modules:
  jmeter:
    path: ~/.bzt/jmeter-taurus/bin/jmeter
    download-link: https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{version}.zip
    version: 3.0
    plugins:
    - jpgc-json=2.2
    - jmeter-ftp
    - jpgc-casutg
```
`plugins` option lets you describe list of JMeter plugins you want to use. If `plugins` option isn't found only following plugins will be installed: jpgc-casutg, jpgc-dummy, jpgc-ffw, jpgc-fifo, jpgc-functions, jpgc-json, jpgc-perfmon, jpgc-prmctl, jpgc-tst. Keep in mind: you can change plugins list only for clean installation. If you already have JMeter placed at `path` you need to remove it for plugins installation purpose.

## Run Existing JMX File
```yaml
execution:
- scenario: simple

scenarios:
  simple:
    script: tests/jmx/dummy.jmx
```

or simply `bzt tests/jmx/dummy.jmx`

TODO: explain how multi-thread group will accept concurrency with maintained proportion

## JMeter Properties
There are two places to specify JMeter properties: global at module-level and local at scenario-level. Scenario properties are merged into global properties and resulting set comes as input for JMeter, see corresponding `.properties` file in artifacts.
You may also specify system properties for JMeter in system-properties section. They comes as system.properties file in artifacts.

Global properties are set like this:

```yaml
modules:
  jmeter:
    properties:
      my-hostname: www.pre-test.com
      log_level.jmeter: WARN
      log_level.jmeter.threads: DEBUG
    system-properties:
      sun.net.http.allowRestrictedHeaders: "true"
```

Scenario-level properties are set like this:

```yaml
scenarios:
  prop_example:
    properties:
        my-hostname: www.prod.com
        log_level.jmeter: DEBUG
```

## Open JMeter GUI
When you want to verify or debug the JMX file that were generated from your requests scenario, you don't need to search for the file on disk, just enable GUI mode for JMeter module:

```yaml
modules:
  jmeter:
    gui: false  # set it to true to open JMeter GUI instead of running non-GUI test
```

For the command-line, use alias `-gui` or option `-o modules.jmeter.gui=true`, without the need to edit configuration file.

## Run JMeter in Distributed Mode
Distributed mode for JMeter is enabled with simple option `distributed` under execution settings, listing JMeter servers under it:

```yaml
execution:
- distributed:
  - host1.mynet.com
  - host2.mynet.com
  - host3.mynet.com
  scenario: some_scenario

scenarios:
  some_scenario:
    script: my-test.jmx
```
For accurate load calculation don't forget to choose different hostname values for slave hosts. If you have any properties specified in settings, they will be sent to remote nodes.

## Shutdown Delay
By default, Taurus tries to call graceful JMeter shutdown by using its UDP shutdown port (this works only for non-GUI). There is option to wait for JMeter to exit before killing it forcefully, called `shutdown-wait`. By default, its value is 5 seconds.

## Modifications for Existing Scripts

JMeter executor allows you to apply some modifications to the JMX file before running JMeter (this affects both existing JMXes and generated from requests):

```yaml
scenarios:
  modification_example:
    script: tests/jmx/dummy.jmx
    variables: # add User Defined Variables component to test plan,
               # overriding other global variables
      user_def_var: http://demo.blazemeter.com/api/user
      user_def_var2: user_def_val_2
    modifications:
      disable:  # Names of the tree elements to disable
      - Thread Group 1
      enable:  # Names of the tree elements to enable
      - Thread Group 2
      set-prop:  # Set element properties, selected as [Element Name]>[property name]
        "HTTP Sampler>HTTPSampler.connect_timeout": "0"
        "HTTP Sampler>HTTPSampler.protocol": "https"
```
If selector for set-prop isn't found, taurus tries to create stringProp jmx element with last element of selector as name and sets given value for it. So you can create simple properties in jmx if it's necessary.

## Building Test Plan from Config

Scenario that has `requests` element makes Taurus to generate the script for underlying tools automatically. For now, this is available for JMeter and partially available for some other tools.

The `requests` element must contain a list of requests, each with its settings and child elements (assertions, extractors). Also there are additional configuration elements for requests-based scenario, described below.

Scenario is the sequence of steps and some settings that will be used by underlying tools (JMeter, Grinder, Gatling) on execution stage.

Scenarios are listed in top-level `scenarios` element and referred from executions by their alias:

```yaml
scenarios:
  get-requests:  # the alias for scenario
    requests:
    - http://localhost/1
    - http://localhost/2

execution:
- scenario: get-requests  # alias from above is used
```

### Global Settings

Scenario has some global settings:

```yaml
scenarios:
  get-requests:
    store-cache: true  # browser cache simulation, enabled by default
    store-cookie: true  # browser cookies simulation, enabled by default
    headers: # global headers
      header-name: header-value
    think-time: 1s500ms  # global delay between each request
    timeout: 500ms  #  timeout for connecting, receiving results
    default-address: "https://www.blazedemo.com:8080"  # http request defaults scheme, domain, port
    keepalive: true  # true by default, applied on all requests in scenario
    retrieve-resources: true  # true by default, retrieves all embedded resources from HTML pages
    retrieve-resources-regex: ^((?!google|facebook).)*$  # regular expression used to match any resource
                                                         # URLs found in HTML document against. Unset by default
    concurrent-pool-size: 4  # concurrent pool size for resources download, 4 by default
    use-dns-cache-mgr: true  # use DNS Cache Manager to test resources
                             # behind dns load balancers. True by default.
    force-parent-sample: true  # generate only parent sample for transaction controllers.
                               # True by default
    content-encoding: utf-8  # global content encoding, applied to all requests.
                             # Unset by default
    follow-redirects: true  # follow redirects for all HTTP requests
    data-sources: # list of external data sources
    - path/to/my.csv  # this is a shorthand form
    - path: path/to/another.csv  # this is full form, path option is required
      delimiter: ';'  # CSV delimiter, auto-detected by default
      quoted: false  # allow quoted data
      loop: true  # loop over in case of end-of-file reached if true, stop thread if false
      variable-names: id,name  # delimiter-separated list of variable names, empty by default
```

Note that `timeout` also sets duration assertion that will mark response failed if response time was more than timeout.

If you want to use JMeter properties in `default-address`, you'll have to specify mandatory scheme and separate address/port. Like this: `default-address: https://${\__P(hostname)}:${\__P(port)}`.

### Requests

Request objects can be of two kinds:
1. Plain HTTP requests
2. Logic blocks that allow user to control execution flow of test session.

#### HTTP Requests
The base element for requests scenario is HTTP Request. In its simplest form it contains just the URL as string:

```yaml
scenarios:
  get-requests:
    requests:
    - http://localhost/1
    - http://localhost/2
```

The full form for request is dictionary, all fields except `url` are optional:

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/  # url to hit
      method: GET  # request method (GET, POST, PUT, DELETE)
      label: homepage  # sampler label

      body: 'request-body-string'  # if present, will be used as body
      body:  # generate query string based on parameters and request type
        param1: value1
        param2: value2
      body-file: path/to/file.txt  # this file contents will be used as post body

      upload-files:  # attach files to form (and enable multipart/form-data)
      - param: summaryReport  # form parameter name
        path: report.pdf  # path to file
        mime-type: application/pdf  # optional, Taurus will attempt to guess it automatically

      headers:  # local headers that override global
        Authentication: Token 1234567890
        Referer: http://taurus.blazemeter/docs
      think-time: 1s  # local think-time, overrides global
      timeout: 1s  # local timeout, overrides global
      content-encoding: utf-8  # content encoding (at JMeter's level), unset by default
      follow-redirects: true  # follow HTTP redirects

      extract-regexp: {}  # explained below
      extract-jsonpath: {}  # explained below
      assert: []  # explained below
      jsr223: []  # explained below
```

##### Extractors

Extractors are the objects that attached to request to take a piece of the response and use it in following requests.
The concept is based on JMeter's extractors. The following types of extractors are supported:

- by regular expression
- by JSONPath expression
- by CSS/JQuery selectors
- by XPath query

To specify extractors in shorthand form, use following configuration:

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/
      extract-regexp: # dictionary under it has form <var name>: <regular expression>
        page_title: <title>(\w+)</title>  #  must have at least one capture group
      extract-jsonpath: # dictionary under it has form <var name>: <JSONPath expression>
        varname: $.jsonpath[0].expression
    - url: http://blazedemo.com/${varname}/${page_title}  # that's how we use those variables
      extract-css-jquery: # dictionary under it has form <var name>: <CSS/JQuery selector>
        extractor1: input[name~=my_input]
    - url: http://blazedemo.com/${varname}/${extractor1}.xml
      extract-xpath:
        title: /html/head/title
```

The full form for extractors is:

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/
      extract-regexp:
        page_title:
          regexp: <title>(\w+)</title>  # regular expression
          default: NOT_FOUND  # default value to use when regexp not found
          match-no: 1  # if multiple values has matched, which match use (0=random)
          template: 1  # which capture group to take, integer or template string
          subject: body  #  subject for search
      extract-jsonpath:
        varname:
          jsonpath: $.jsonpath[0]  # jsonpath expression
          default: NOT_FOUND  # default value to use when jsonpath not found
    - url: http://blazedemo.com/${varname}/${page_title}
      extract-css-jquery:
        extractor2:
          expression: input[name=JMeter]
          attribute: value
          match-no: 1
          default: NOT_FOUND
    - url: http://blazedemo.com/${varname}/${extractor2}.xml
      extract-xpath:
        destination:
          xpath: /order/client/address
          default: NOT_FOUND
          validate-xml: false
          ignore-whitespace: true
          use-tolerant-parser: false
```

Possible subjects for regexp are:
  - `body`
  - `headers`
  - `http-code`

##### Assertions

Assertions are attached to request elements and used to set fail status on the response. Fail status for the response is
not the same as response code for JMeter.
Currently three types of response assertions are available.

First one checks http response fields, its short form looks like this:

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/
      assert:  # contains list of regular expressions to check
      - .+App.+
```

The full form has following format:

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/
      assert:
       - contains:  # list of strings to check
         - .+App.+
         subject: body  # subject for search
         regexp: true  # treat string as regular expression
         not: false  # invert condition - fail if found
         assume-success: false  # mark sample successful before asserting it
```

Possible subjects are:
  - `body`
  - `headers`
  - `http-code`

The second assertion type is used to perform validation of JSON response against JSONPath expression.

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/
      assert-jsonpath:  # contains list of options
        - "$."  # if this JSONPath not found, assert will fail
        - "$.result[0]" # there can be multiple JSONPaths provided
```

Full form:

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/
      assert-jsonpath:
      - jsonpath: "$." # path to value, validation fails if path not exists
        validate: true # validate against expected value
        expected-value: "value" # the value we are expecting to validate, default: false
        regexp: true  # if the value is regular expression, default: true
        expect-null: false  # expected value is null
        invert: false # invert condition
```

And the third assertion type uses XPath query to validate XML response.

```yaml
scenarios:
  assertion-demo:
    requests:
    - url: http://blazedemo.com/
      assert-xpath:  # contains list of xpath queries
        - "/bookstore/book"  # if this XPath won't be matched, assert will fail
        - "/html/head/title" # you can provide multiple XPath queries
```

Full form:

```yaml
scenarios:
  my-req:
    requests:
    - url: http://blazedemo.com/
      assert-xpath:
      - xpath: "/html/head/title/text()='My title'" # query that compares XPath query result with some value
        use-tolerant-parser: false  # use error-tolerant XML parser
        ignore-whitespace: true # ignore whitespaces in XML (has no effect when `use-tolerant-parser` is true)
        validate: false # validate XML against its schema (has no effect when `use-tolerant-parser` is true)
        invert: false # invert condition
```

##### JSR223 Blocks

Sometimes you may want to use a JSR223 Pre/Post Processor to execute a code block before or
after each request. Taurus allows that with `jsr223` block.

Minimal example that will generate one JSR223 Post Processor.
```yaml
scenarios:
  jsr-example:
    requests:
    - url: http://blazedemo.com/
      jsr223: 'vars.put("varname", "somevalue")'  # inline script to execute, unless script-file is specified
```

The example above uses defaults and inline script. If you want to use language different from groovy or use separate
script file, please use extended form of `jsr223` with key-value options.

Each jsr223 element can define the following fields:
- `language` - script language ('beanshell', 'bsh', 'ecmascript', 'groovy', 'java', 'javascript', 'jexl', 'jexl2')
- `script-file` - path to script file
- `script-text` - inline code, specified directly in config file
- `parameters` - string of parameters to pass to script, empty by default
- `execute` - whether to execute script before or after the request

If `execute` field is set to `after` - Taurus will generate a JSR223 PostProcessor, if set to `before` - a PreProcessor.
By default it's set to `after`.

Full form:
```yaml
scenarios:
  jsr-example:
    requests:
    - url: http://blazedemo.com/
      jsr223:
      - language: javascript
        script-file: preproc.js
        parameters: foo bar
        execute: before
      - language: beanshell
        script-file: postproc.bsh
        execute: after
```

#### Logic Blocks

Taurus allows to control execution flow with the following constructs:
- `if` blocks
- `loop` blocks
- `while` blocks
- `foreach` blocks
- `transaction` blocks
- `include-scenario` blocks
- `action` blocks

##### If Blocks

`if` blocks allow conditional execution of HTTP requests.

Each `if` block should contain a mandatory `then` field, and an optional `else` field. Both `then` and `else` fields
should contain lists of requests.

Here's a simple example:

```yaml
scenarios:
  if_example:
    variables:
      searchEngine: google
    requests:
    - if: '"${searchEngine}" == "google"'
      then:
        - https://google.com/
      else:
        - https://bing.com/
```

Note that Taurus compiles `if` blocks to JMeter's `If Controllers`, so `<condition>` must be in JMeter's format.

Logic blocks can also be nested:

```yaml
scenarios:
  nested_example:
    requests:
    - if: <condition1>
      then:
      - if: <condition2>
        then:
        - https://google.com/
        else:
        - https://yahoo.com/
      else:
      - https://bing.com/
```

And here's the real-world example of using `if` blocks:

```yaml
scenarios:
  complex:
    requests:
    # first request is a plain HTTP request that sets `status_code`
    # and `username` variables
    - url: https://api.example.com/v1/media/search
      extract-jsonpath:
        status_code: $.meta.code
        username: $.data.[0].user.username

    # branch on `status_code` value
    - if: '"${status_code}" == "200"'
      then:
        - https://example.com/${username}
```

##### Loop Blocks

`loop` blocks allow repeated execution of requests. Nested requests are to be specified with `do` field.

```yaml
scenarios:
  loop_example:
    requests:
    - loop: 10
      do:
      - http://blazedemo.com/
```

If you want to loop requests forever, you can specify string `forever` as `loop` value.
```yaml
scenarios:
  forever_example:
    requests:
    - loop: forever
      do:
      - http://blazedemo.com/
```

Note that `loop` blocks correspond to JMeter's `Loop Controllers`.

##### While Blocks

`while` block is similar to `while` loops in many programming languages. It allows conditional repeated execution of
requests. `while` blocks are compiled to JMeter's `While Controllers`.

```yaml
scenarios:
  while_example:
    requests:
    - while: ${JMeterThread.last_sample_ok}
      do:
      - http://blazedemo.com/
```

##### Foreach Blocks

`foreach` blocks allow you to iterate over a collection of values. They are compiled to JMeter `ForEach Controllers`.

Syntax:
```yaml
requests:
- foreach: <elementName> in <collection>
  do:
  - http://${elementName}/
```

Concrete example:
```yaml
scenarios:
  complex_foreach:
    requests:
    - url: https://api.example.com/v1/media/search
      extract-jsonpath:
        usernames: $.data.[:100].user.username  # grab first 100 usernames
    - foreach: name in usernames
      do:
      - https://example.com/user/${name}
```

##### Transaction Blocks

`transaction` blocks allow wrapping http requests in a transaction. `transaction` blocks correspond to JMeter's
`Transaction Controllers`.

Example:
```yaml
scenarios:
  transaction_example:
    requests:
    - transaction: Customer Session
      do:
      - http://example.com/shop
      - http://example.com/shop/items/1
      - http://example.com/shop/items/2
      - http://example.com/card
      - http://example.com/checkout
```

##### Include Scenario blocks
`include-scenario` block allows you to include scenario in another one. You can use it to split your test plan into
a few of independent scenarios that can be reused.

Example:
```yaml
scenarios:
  login:
    data-sources:
    - logins.csv
    requests:
    - url: http://example.com/login
      method: POST
      body:
        user: ${username}
        password: ${password}
  logout:
    requests:
    - url: http://example.com/logout
      method: POST
   shop-session:
     requests:
     - include-scenario: login
     - http://example.com/shop/items/1
     - http://example.com/checkout
     - include-scenario: logout
```

Taurus translates each `include-scenario` block to a JMeter's `Simple Controller` and puts all scenario-level
settings and requests there.
Keep in mind: the following scenario-level parameters of including scenario have no effect for included ones:
- `keepalive`
- `timeout`
- `think-time`
- `follow-redirects`

##### Action Blocks

`action` block allows you to specify a thread-specific action that will be performed. You can use it to pause or stop
the current thread, or force it to go to the next loop iteration.

The following actions are available:
- `pause` - pause the target thread (pause duration is controlled with `pause-duration` field)
- `stop` - stop the target thread gracefully
- `stop-now` - stop the test without waiting for samples to complete
- `continue` - send target thread to the next iteration of the loop

Actions can be applied to the following targets:
- `current-thread` - set by default
- `all-threads` - action will be applied to all threads (unavailable for `continue` action)

Examples:
```yaml
scenarios:
  action_example:
    requests:
    - action: pause
      target: current-thread
      pause-duration: 1s500ms
    - action: stop-now
      target: all-threads
```

## JMeter Test Log
You can tune JTL file content with option `write-xml-jtl`. Possible values are 'error' (default), 'full', or any other value for 'none'. Keep in mind: max `full` logging can seriously load your system.
```yaml
execution:
- write-xml-jtl: full
  scenario: simple_script

scenarios:
  simple_script:
    script: my.jmx

```
Another way to adjust verbosity is to change flags in `xml-jtl-flags` dictionary. Next example shows all flags with default values (you don't have to use full dictionary if you want to change some from them):
```yaml
modules:
  jmeter:
    xml-jtl-flags:
      xml: true
      fieldNames: true
      time: true
      timestamp: true
      latency: true
      success: true
      label: true
      code: true
      message: true
      threadName: true
      dataType: true
      encoding: true
      assertions: true
      subresults: true
      responseData: false
      samplerData: false
      responseHeaders: true
      requestHeaders: true
      responseDataOnError: true
      saveAssertionResultsFailureMessage: true
      bytes: true
      threadCounts: true
      url: true
```

Remember: some logging information might be used by `[assertions](#Assertions)` so change log verbosity can affect them.

## JMeter JVM Memory Limit

You can tweak JMeter's memory limit (aka, `-Xmx` JVM option) with `memory-xmx` setting.
Use `K`, `M` or `G` suffixes to specify memory limit in kilobytes, megabytes or gigabytes.

Example:
```yaml
modules:
  jmeter:
    memory-xmx: 4G  # allow JMeter to use up to 4G of memory
```

## SoapUI Integration

You can specify SoapUI projects in place of JMX scripts for JMeter executor. The executor will convert them into
Taurus scenarios and execute them with JMeter.

Example:
```yaml
execution:
- concurrency: 10
  hold-for: 5m
  scenario: soapui-project

scenarios:
  soapui-project:
    script: project.xml
    test-case: TestIndex
```

You can read more on that [here](SoapUI.md).


text:
package com.epam.rft.atsy.web.controllers.rest;

import com.epam.rft.atsy.service.PositionService;
import com.epam.rft.atsy.service.domain.ChannelDTO;
import com.epam.rft.atsy.service.domain.PositionDTO;
import com.epam.rft.atsy.web.controllers.LogicallyDeletableAbstractController;
import com.epam.rft.atsy.web.exceptionhandling.RestResponse;
import com.epam.rft.atsy.web.messageresolution.MessageKeyResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.Locale;
import javax.validation.Valid;

/**
 * A REST controller for retrieving the available positions in JSON format.
 */
@RestController
@RequestMapping(value = "/secure/positions")
public class PositionController extends LogicallyDeletableAbstractController<PositionDTO> {

  private static final String EMPTY_POSITION_NAME_MESSAGE_KEY = "settings.positions.error.empty";

  @Autowired
  public PositionController(PositionService positionService,
                            MessageKeyResolver messageKeyResolver) {
    super(positionService, messageKeyResolver);
  }

  @Override
  public ResponseEntity<RestResponse> saveOrUpdate(@RequestBody @Valid PositionDTO positionDTO,
                                                   BindingResult result, Locale locale) {
    if (!result.hasErrors()) {
      this.logicallyDeletableService.saveOrUpdate(positionDTO);

      return new ResponseEntity<>(RestResponse.NO_ERROR, HttpStatus.OK);
    } else {
      String
          errorMessage =
          this.messageKeyResolver.resolveMessageOrDefault(EMPTY_POSITION_NAME_MESSAGE_KEY);

      RestResponse restResponse = new RestResponse(errorMessage);

      return new ResponseEntity<>(restResponse, HttpStatus.BAD_REQUEST);
    }
  }

  @RequestMapping(method = RequestMethod.GET)
  public Collection<ChannelDTO> getPositions() {
    return logicallyDeletableService.getAllNonDeletedDto();
  }
}


text:
layout: doc-page
title: "Kind Polymorphism"
---

Normally type parameters in Scala are partitioned into _kinds_. First-level types are types of values. Higher-kinded types are type constructors
such as `List` or `Map`. The kind of a type is indicated by the top type of which it is a subtype. Normal types are subtypes of `Any`,
covariant single argument type constructors such as `List` are subtypes of `[+X] =>> Any`, and the `Map` type constructor is
a subtype of `[X, +Y] =>> Any`.

A type can be used only as prescribed by its kind. Subtypes of `Any` cannot be applied to type arguments whereas subtypes of `[X] =>> Any`
_must_ be applied to a type argument, unless they are passed to type parameters of the same kind.

Sometimes we would like to have type parameters that can have more than one kind, for instance to define an implicit
value that works for parameters of any kind. This is now possible through a form of (_subtype_) kind polymorphism.
Kind polymorphism relies on the special type `scala.AnyKind` that can be used as an upper bound of a type.

```scala
def f[T <: AnyKind] = ...
```

The actual type arguments of `f` can then be types of arbitrary kinds. So the following would all be legal:

```scala
f[Int]
f[List]
f[Map]
f[[X] =>> String]
```

We call type parameters and abstract types with an `AnyKind` upper bound _any-kinded types_.
Since the actual kind of an any-kinded type is unknown, its usage must be heavily restricted: An any-kinded type
can be neither the type of a value, nor can it be instantiated with type parameters. So about the only
thing one can do with an any-kinded type is to pass it to another any-kinded type argument.
Nevertheless, this is enough to achieve some interesting generalizations that work across kinds, typically
through advanced uses of implicits.

(todo: insert good concise example)

Some technical details: `AnyKind` is a synthesized class just like `Any`, but without any members. It extends no other class.
It is declared `abstract` and `final`, so it can be neither instantiated nor extended.

`AnyKind` plays a special role in Scala's subtype system: It is a supertype of all other types no matter what their kind is. It is also assumed to be kind-compatible with all other types. Furthermore, `AnyKind` is treated as a higher-kinded type (so it cannot be used as a type of values), but at the same time it has no type parameters (so it cannot be instantiated).

**Note**: This feature is considered experimental but stable and it can be disabled under compiler flag
(i.e. `-Yno-kind-polymorphism`).