text:
var inquirer = require("inquirer");
var cryptoLib = require("../lib/crypto.js");
var accountHelper = require("../helpers/account.js");

function genPubkey() {
	inquirer.prompt([
		{
			type: "password",
			name: "secret",
			message: "Enter secret of your testnet account",
			validate: function (value) {
				var done = this.async();

				if (value.length == 0) {
					done("Secret is too short, minimum is 1 character");
					return;
				}

				if (value.length > 100) {
					done("Secret is too long, maximum is 100 characters");
					return;
				}

				done(true);
			}
		}
	], function (result) {
		var account = accountHelper.account(result.secret.trim());
		console.log("Public key: " + account.keypair.publicKey);
		console.log("Address: " + account.address);
	});
}

function genAccount() {
	inquirer.prompt([
		{
			type: "input",
			name: "amount",
			message: "Enter number of accounts to generate",
			validate: function (value) {
				var num = parseInt(value);
				return !isNaN(num);
			}
		}
	], function (result) {
		var n = parseInt(result.amount);
		var accounts = [];

		for (var i = 0; i < n; i++) {
			var a = accountHelper.account(cryptoLib.generateSecret());
			accounts.push({
				address: a.address,
				secret: a.secret,
				publicKey: a.keypair.publicKey
			});
		}
		console.log(accounts);
		console.log("Done");
	});
}

module.exports = function (program) {
  program
		.command("crypto")
		.description("crypto operations")
		.option("-p, --pubkey", "generate public key from secret")
		.option("-g, --generate", "generate random accounts")
		.action(function (options) {
			if (options.pubkey) {
				genPubkey();
			} else if (options.generate) {
				genAccount();
			} else {
				console.log("'node crypto -h' to get help");
			}
		});
}


text:
from xml_tools import xml_get_text

class State(object):

    def __init__(self, deltacloud, dom):
        self._deltacloud = deltacloud
        self.xml = dom.toxml()
        self.name = xml_get_text(dom, "name")[0]
        self.transitions = []

    def __repr__(self):
        return self.xml

redpajama_set_name: RedPajamaGithub


text:
#define WIN32_LEAN_AND_MEAN
#include "config.h"
#ifdef HAVE_ALAZAR
#include <Windows.h>
#include <stdlib.h>
#include <stdio.h> //for logging
#include <AlazarApi.h>
#include <AlazarCmd.h>
#include "alazar.h"

/** \file

    \todo Only modify input levels for enabled channels.
    \todo Test triggering.
    \todo Organize static interface and document a little.
    \todo ?Add a method for configuring sample rate.

    \section Macros

    \def LOG(...)          Used like a printf() call.  All logging-related messages should for this module should go through LOG()
    \def ENDL              The end-of-line character(s) to use.
    \def TRY(e)            Jumps to a label named "Error," if the expression \a e evaluates to falss and reports the event.
    \def ERR(e)            Similar to try, but checks for error codes generated by API calls.  \a e should evaluate to an ATS SDK error code.
    \def NEW(e,type,count) Shorthand expression that allocates an array of \a count objects sized by \type.  Checks to make sure the pointer is not NULL and zeros the array.
*/

#if 1 // PROFILING
#define TS_OPEN(name)   timestream_t ts__=timestream_open(name)
#define TS_TIC          timestream_tic(ts__)
#define TS_TOC          timestream_toc(ts__)
#define TS_CLOSE        timestream_close(ts__)
#else
#define TS_OPEN(name)
#define TS_TIC
#define TS_TOC
#define TS_CLOSE
#endif

#define DEBUG 1
#if DEBUG==0
    #define DBG(...)
    #define DBG_VERBOSE(...)
#elif DEBUG==1
    #define DBG(...) LOG(__VA_ARGS__)
    #define DBG_VERBOSE(...)
#else
    #define DBG(...) LOG(__VA_ARGS__)
    #define DBG_VERBOSE(...) LOG(__VA_ARGS__)
#endif

#define LOG(...)          printf(__VA_ARGS__)
#define ENDL              "\n"
static void breakme() {LOG(" ");}
#define REPORT(type,e,msg)     LOG("%s(%d) - %s(): %s"ENDL "\t%s"ENDL "\tExpression evaluated as false."ENDL "\t%s"ENDL,__FILE__,__LINE__,__FUNCTION__,type,e,msg)
#define REPORT_ATS(code,e)     LOG("%s(%d) - %s(): ATS API"ENDL "\t%s"ENDL "\tAlazar API call failed (error code %d)."ENDL "\t%s"ENDL ,__FILE__,__LINE__,__FUNCTION__,e,code,AlazarErrorToText(code))
#define TRY(e)            do{if(!(e)){REPORT("Error"  ,#e,"" ); breakme(); goto Error;}}while(0)
#define WARN(e,msg)       do{if(!(e)){REPORT("Warning",#e,msg);                       }}while(0)
#define FAIL(msg)         do{if(!(e)){REPORT("Error"  ,"Forced failure.",msg);            goto Error;}}while(0)
#define ERR(e)            do{RETURN_CODE code=(e); if(code!=ApiSuccess) {REPORT_ATS(code,#e); breakme(); goto Error;}}while(0)
#define ATSWARN(e)        do{RETURN_CODE code=(e); if(code!=ApiSuccess) {REPORT_ATS(code,#e); breakme();            }}while(0)
#define NEW(e,type,count)  TRY((e)=(type*)calloc(count,sizeof(type)))
#define ZERO(e,type,count) memset((e),0,count*sizeof(type))
#define SAFEFREE(e)       do{if(e) {free(e); (e)=NULL;}}while(0)

#define VALIDATE(e)       do{if(!(e) || !((e)->cfg)) { LOG("%s(%d): %s"ENDL "\tContext is invalid.  There was a past error."ENDL,__FILE__,__LINE__,__FUNCTION__); breakme(); goto Error;} }while(0)

#define SUCCESS (1)
#define FAILURE (0)

#define BOARD(i) (ctx->boards[i])
#define BOARDS   (ctx[0]->boards)

#define BUFS_PER_BOARD (2)
#define MAXBOARDS      (4)
#define CHANSPERBOARD  (2)

/** Configuration parameters.

 Reference counted.  The device will hold a reference to a configuration
 object until it is disarmed.
 */
struct _alazar_cfg_t
{
  U32 ref;                                                                 ///< reference counter
  U32 nsamples;                                                            ///< samples per record
  U32 nrecords;                                                            ///< number of records
  U32 sample_rate_id;                                                      ///< ATS-SDK constant specifying sample rate
  double line_trig_lvl_volts;                                              ///< 0-255.  Full range given by input_range_id.
  U32 aux_out_board_id;                                                    ///< a board id, 0-3 depending on how many boards are in the system.
  U32 enable[MAXBOARDS][CHANSPERBOARD];                                    ///< bool indicating whether to enable a channel
  U32 input_range_ids[MAXBOARDS][CHANSPERBOARD];                           ///< ATS-SDK constant specifying input range
};
/** Device context for the board system. */
struct _alazar_t
{ U32          system_id;                                                  ///< valid system id's are 1..systemCount (inclusive)
  U32          nboards;                                                    ///< valid board id's are 1..board_count (inclusive)
  HANDLE       boards[MAXBOARDS];                                          ///< handles used to adress the boards in the system
  void        *bufs[MAXBOARDS][BUFS_PER_BOARD];                            ///< array of page-locked buffers for async DMA transfers
  RETURN_CODE  last;                                                       ///< error code from last ATS SDK call.
  alazar_cfg_t cfg;                                                        ///< parameters used to configure the device.
  U32          is_started;                                                 ///< Indicates acquisition has been started.
  U32          ibuf;                                                       ///< Index to the current read point of bufs.
  SRWLOCK      lock;                                                       ///< Mutex to protect access
  char         lock_mode;
};

//  EXTRAS                     ////////////////////////////////////////////

/* public */
int alazar_print_version(FILE* fp)
{
  U8 major,minor,rev;
  ERR(AlazarGetSDKVersion(&major,&minor,&rev));
  fprintf(fp,"Alazar SDK Version %u.%u.%u\n",major,minor,rev);
  ERR(AlazarGetDriverVersion(&major,&minor,&rev));
  fprintf(fp,"Alazar Driver Version %u.%u.%u\n",major,minor,rev);

  { int i,n=0;
    TRY(AlazarNumOfSystems()==1);             //ensure single system
    TRY(n=AlazarBoardsInSystemBySystemID(1)); //ensure >0
    fprintf(fp,"Alazar Firmware(CPLD) Version:\n");
    for(i=0;i<n;++i)
    { HANDLE board=AlazarGetBoardBySystemID(1,i+1);
      ERR(AlazarGetCPLDVersion(board,&major,&minor));
      fprintf(fp,"\tBoard %2d - Version %u.%u (HANDLE: 0x%p)\n",i,major,minor,board);
    }
  }
  return 1;
Error:
  fprintf(fp,"Error querying Alazar ATS SDK version numbers.\n");
  return 0;
}

//  STATIC INTERFACE - Queries ////////////////////////////////////////////

/** \returns the number of enabled channels across all boards */
static size_t active_channel_count(alazar_t ctx)
{
  unsigned i,j,c=0;
  VALIDATE(ctx);
  if(!ctx->cfg) return 0;
  for(i=0;i<ctx->nboards;++i)  // two channels per board
    for(j=0;j<2;++j)
      c+=ctx->cfg->enable[i][j];
  return c;
Error:
  return 1; // avoid divide by zero
}

/** \returns the size in bytes required to acquire all channels */
static size_t buffer_size_bytes(alazar_t ctx)
{ size_t out;
  VALIDATE(ctx);
  out=active_channel_count(ctx)*ctx->cfg->nrecords*ctx->cfg->nsamples*2;
  DBG_VERBOSE("Buffer Size Bytes: %d"ENDL
      "\tActive Channel Count: %d"ENDL
      "\tRecords             : %d"ENDL
      "\tSamples             : %d"ENDL
      "\tBpp                 : %d"ENDL,
      (int)out,
      (int)active_channel_count(ctx),
      (int)ctx->cfg->nrecords,
      (int)ctx->cfg->nsamples,
      (int)2);
  return out; /*2 Bpp*/
Error:
  return 0;
}

/** \returns true if the device is armed, otherwise false */
static int alazar_is_armed(alazar_t ctx)
{
  return ctx->cfg!=0;
}

/** \returns true if acquisition has been started, otherwise false */
static int alazar_is_started(alazar_t ctx)
{  return ctx->is_started;
}

/** \returns the channel mask specifying enabled channels on board \a i */
static U32 channel_mask(alazar_t ctx, int i)
{
  return (ctx->cfg->enable[i][0]?CHANNEL_A:0)
       | (ctx->cfg->enable[i][1]?CHANNEL_B:0);
}

/** Translates a rate id defined by the ATS-SDK into a real number.
    \returns the sample rate in Hz.
*/
static double samples_per_second(U32 rate_id)
{
  switch(rate_id)
  {
  case SAMPLE_RATE_1KSPS		: return   1e3;
  case SAMPLE_RATE_2KSPS		: return   2e3;
  case SAMPLE_RATE_5KSPS		: return   5e3;
  case SAMPLE_RATE_10KSPS		: return  10e3;
  case SAMPLE_RATE_20KSPS		: return  20e3;
  case SAMPLE_RATE_50KSPS		: return  50e3;
  case SAMPLE_RATE_100KSPS	: return 100e3;
  case SAMPLE_RATE_200KSPS	: return 200e3;
  case SAMPLE_RATE_500KSPS	: return 500e3;
  case SAMPLE_RATE_1MSPS		: return   1e6;
  case SAMPLE_RATE_2MSPS		: return   2e6;
  case SAMPLE_RATE_5MSPS		: return   5e6;
  case SAMPLE_RATE_10MSPS		: return  10e6;
  case SAMPLE_RATE_20MSPS		: return  20e6;
  case SAMPLE_RATE_25MSPS		: return  25e6;
  case SAMPLE_RATE_50MSPS		: return  50e6;
  case SAMPLE_RATE_100MSPS	: return 100e6;
  case SAMPLE_RATE_125MSPS	: return 125e6;
  case SAMPLE_RATE_160MSPS	: return 160e6;
  case SAMPLE_RATE_180MSPS	: return 180e6;
  case SAMPLE_RATE_200MSPS	: return 200e6;
  case SAMPLE_RATE_250MSPS  : return 250e6;
  case SAMPLE_RATE_500MSPS  : return 500e6;
  case SAMPLE_RATE_1GSPS    : return   1e9;
  case SAMPLE_RATE_2GSPS    : return   2e9;
  default:
    /// \todo better exception handling here?
    WARN(0,"Unrecognized sample rate id.");
    return 0.0;
  }
}

/** Queries the operating system for the page size */
static unsigned page_alignment_samples()
{
  unsigned bytes;
#ifdef _MSC_VER
  {
    SYSTEM_INFO info={0};
    GetSystemInfo(&info);
    bytes=info.dwPageSize;
  }
#else
  FAIL("Not implemented.");
Error:
  abort();
  return 0;
#endif
  return bytes/2; /*2 bytes per sample*/
}

//  STATIC INTERFACE - Memory management //////////////////////////////////

/** Allocates page aligned memory */
static void* page_alloc(size_t bytes)
{ void *out;
  TRY(bytes>0);
#ifdef _MSC_VER
    TRY(out=VirtualAlloc(NULL,bytes,MEM_COMMIT,PAGE_READWRITE));
#else
    FAIL("Allocation of page locked memory with valloc() not implemented (yet).");
#endif
  return out;
Error:
  return NULL;
}

/** Frees page aligned memory */
static void page_dealloc(void **buf)
{
  if(!buf || !*buf) return;
#ifdef _MSC_VER
  VirtualFree(*buf,0,MEM_RELEASE);
  *buf=NULL;
#else
  FAIL("DeAllocation of page locked memory not implemented (yet).");
Error:
  abort()
#endif;
}

static void free_alazar_t(alazar_t *ctx)
{ if(ctx && *ctx)
  { free(ctx[0]);
    ctx[0]=0;
  }
}

/** allocates async DMA bufs for each board */
static int alloc_bufs(alazar_t ctx)
{ unsigned i,j;
  VALIDATE(ctx);
  { const size_t bytes = 2*buffer_size_bytes(ctx)/active_channel_count(ctx); // two channels per board
    TRY(bytes>0);
    TRY(ctx && ctx->nboards>0);
    for(j=0;j<ctx->nboards;++j)
      for(i=0;i<BUFS_PER_BOARD;++i)
        TRY(ctx->bufs[j][i]=page_alloc(bytes));
  }
  return SUCCESS;
Error:
  return FAILURE;
}

/* public */
void alazar_free_buf(void **buf)
{ free(*buf);
  *buf=0;
}

static void free_bufs(alazar_t ctx)
{ unsigned i,j;
  if(!ctx) return;
  if(!ctx->bufs) return;
  for(j=0;j<ctx->nboards;++j)
    for(i=0;i<BUFS_PER_BOARD;++i)
      page_dealloc(ctx->bufs[j]+i);
}

static U32 line_trigger_level(alazar_t ctx)
{ VALIDATE(ctx);
  return (U32) (128.0*(1.0+ctx->cfg->line_trig_lvl_volts/5.0)); // assumes 5.0V range on external trigger
Error:
  return 0; // this is a valid trigger level...can't test for error with this value
}

static void lock(alazar_t ctx, char mode)
{ switch(mode)
  { case 'r': AcquireSRWLockShared(&ctx->lock); break;
    case 'w': AcquireSRWLockExclusive(&ctx->lock); break;
    default: abort();
  }
  //LOG("+++ ALAZAR LOCK ACQUIRED MODE %c\n",mode);
  ctx->lock_mode=mode;
}
static void unlock(alazar_t ctx)
{ char mode=ctx->lock_mode;
  ctx->lock_mode=0;
  //LOG("--- ALAZAR LOCK RELEASED MODE %c\n",mode);
  switch(mode)
  { case 'r': ReleaseSRWLockShared(&ctx->lock); break;
    case 'w': ReleaseSRWLockExclusive(&ctx->lock); break;
    default: abort();
  }
}

//  DEVICE INTERFACE /////////////////////////////////////////////////////

int alazar_alloc_buf(alazar_t ctx, void **buf)
{ lock(ctx,'r');
  TRY(alazar_is_armed(ctx));
  TRY(buf);
  TRY(*buf=malloc(buffer_size_bytes(ctx)));
  unlock(ctx);
  return SUCCESS;
Error:
  unlock(ctx);
  return FAILURE;
}

/** Acquires the device context for the board system.

  Current policies:
  1. Use first discovered system.
  2. Use all the boards in that system.
  */
int alazar_attach(alazar_t *ctx)
{
  U32 n,i;
  TRY(AlazarNumOfSystems()==1);                             //ensure single system
  NEW( ctx[0],struct _alazar_t,1);
  ZERO(ctx[0],struct _alazar_t,1);
  ctx[0]->last=ApiSuccess;
  ctx[0]->system_id = 1;
  TRY(ctx[0]->nboards=n=AlazarBoardsInSystemBySystemID(1)); //ensure >0
  for(i=0;i<n;++i)
    BOARDS[i]=AlazarGetBoardBySystemID(1,i+1);
  //ctx->lock=SRWLOCK_INIT;
  return SUCCESS;
Error:
  free_alazar_t(ctx);
  return FAILURE;
}

/** Releases the device context */
int alazar_detach(alazar_t *ctx)
{ if(!ctx || !*ctx) return SUCCESS;
  if(alazar_is_armed(*ctx))
    WARN(alazar_disarm(*ctx),"Trying to disarm.");
  free_alazar_t(ctx);
  return SUCCESS;
}

/** Validates and applies configuration settings to the device. */
int alazar_arm(alazar_t ctx, alazar_cfg_t cfg)
{ unsigned i,j;
  lock(ctx,'w');
  if(alazar_is_armed(ctx))
  { WARN(!alazar_is_armed(ctx),"Must disarm before re-arming.");
    goto Error;
  }
  ctx->cfg=cfg;
  cfg->ref++;
  ///// CHANNELS AND TRIGGERS
  for(i=0;i<ctx->nboards;++i)
  { ERR(AlazarSetCaptureClock(BOARD(i),INTERNAL_CLOCK,cfg->sample_rate_id,CLOCK_EDGE_RISING,0/*decimation*/));
    ERR(AlazarInputControl(BOARD(i),CHANNEL_A,DC_COUPLING,cfg->input_range_ids[i][0],IMPEDANCE_50_OHM));
    ERR(AlazarSetBWLimit(BOARD(i),CHANNEL_A,0/*disable*/));
    ERR(AlazarInputControl(BOARD(i),CHANNEL_B,DC_COUPLING,cfg->input_range_ids[i][1],IMPEDANCE_50_OHM));
    ERR(AlazarSetBWLimit(BOARD(i),CHANNEL_B,0/*disable*/));
  }
  // assume BOARD(0) is the master
  ERR(AlazarSetTriggerOperation(BOARD(0),TRIG_ENGINE_OP_J,                               // external trigger accepts line trigger
           TRIG_ENGINE_J,TRIG_EXTERNAL,TRIGGER_SLOPE_POSITIVE,line_trigger_level(ctx),
           TRIG_ENGINE_K,TRIG_DISABLE,TRIGGER_SLOPE_POSITIVE,0));
  ERR(AlazarSetExternalTrigger(BOARD(0),DC_COUPLING,ETR_5V));                            // set voltage range for line trigger (must be 5V for 9350)
  ERR(AlazarSetTriggerDelay(BOARD(0),0));
  ERR(AlazarSetTriggerTimeOut(BOARD(0),0));                                              // Disable timeout
  ERR(AlazarConfigureAuxIO(BOARD(0),AUX_IN_TRIGGER_ENABLE,TRIGGER_SLOPE_POSITIVE));      // config "digitizer ready" output

  //ERR(AlazarConfigureAuxIO(BOARD(1),AUX_OUT_TRIGGER,0));
  ERR(AlazarConfigureAuxIO(BOARD(cfg->aux_out_board_id),AUX_OUT_BUSY,0));

///// ALLOCATE WORKING MEMORY
  TRY(alloc_bufs(ctx));
  unlock(ctx);
  return SUCCESS;
Error:
  if(ctx && ctx->nboards)
  { unsigned i;
    for(i=0;i<ctx->nboards;++i)
      if(BOARD(i))
        ATSWARN(AlazarAbortAsyncRead(BOARD(i)));
  }
  ctx->cfg=NULL;
  cfg->ref--;
  unlock(ctx);
  return FAILURE;
}

/** Releases configuration-specific resources. */
int alazar_disarm(alazar_t ctx)
{ unsigned i;
  if(!ctx) return SUCCESS;
  if(alazar_is_started(ctx))
    WARN(alazar_stop(ctx),"Trying to stop.");
  lock(ctx,'w'); // FIXME: There's a race condition here.  is_started() should be a condition variable
  alazar_free_config(&ctx->cfg);
  free_bufs(ctx);
  unlock(ctx);
  return SUCCESS;
Error:
  return FAILURE;
}

/** Starts the acquisition. */
int alazar_start (alazar_t ctx)
{ int i,j;
  U32 nbytes;
  lock(ctx,'w');
  nbytes=(U32)buffer_size_bytes(ctx)/(U32)active_channel_count(ctx);
  LOG("START START START\n");
  TRY(alazar_is_armed(ctx));
  // init the async read
  i=ctx->nboards;
  while(i-->0) // need to do the master board last, so iterate backwards
  {
    U32 mask = channel_mask(ctx,i);
    if(mask)
    { ERR(AlazarSetRecordSize(BOARD(i),0,ctx->cfg->nsamples)); // this effects how often trigger enable resets
      ERR(AlazarBeforeAsyncRead(BOARD(i),mask,
        0,             /* transfer offset - pre-trigger samples*/
        ctx->cfg->nsamples, /* samples per record*/
        ctx->cfg->nrecords, /* records per buffer*/
        0x7fffffff,    /* records per acquisition (0x7FFFFFFF is infinite)*/
        ADMA_NPT       /* flags - No PreTrigger - enables faster retriggering*/
        | ADMA_EXTERNAL_STARTCAPTURE /* require call to AlazarStartCapture() */
        ));
    }
  }
  // post buffers
  for(i=0;i<ctx->nboards;++i)
  { int nchan = ctx->cfg->enable[i][0]+ctx->cfg->enable[i][1];
    if(nchan>0)
      for(j=0;j<BUFS_PER_BOARD;++j)
        ERR(AlazarPostAsyncBuffer(BOARD(i),((char*)ctx->bufs[i][j]),nbytes*nchan));
  }
  ctx->ibuf=0;
  ERR(AlazarStartCapture(BOARD(0)));
  ctx->is_started=1;
  unlock(ctx);
  return SUCCESS;
Error:
  ctx->is_started=0;
  unlock(ctx);
  return FAILURE;
}

/** Stops the acquisition. */
int alazar_stop  (alazar_t ctx)
{ int i;
  lock(ctx,'w');
  LOG("STOP STOP STOP\n");
  for(i=0;i<ctx->nboards;++i) // Require Abort called for master board first
    ERR(AlazarAbortAsyncRead(BOARD(i)));
  ctx->is_started=0;
  unlock(ctx);
  return SUCCESS;
Error:
  unlock(ctx);
  return FAILURE;
}

#define CURRENT(iboard) (ctx->bufs[iboard][ctx->ibuf%BUFS_PER_BOARD])
/** Waits for the next buffer to be acquired.

 This follows the symantics of other acquisition functions for the microscope that
 hand off the input buffer, but in this case the same buffer gets returned.

 This ends up copying data from digitzer buffers to the destination buffer and then
 reposting them.  The reason they're copied is because the buffers for each board
 need to be page locked.  That is, when channels are acquired from different
 boards, the data might exist in completely different areas of memory; a copy is
 required to make the data contiguous.

 \param[in]     ctx        The device context.
 \param[in,out] buf        A pointer to an image buffer.  This may be swapped with
                           the acquired buffer.  The input buffer is added to the
                           acquisition queue.
 \param[in]     timeout_ms If the acquisition doesn't complete within the
                           specified timeout (in milliseconds), the acquisition
                           will fail.
*/
#if 0
#define FUDGE ((i>0)?92:0)
#else
#define FUDGE (0)
#endif
int alazar_fetch (alazar_t ctx, void **buf, unsigned timeout_ms)
{ unsigned i,j,j0;
  size_t o=0;
  lock(ctx,'r');
  TRY(alazar_is_started(ctx));
  { const U32 nbytes=(U32)buffer_size_bytes(ctx)/(U32)active_channel_count(ctx);
    for(i=0;i<ctx->nboards;++i)
    { int nchan = ctx->cfg->enable[i][0]+ctx->cfg->enable[i][1];
      if(nchan>0)
      { ERR(AlazarWaitAsyncBufferComplete(BOARD(i),(char*)CURRENT(i),timeout_ms));
        memcpy(((char*)buf[0])+o,((char*)CURRENT(i))+FUDGE,nbytes*nchan-FUDGE); ///< FIXME: HACK!!!  FOR SOME REASON TRIGGERING/ADDRESSING IS OFF FOR THE SECOND BOARD
        { unsigned short *p=(unsigned short*)((char*)buf[0]+o+nbytes*nchan-FUDGE);
          for(j=0;j<FUDGE/2;++j)
            p[j]=p[-1];
        }
        o+=nbytes*nchan;
        ERR(AlazarPostAsyncBuffer(BOARD(i),(char*)CURRENT(i),nbytes*nchan));
      }
    }
  }
  ctx->ibuf++;
  unlock(ctx);
  return SUCCESS;
Error:
  unlock(ctx);
  return FAILURE;
}
#undef CURRENT

//  CONFIGURATION INTERFACE  /////////////////////////////////////////////
/** Generates a default configuration */
alazar_cfg_t alazar_make_config()
{
  alazar_cfg_t cfg;
  NEW( cfg,struct _alazar_cfg_t, 1);
  ZERO(cfg,struct _alazar_cfg_t, 1);
  cfg->sample_rate_id      = SAMPLE_RATE_125MSPS;
  { int i,j;
    for(i=0;i<MAXBOARDS;++i)
      for(j=0;j<CHANSPERBOARD;++j)
        cfg->input_range_ids[i][j] = INPUT_RANGE_PM_1_V;
  }
  cfg->aux_out_board_id=1;
  cfg->line_trig_lvl_volts = 0.5;
  cfg->ref=1;
  return cfg;
Error:
  return 0;
}

/** Releases resources held by the configuration */
void alazar_free_config(alazar_cfg_t *cfg)
{
  if(!cfg)    return;
  if(!cfg[0]) return;
  if(--(cfg[0]->ref)==0)
  { alazar_cfg_t c=cfg[0];
    cfg[0]=0;
    free(c);
  }
}

/** Setup config according to input scan parameters.

 Due to alignment requirements, the number of samples per image in a single
 channel is constrained to be divisible by some number of samples.  The
 actual number is related to the page alignment and is queried from the
 operating system.

 To make sure the image is aligned, the \a duty may be adjusted.  The input
 \a duty should be an upper bound.  It will be adjusted downwards a small
 amount (shaving a few samples off of each line).

 Divisibility by align implies there is an integer M.  Estimate one close to duty but for a smaller duty.

 \param[in]     cfg              The configuration object to modify.
 \param[in]     scans_per_second Each scan will be a row in the output image.
 \param[in]     scans            The number of rows in the output image.
 \param[in,out] duty             This is the fraction of the scan time
                                 during which samples are acquired
                                 during a scan.  Should be between 0 and 1.
*/
void alazar_set_image_size(alazar_cfg_t cfg, unsigned scans_per_second,unsigned scans,double *duty)
{ const double t = 1.0/(double)scans_per_second,
               r = samples_per_second(cfg->sample_rate_id),
               align = page_alignment_samples();
  size_t M = (size_t) (t*duty[0]*r*scans/align);                          //implicit floor
  *duty = M*align/(t*r*scans);                                            //adjust duty, aligning samples from a full frame to a page boundary
  cfg->nrecords=scans;
  cfg->nsamples=32*((U32)(t*r*duty[0]+0.5)/32);                           // round to nearest u32, and align scan to 32 sample boundary (ATS 9350 specific)

}

/** Change the line trigger level.
*/
void alazar_set_line_trigger_lvl_volts(alazar_cfg_t cfg, double volts)
{ cfg->line_trig_lvl_volts=volts;
}

/** By default no channels are enabled.  Use this to turn channels on.

 Channels are ordered like this: Board0.ChA, Board0.ChB, Board1.ChA ...
*/
void alazar_set_channel_enable(alazar_cfg_t cfg, int iboard, int ichan, int isenabled)
{ cfg->enable[iboard][ichan==CHANNEL_B]=isenabled;
}

void alazar_set_channel_input_range(alazar_cfg_t cfg, int iboard, int ichan, unsigned rangeid)
{ cfg->input_range_ids[iboard][ichan==CHANNEL_B]=rangeid;
}

void alazar_set_aux_out_board(alazar_cfg_t cfg, unsigned boardid)
{ cfg->aux_out_board_id=boardid;
}

/** Returns the image size that will be acquired by the armed device, */
void alazar_get_image_size(alazar_t ctx, unsigned *w, unsigned *h)
{ *w=*h=0;
  if(!ctx->cfg) return;
  *w=ctx->cfg->nsamples;
  *h=ctx->cfg->nrecords;
}

/** context must be armed. */
size_t alazar_get_image_size_bytes(alazar_t ctx)
{
   return buffer_size_bytes(ctx);
}
#endif // HAVE_ALAZAR


text:
title: Checking your modules or application graph
---

:::note
Koin allows you to verify your configuration modules, avoiding to discover dependency injection issues at runtime.
:::

To verify your modules, you just need to the `checkModules()` function within a simple JUnit test. This will launch your modules and try to run each possible definition for you.

```kotlin
class CheckModulesTest : KoinTest {

    @Test
    fun verifyKoinApp() {

        koinApplication {
            modules(module1,module2)
            checkModules()
        }
    }
}
```

also possible to use `checkKoinModules`:

```kotlin
class CheckModulesTest : KoinTest {

    @Test
    fun verifyKoinApp() {

        checkKoinModules(listOf(module1,module2))
    }
}
```

#### CheckModule DSL

For any definition that is using injected parameters, properties or dynamic instances, the `checkModules` DSL allow to specify how to work with the following case:

* `withInstance(value)` - will add `value` instance to Koin graph (can be used in dependency or parameter)

* `withInstance<MyType>()` - will add a mocked instance of `MyType`. Use MockProviderRule. (can be used in dependency or parameter)

* `withParameter<Type>(qualifier){ qualifier -> value }` - will add `value` instance to be injected as parameter

* `withParameter<Type>(qualifier){ qualifier -> parametersOf(...) }` - will add `value` instance to be injected as parameter

* `withProperty(key,value)` - add property to Koin

#### Allow mocking with a Junit rule

To use mocks with `checkModules`, you need to provide a `MockProviderRule`

```kotlin
@get:Rule
val mockProvider = MockProviderRule.create { clazz ->
    // Mock with your framework here given clazz
}
```

#### Verifying modules with dynamic behavior (3.1.3+)

To verify a dynamic behavior like following, let's use the CheckKoinModules DSL to provide the missing instance data to our test:

```kotlin
val myModule = module {
    factory { (id: String) -> FactoryPresenter(id) }
}
```

You can verify it with the following:

```kotlin
class CheckModulesTest : KoinTest {

    @Test
    fun verifyKoinApp() {

        koinApplication {
            modules(myModule)
            checkModules(){
                // value to add to Koin, used by definition
                withInstance("_my_id_value")
            }
        }
    }
}
```

This way, `FactoryPresenter` definition will be injected with `"_my_id_value"` define above.

You can also use mocked instances, to fill up your graph. You can notice that we need a `MockProviderRule` declaration to allow Koin mock any injected definition

```kotlin
val myModule1 = module {
    factory { (a : ComponentA) -> ComponentB(a) }
}
// or
val myModule2 = module {
    factory { ComponentB(get()) }
}
```

```kotlin
class CheckModulesTest : KoinTest {

    @get:Rule
    val mockProvider = MockProviderRule.create { clazz ->
        // Setup your nock framework
        Mockito.mock(clazz.java)
    }

    @Test
    fun verifyKoinApp() {

        koinApplication {
            modules(myModule1)
            checkModules(){
                // add a mock of ComponentA to Koin
                withInstance<ComponentA>()
            }
        }
    }
}
```

#### Checking Modules for Android (3.1.3)

Here below is how you can test your graph for a typical Android app:

```kotlin
class CheckModulesTest {

    @get:Rule
    val rule: TestRule = InstantTaskExecutorRule()

    @get:Rule
    val mockProvider = MockProviderRule.create { clazz ->
        Mockito.mock(clazz.java)
    }

    @Test
    fun `test DI modules`(){
        koinApplication {
            modules(allModules)
            checkModules(){
                withInstance<Context>()
                withInstance<Application>()
                withInstance<SavedStateHandle>()
                withInstance<WorkerParameters>()
            }
        }
    }
}
```

also possible to use `checkKoinModules`:

```kotlin
class CheckModulesTest {

    @get:Rule
    val rule: TestRule = InstantTaskExecutorRule()

    @get:Rule
    val mockProvider = MockProviderRule.create { clazz ->
        Mockito.mock(clazz.java)
    }

    @Test
    fun `test DI modules`(){
        checkKoinModules(allModules) {
            withInstance<Context>()
            withInstance<Application>()
            withInstance<SavedStateHandle>()
            withInstance<WorkerParameters>()
        }
    }
}
```

#### Providing Default Values (3.1.4)

If you need, you can set a default value for all type in the checked modules. For example, We can override all injected string values:

Let's use the `withInstance()` function in `checkModules` block, to define a default value for all definitions:

```kotlin
@Test
fun `test DI modules`(){
    koinApplication {
        modules(allModules)
        checkModules(){
            withInstance("_ID_")
        }
    }
}
```

All injected definition that are using a injected `String` parameter, will receive `"_ID_"`:

```kotlin
module {
    single { (i: String) -> Simple.ComponentC(i) }
    factory { (id: String) -> FactoryPresenter(id) }
}
```

#### Providing ParametersOf values (3.1.4)

You can define default value to be injected for one specific definition, with `withParameter` or `withParameters` functions:

```kotlin
@Test
fun `test DI modules`(){
    koinApplication {
        modules(allModules)
        checkModules(){
            withParameter<FactoryPresenter> { "_FactoryId_" }
            withParameters<FactoryPresenter> { parametersOf("_FactoryId_",...) }
        }
    }
}
```

#### Providing Scope Links

You can link scopes by using `withScopeLink` function in`checkModules` block to inject instances from another scope's definitions:

```kotlin
val myModule = module {
    scope(named("scope1")) {
        scoped { ComponentA() }
    }
    scope(named("scope2")) {
        scoped { ComponentB(get()) }
    }
}
```

```kotlin
@Test
fun `test DI modules`(){
    koinApplication {
        modules(myModule)
        checkModules(){
            withScopeLink(named("scope2"), named("scope1"))
        }
    }
}
```


text:
body {
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  font-size: 13px;
  -webkit-font-smoothing: auto;
}

/*
 * Globabally or selectively apply these to aid debuging.
 */
.debug, [debug] {
  outline: blue solid 1px !important;
}

/*
 * Uncomment to debug focus changes and tabIndex ordering.
 */
/*
*:focus {
  box-shadow: 0 0 10px 10px pink !important;
}
*/


text:
package net.ruippeixotog.scalafbp.component.stream

import spray.json._

import net.ruippeixotog.scalafbp.component.{ AutoTerminateSpec, ComponentSpec }

class MapConcatSpec extends ComponentSpec with AutoTerminateSpec {
  val component = MapConcat

  "A MapConcat component" should {

    "let every element pass untouched until the function is defined" in new ComponentInstance {
      MapConcat.inPort.send(JsNumber(0))
      MapConcat.outPort must emit(JsNumber(0))
      MapConcat.inPort.send(JsNumber(3))
      MapConcat.outPort must emit(JsNumber(3))
    }

    "use the transformation function once it is defined" in new ComponentInstance {
      MapConcat.inPort.send(JsNumber(0))
      MapConcat.outPort must emit(JsNumber(0))

      MapConcat.funcPort.send("return [x - 1, x + 1]")
      MapConcat.outPort must emitNothing

      MapConcat.inPort.send(JsNumber(0))
      MapConcat.outPort must emit(JsNumber(-1))
      MapConcat.outPort must emit(JsNumber(1))
      MapConcat.inPort.send(JsNumber(3))
      MapConcat.outPort must emit(JsNumber(2))
      MapConcat.outPort must emit(JsNumber(4))
    }

    "update the transformation function if it changes" in new ComponentInstance {
      MapConcat.funcPort.send("return [x * 2, x * 3, x * 4]")
      MapConcat.inPort.send(JsNumber(0))
      MapConcat.outPort must emit(JsNumber(0))
      MapConcat.outPort must emit(JsNumber(0))
      MapConcat.outPort must emit(JsNumber(0))
      MapConcat.inPort.send(JsNumber(3))
      MapConcat.outPort must emit(JsNumber(6))
      MapConcat.outPort must emit(JsNumber(9))
      MapConcat.outPort must emit(JsNumber(12))

      MapConcat.funcPort.send("return [-1]")
      MapConcat.outPort must emitNothing

      MapConcat.inPort.send(JsNumber(0))
      MapConcat.outPort must emit(JsNumber(-1))
      MapConcat.inPort.send(JsNumber(3))
      MapConcat.outPort must emit(JsNumber(-1))

      MapConcat.funcPort.send("return []")
      MapConcat.outPort must emitNothing

      MapConcat.inPort.send(JsNumber(0))
      MapConcat.outPort must emitNothing
    }

    "terminate with an error if the function does not return an array" in new ComponentInstance {
      MapConcat.funcPort.send("return x")
      MapConcat.inPort.send(JsNumber(0))
      this must terminateWithError()
    }

    terminateItselfWhenAllInPortsAreClosed
    terminateItselfWhenAllOutPortsAreClosed
  }
}


text:
/* This source file is part of the ATMEL QTouch Library 5.0.1 */

/*****************************************************************************
 *
 * \file
 *
 * \brief  This file contains the QDebug public API that can be used to
 * transfer data from a Touch Device to QTouch Studio using the QT600
 * USB Bridge.
 *
 *
 * - Userguide:          QTouch Library Peripheral Touch Controller User Guide.
 * - Support: http://www.atmel.com/design-support/
 *
 *
 * Copyright (c) 2014 Atmel Corporation. All rights reserved.
 *
 * \asf_license_start
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. The name of Atmel may not be used to endorse or promote products derived
 *    from this software without specific prior written permission.
 *
 * 4. This software may only be redistributed and used in connection with an
 *    Atmel microcontroller product.
 *
 * THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * \asf_license_stop
 *
 ******************************************************************************/

/*============================ INCLUDES ======================================*/

/*============================ INCLUDES ======================================*/
 /**
 * Support and FAQ: visit Atmel Support
 */
#include "asf.h"
#include "QDebug_samd.h"

/* ! compile file only when QDebug is enabled. */
#if DEF_TOUCH_QDEBUG_ENABLE == 1

#include "QDebugTransport.h"
#include "QDebugSettings.h"

#if (defined QDEBUG_SPI)
#include "SPI_Master.h"
#elif (defined QDEBUG_SERIAL)
#include "SERIAL.h"
#elif (defined QDEBUG_BITBANG_SPI)
#include "BitBangSPI_Master.h"
#else
#warning "No Debug Interface is selected in QDebugSettings.h"
#endif

/*============================ GLOBAL VARIABLES ==============================*/
/* ! These must somehow be updated from the library. */
uint8_t qgRefschanged;
uint8_t qgStateschanged;

/*! \name Object to get library info.
 */
touch_info_t qt_libinfo;

/**
 * Time stamp information.
 */
uint16_t timestamp1_hword;
uint16_t timestamp1_lword;
uint16_t timestamp2_hword;
uint16_t timestamp2_lword;
uint16_t timestamp3_hword;
uint16_t timestamp3_lword;

/*============================ EXTERN VARIABLES ==============================*/
extern touch_config_t touch_config;
extern volatile int8_t autonomous_qtouch_in_touch;

/*============================ LOCAL VARIABLES ===============================*/
/* ! Subscriptions. */
static uint16_t qgSubsOnce = 0;
static uint16_t qgSubsChange = 0;
static uint16_t qgSubsAllways = 0;
static uint16_t qgLibraryChanges = 0;
static uint16_t delivery = 0;

#if (defined QDEBUG_SPI)
static bool transmit_dummy = true;
#elif (defined QDEBUG_SERIAL)
static bool transmit_dummy = false;
#elif (defined QDEBUG_BITBANG_SPI)
static bool transmit_dummy = true;
#else
#endif

#if ((BOARD == SAMD20_XPLAINED_PRO) || (BOARD == SAMD21_XPLAINED_PRO))
extern volatile uint16_t touch_time_counter;
#else
extern void set_timer_period(uint16_t time);
#endif
/*============================ IMPLEMENTATION ================================*/

/*! \brief This API initializes QDebug interface, including the low level
 * hardware interface (SPI, TWI, USART etc).
 * \note Must be called before using any other QDebug API.
 */
void QDebug_Init(void)
{
	touch_ret_t touch_ret = TOUCH_SUCCESS;

#if (defined QDEBUG_BITBANG_SPI)
	BitBangSPI_Master_Init();
#endif

	touch_ret = QDEBUG_GET_LIBINFO_FUNC(&QDEBUG_LIBINFO);
	if (touch_ret != TOUCH_SUCCESS) {
		while (1) {
		}
	}

	Init_Buffers();
}

/*! \brief Command handler for the data received from QTouch Studio
 * \note This function should be called in the main loop after
 * measure_sensors to process the data received from QTOuch Studio.
 */
void QDebug_ProcessCommands(void)
{
	uint8_t CommandID;

	if (Receive_Message() == 0) {
		return;
	}

	/* Handle the commands */
	CommandID = GetChar();

	switch (CommandID) {
	case QT_CMD_DUMMY:
		break;

	case QT_CMD_SET_SUBS:
		Set_Subscriptions();
		break;

	case QT_CMD_SET_GLOBAL_CONFIG:
		Set_Global_Config();
		Set_Measurement_Period();
		break;

	case QT_CMD_SET_CH_CONFIG:
		Set_Channel_Config();
		break;
	}

	RX_Buffer[0] = 0;
	RX_index = 0;
}

/*! \brief Send data to QTouch Studio based on the subscription.
 * \param  qt_lib_flags:Change flag from measure_sensors.
 */
void QDebug_SendData(uint16_t qt_lib_flags)
{
	SequenceH = (SequenceH + 1) & 0x0F;

	/* Test if measure_sensors has reported change in key states or
	 *rotor/slider positions */
	if ((qt_lib_flags & TOUCH_STATUS_CHANGE) ||
			(qt_lib_flags & TOUCH_ROTOR_SLIDER_POS_CHANGE)) {
		qgLibraryChanges |= (1 << SUBS_STATES);
	}

	/* Test if measure_sensors has reported change in at least one channel
	 *reference */
	if (qt_lib_flags & TOUCH_CHANNEL_REF_CHANGE) {
		qgLibraryChanges |= (1 << SUBS_REF);
	}

	delivery = qgSubsAllways | qgSubsOnce |
			(qgLibraryChanges & qgSubsChange);

	if (delivery & (1 << SUBS_SIGN_ON)) {
		Transmit_Sign_On();
	}

	if (delivery & (1 << SUBS_GLOBAL_CONFIG)) {
		Transmit_Global_Config();
	}

	if (delivery & (1 << SUBS_SENSOR_CONFIG)) {
		Transmit_Sensor_Config();
	}

	if (delivery & (1 << SUBS_SIGNALS)) {
		Transmit_Signals();
	}

	if (delivery & (1 << SUBS_REF)) {
		Transmit_Ref();
	}

	if (delivery & (1 << SUBS_STATES)) {
		Transmit_State();
	}

	if (delivery & (1 << SUBS_DELTA)) {
		Transmit_Delta();
	}

	if ((transmit_dummy == true) && (delivery == 0)) {
		Transmit_Dummy();
	}

	/* Reset masks until PC sends another request */
	qgSubsOnce = 0;

	/* Reset the changes we have just sent */
	qgLibraryChanges &= ~delivery;
}

/*! \brief Set subscription values.
 * \note  This function can be used directly in main to set data subscription
 * if 1way SPI interface is used.
 */
void QDebug_SetSubscriptions(uint16_t once, uint16_t change, uint16_t allways)
{
	qgSubsOnce = once;
	qgSubsChange = change;
	qgSubsAllways = allways;
}

/*! \brief Set Data Subscription values.
 * \note  Should only be called from the command handler.
 */
void Set_Subscriptions(void)
{
	GetChar();              /* Bit 8-15 is reserved for future use */
	uint8_t a = GetChar();
	GetChar();              /* Bit 8-15 is reserved for future use */
	uint8_t b = GetChar();
	GetChar();              /* Bit 8-15 is reserved for future use */
	uint8_t c = GetChar();
	QDebug_SetSubscriptions(a, b, c);
}

/*! \brief Extract the data packet from QTouch Studio and set global config.
 * \note  Should only be called from the command handler.
 */
void Set_Global_Config(void)
{
	touch_ret_t touch_ret;
#ifdef DEF_TOUCH_QDEBUG_ENABLE_MUTLCAP
	touch_config_t *p_touch_config = &touch_config;
	touch_mutlcap_config_t *p_mutlcap_config
		= p_touch_config->p_mutlcap_config;

	p_mutlcap_config->global_param.recal_threshold
		= (recal_threshold_t)GetChar();
	p_mutlcap_config->global_param.di = GetChar();
	p_mutlcap_config->global_param.drift_hold_time = GetChar();
	p_mutlcap_config->global_param.max_on_duration = GetChar();
	p_mutlcap_config->global_param.tch_drift_rate = GetChar();
	p_mutlcap_config->global_param.atch_drift_rate = GetChar();
	p_mutlcap_config->global_param.atch_recal_delay = GetChar();
#endif
#ifdef DEF_TOUCH_QDEBUG_ENABLE_SELFCAP
	touch_config_t *p_touch_config = &touch_config;
	touch_selfcap_config_t *p_selfcap_config
		= p_touch_config->p_selfcap_config;

	p_selfcap_config->global_param.recal_threshold
		= GetChar();
	p_selfcap_config->global_param.di = GetChar();
	p_selfcap_config->global_param.drift_hold_time = GetChar();
	p_selfcap_config->global_param.max_on_duration = GetChar();
	p_selfcap_config->global_param.tch_drift_rate = GetChar();
	p_selfcap_config->global_param.atch_drift_rate = GetChar();
	p_selfcap_config->global_param.atch_recal_delay = GetChar();
#endif

	touch_time.measurement_period_ms          = (GetChar() << 8u);
	touch_time.measurement_period_ms          |= GetChar();
#if ((BOARD == SAMD20_XPLAINED_PRO) || (BOARD == SAMD21_XPLAINED_PRO))
	touch_time_counter = 0u;
#else
	set_timer_period(touch_time.measurement_period_ms);
#endif
#ifdef DEF_TOUCH_QDEBUG_ENABLE_SELFCAP
	/* update the global parameter value inside the SAMD library */
	touch_ret = QDEBUG_UPDATE_GLOBAL_PARAM_FUNC(
			&p_selfcap_config->global_param);
	if (touch_ret != TOUCH_SUCCESS) {
		while (1) {
		}
	}

#endif

#ifdef DEF_TOUCH_QDEBUG_ENABLE_MUTLCAP
	/* update the global parameter value inside the SAMD library */
	touch_ret = QDEBUG_UPDATE_GLOBAL_PARAM_FUNC(
			&p_mutlcap_config->global_param);
	if (touch_ret != TOUCH_SUCCESS) {
		while (1) {
		}
	}

#endif
}

/*! \brief Extract the data packet from QTouch Studio and set channel config.
 * \note  Should only be called from the command handler.
 */
void Set_Channel_Config(void)
{
	touch_ret_t touch_ret = TOUCH_SUCCESS;
	sensor_id_t sensor_id;
	uint8_t type_aks_pos_hyst;
#ifdef DEF_TOUCH_QDEBUG_ENABLE_MUTLCAP
	touch_mutlcap_param_t touch_sensor_param;
#else
	touch_selfcap_param_t touch_sensor_param;
#endif
	sensor_id = GetChar();

	/* Read back and initialize the touch_sensor_param structure.
	 * This is because not all the touch_sensor_param members are
	 * updated by this API. */
	touch_ret
		= QDEBUG_GET_SENSOR_CONFIG_FUNC(sensor_id,
			&touch_sensor_param);
	if (touch_ret != TOUCH_SUCCESS) {
		while (1) {
		}
	}

	/* Update the necessary members of the touch_sensor_param structure
	 * and write back. */
	touch_sensor_param.detect_threshold = GetChar();
	type_aks_pos_hyst = GetChar();
	touch_sensor_param.aks_group
		= (aks_group_t)((uint8_t)((type_aks_pos_hyst & 0x38u) >> 3u));
	touch_sensor_param.detect_hysteresis
		= (hysteresis_t)((uint8_t)(type_aks_pos_hyst & 0x03u));

	touch_ret = QDEBUG_UPDATE_SENSOR_CONFIG_FUNC(sensor_id,
			&touch_sensor_param);
	if (touch_ret != TOUCH_SUCCESS) {
		while (1) {
		}
	}
}

/*! \brief Extract the data packet from QTouch Studio and set measurement
 * period.
 * \note  Should only be called from the command handler.
 */
void Set_Measurement_Period(void)
{
	touch_time.measurement_period_ms = touch_time.measurement_period_ms; /*
	                                                                      *Dummy.
	                                                                      **/
}

/*! \brief Extracts user data from QTouch Studio to touch mcu memory.
 * \param pdata: data pointer.
 * \note  The data can be binary data.
 */
void Set_QT_User_Data(uint8_t *pdata)
{
	uint16_t c = RX_Buffer[1];
	while (c > 0) {
		PutChar(*pdata++);
		c--;
	}
	Send_Message();
}

/*! \brief Transmits a dummy packet if no other subscriptions are set.
 */
void Transmit_Dummy(void)
{
	PutChar(QT_DUMMY);
	Send_Message();
}

/*! \brief Transmits the sign on packet to QTouch Studio.
 */
void Transmit_Sign_On(void)
{
	PutChar(QT_SIGN_ON);
	PutInt(PROJECT_ID);
	PutChar(INTERFACE);
	PutChar(1);             /* PROTOCOL_TYPE */
	PutChar(2);             /* PROTOCOL_VERSION */
#if DEF_TOUCH_MUTLCAP == 1
	PutChar(1);             /* LIB_TYPE    Mutual Cap */
#else
	PutChar(0);             /* LIB_TYPE    Self Cap */
#endif
	PutInt(QDEBUG_LIBINFO.fw_version); /* LIB_VERSION */
	PutInt(0);              /* LIB_VARIANT */
	PutChar(QDEBUG_NUM_CHANNELS);
	PutInt(delivery);       /* subscription info */
	Send_Message();
}

/*! \brief Transmits the global config struct to QTouch Studio.
 */
void Transmit_Global_Config(void)
{
#ifdef DEF_TOUCH_QDEBUG_ENABLE_MUTLCAP
	touch_config_t *p_touch_config = &touch_config;
	touch_mutlcap_config_t *p_mutlcap_config
		= p_touch_config->p_mutlcap_config;
	touch_ret_t touch_ret = TOUCH_SUCCESS;

	/* get the global parameters from the library and transmit the global
	 * parameters to the Qtouch Studio */
	touch_ret = QDEBUG_GET_GLOBAL_PARAM_FUNC(&p_mutlcap_config->global_param);
	if (touch_ret != TOUCH_SUCCESS) {
		while (1) {
		}
	}

	PutChar(QT_GLOBAL_CONFIG);
	PutChar(p_mutlcap_config->global_param.recal_threshold);
	PutChar(p_mutlcap_config->global_param.di);
	PutChar(p_mutlcap_config->global_param.drift_hold_time);
	PutChar(p_mutlcap_config->global_param.max_on_duration);
	PutChar(p_mutlcap_config->global_param.tch_drift_rate);
	PutChar(p_mutlcap_config->global_param.atch_drift_rate);
	PutChar(p_mutlcap_config->global_param.atch_recal_delay);
#endif
#ifdef DEF_TOUCH_QDEBUG_ENABLE_SELFCAP
	touch_config_t *p_touch_config = &touch_config;
	touch_selfcap_config_t *p_selfcap_config
		= p_touch_config->p_selfcap_config;
	touch_ret_t touch_ret = TOUCH_SUCCESS;

	/* get the global parameters from the library and transmit the global
	 * parameters to the Qtouch Studio */
	touch_ret = QDEBUG_GET_GLOBAL_PARAM_FUNC(&p_selfcap_config->global_param);
	if (touch_ret != TOUCH_SUCCESS) {
		while (1) {
		}
	}

	PutChar(QT_GLOBAL_CONFIG);
	PutChar(p_selfcap_config->global_param.recal_threshold);
	PutChar(p_selfcap_config->global_param.di);
	PutChar(p_selfcap_config->global_param.drift_hold_time);
	PutChar(p_selfcap_config->global_param.max_on_duration);
	PutChar(p_selfcap_config->global_param.tch_drift_rate);
	PutChar(p_selfcap_config->global_param.atch_drift_rate);
	PutChar(p_selfcap_config->global_param.atch_recal_delay);
#endif
	PutInt(touch_time.measurement_period_ms);
	PutInt(0);                      /* TICKS_PER_MS */
	PutChar(0);             /* Time_Setting */

	Send_Message();
}

/*! \brief Transmits the channel config struct to QTouch Studio.
 */
void Transmit_Sensor_Config(void)
{
	uint8_t c;
	sensor_t *p_sensors = QDEBUG_SENSOR_PTR;

	PutChar(QT_SENSOR_CONFIG);

	PutChar(1);             /* 1 = KRS */
	for (c = 0; c < QDEBUG_NUM_SENSORS; c++) {
		PutChar(p_sensors[c].threshold);
		PutChar(p_sensors[c].type_aks_pos_hyst);
		PutChar(p_sensors[c].from_channel);
		PutChar(p_sensors[c].to_channel);
	}
	Send_Message();
}

/*! \brief Transmits the measurement values for each channel to QTouch Studio.
 */
void Transmit_Signals(void)
{
	uint8_t c;
	uint16_t *p_signals = (uint16_t *)QDEBUG_SIGNALS_PTR;

	PutChar(QT_SIGNALS);
	for (c = 0; c < QDEBUG_NUM_CHANNELS; c++) {
		PutChar((uint8_t)((*p_signals >> 8) & 0xFFu));
		PutChar((uint8_t)(*p_signals & 0xFFu));
		p_signals++;
	}
	Send_Message();
}

/*! \brief Transmits the channel reference values to QTouch Studio.
 */
void Transmit_Ref(void)
{
	uint8_t c;
	uint16_t *p_references = (uint16_t *)QDEBUG_REFERENCES_PTR;

	PutChar(QT_REFERENCES);

	for (c = 0; c < QDEBUG_NUM_CHANNELS; c++) {
		PutChar((uint8_t)((*p_references >> 8) & 0xFFu));
		PutChar((uint8_t)(*p_references & 0xFFu));
		p_references++;
	}
	Send_Message();
}

/*! \brief Transmits the channel delta values to QTouch Studio.
 */
void Transmit_Delta(void)
{
	touch_ret_t touch_ret = TOUCH_SUCCESS;
	int16_t delta;
	uint8_t c;

	PutChar(QT_DELTAS);
	for (c = 0; c < QDEBUG_NUM_SENSORS; c++) {
		touch_ret = QDEBUG_GET_DELTA_FUNC(c, &delta);
		if (touch_ret != TOUCH_SUCCESS) {
			while (1u) { /* Check API Error return code. */
			}
		}

		PutChar((uint8_t)((delta >> 8) & 0xFFu));
		PutChar((uint8_t)(delta & 0xFFu));
	}
	Send_Message();
}

/*! \brief Transmits the state values to QTouch Studio.
 */
void Transmit_State(void)
{
	uint8_t c;
	uint8_t *p_sensor_states = QDEBUG_SENSOR_STATES_PTR;
	uint8_t *p_rotor_slider_values = QDEBUG_SENSOR_RS_VALUES;

	PutChar(QT_STATES);
	PutChar(QDEBUG_NUM_CHANNELS);
	PutChar(QDEBUG_NUM_ROTORS_SLIDERS);

	for (c = 0; c < QDEBUG_NUM_SENSOR_STATE_BYTES; c++) {
		PutChar(p_sensor_states[c]);
	}

	for (c = 0; c < QDEBUG_NUM_ROTORS_SLIDERS; c++) {
		PutChar(p_rotor_slider_values[c]);
	}

	Send_Message();
}

/*! \brief Transmits the application execution timestamp values to QTouch
 * Studio.
 * \note This value is a combination of current_time_ms_touch (high word) &
 * timer counter register (low word).
 */
void Transmit_Time_Stamps(void)
{
	PutInt(timestamp1_hword);
	PutInt(timestamp1_lword);
	PutInt(timestamp2_hword);
	PutInt(timestamp2_lword);
	PutInt(timestamp3_hword);
	PutInt(timestamp3_lword);
	Send_Message();
}

/*! \brief Transmits user data to QTouch Studio.
 * \param pdata: data pointer.
 * \param c: length of data in bytes.
 * \note The data will be binary data.
 */
void Transmit_QT_User_Data(uint8_t *pdata, uint16_t c)
{
	while (c > 0) {
		PutChar(*pdata++);
		c--;
	}
	Send_Message();
}

#endif  /* DEF_TOUCH_QDEBUG_ENABLE == 1 */


text:
package info.dgjones.abora.white.spaces.unordered;

import info.dgjones.abora.white.rcvr.Rcvr;
import info.dgjones.abora.white.rcvr.SpecialistRcvr;
import info.dgjones.abora.white.rcvr.Xmtr;
import info.dgjones.abora.white.spaces.basic.CoordinateSpace;
import info.dgjones.abora.white.spaces.basic.Dsp;
import info.dgjones.abora.white.xpp.basic.Heaper;

public class HeaperDsp extends IdentityDsp {
	private static IdentityDsp theDsp = new HeaperDsp();

	/*
	udanax-top.st:29638:
	IdentityDsp subclass: #HeaperDsp
		instanceVariableNames: ''
		classVariableNames: ''
		poolDictionaries: ''
		category: 'Xanadu-Spaces-Unordered'!
	*/
	/*
	udanax-top.st:29642:
	(HeaperDsp getOrMakeCxxClassDescription)
		attributes: ((Set new) add: #PSEUDO.COPY; add: #CONCRETE; add: #NOT.A.TYPE; yourself)!
	*/
	/*
	udanax-top.st:29661:
	HeaperDsp class
		instanceVariableNames: ''!
	*/
	/*
	udanax-top.st:29664:
	(HeaperDsp getOrMakeCxxClassDescription)
		attributes: ((Set new) add: #PSEUDO.COPY; add: #CONCRETE; add: #NOT.A.TYPE; yourself)!
	*/

	public CoordinateSpace coordinateSpace() {
		return HeaperSpace.make();
		/*
		udanax-top.st:29647:HeaperDsp methodsFor: 'accessing'!
		{CoordinateSpace} coordinateSpace
			^HeaperSpace make!
		*/
	}

	public HeaperDsp() {
		super();
		/*
		udanax-top.st:29653:HeaperDsp methodsFor: 'creation'!
		create
			super create!
		*/
	}

	public void sendSelfTo(Xmtr xmtr) {
		/*
		udanax-top.st:29658:HeaperDsp methodsFor: 'generated:'!
		{void} sendSelfTo: xmtr {Xmtr}!
		*/
	}

	public static Dsp make() {
		return theDsp;
		/*
		udanax-top.st:29669:HeaperDsp class methodsFor: 'pseudo constructors'!
		{Dsp} make
			^(theDsp basicCast: IdentityDsp) basicCast: HeaperDsp!
		*/
	}

	public static Heaper make(Rcvr rcvr) {
		((SpecialistRcvr) rcvr).registerIbid(theDsp);
		return theDsp;
		/*
		udanax-top.st:29672:HeaperDsp class methodsFor: 'pseudo constructors'!
		{Heaper} make.Rcvr: rcvr {Rcvr}
			(rcvr cast: SpecialistRcvr) registerIbid: theDsp.
			^theDsp!
		*/
	}
}


text:
module MiqAeMethodService
  class MiqAeServiceContainerQuota < MiqAeServiceModelBase
    expose :ext_management_system,    association => true
    expose :container_project,        association => true
    expose :container_quota_items,    association => true
  end
end


text:
namespace MyLibrary.Services
{
    using Contracts;
    using Data;
    using Microsoft.EntityFrameworkCore;

    public class DatabaseInitializerService : IDatabaseInitializerService
    {
        private readonly LibraryContext context;

        public DatabaseInitializerService(LibraryContext context) => this.context = context;

        public void InitializeDatabase() => this.context.Database.Migrate();
    }
}


text:
Change log
==========

v5.2.1 (2018-10-12)
-------------------

* Relax dependency requirements by removing the upper version number bounds.

v5.2.0 (2017-04-09)
-------------------

* Cross compatibility for both Python 2 and 3.
  Linguistica 5 works on Python 2.7, 3.4, 3.5, and 3.6.
  (The GUI works on Python 3 only.)

* Travis CI was greatly simplified.

* Minor stylistic fixes.
  `flake8` checks for code quality (and is part of Travis CI).

v5.1.1 (2017-03-05)
-------------------

* Switch from the removed `QtWebKitWidgets` to `QtWebEngineWidgets` in the GUI
  code. (`QtWebKitWidgets` was deprecated in Qt 5.5 and removed in Qt 5.6.)

* `linguistica` is now a terminal command for launching the command line
  interface or the graphical user interface.

v5.1.0 (2016-12-16)
-------------------

* The major modules now available:
  - `lexicon`
  - `ngram`
  - `signature`
  - `manifold`
  - `trie`
  - `phon`

* Include graphical user interface (GUI) and command line interface (CLI)


text:
package installer

import (
	"os"
)

// testHelmPath gets the helm path
func testHelmPath() string {
	return getEnvVarWithDefault("TEST_HELM_PATH", "/tmp/rook-tests-scripts-helm/helm")
}

// TestLogCollectionLevel gets whether to collect all logs
func TestLogCollectionLevel() string {
	return getEnvVarWithDefault("TEST_LOG_COLLECTION_LEVEL", "")
}

func StorageClassName() string {
	return getEnvVarWithDefault("TEST_STORAGE_CLASS", "")
}

func UsePVC() bool {
	return StorageClassName() != ""
}

// baseTestDir gets the base test directory
func baseTestDir() (string, error) {
	// If the base test directory is actively set to WORKING_DIR (as in CI),
	// we use the current working directory.
	val := getEnvVarWithDefault("TEST_BASE_DIR", "/data")
	if val == "WORKING_DIR" {
		var err error
		val, err = os.Getwd()
		if err != nil {
			return "", err
		}
	}
	return val, nil
}

// TestScratchDevice get the scratch device to be used for OSD
func TestScratchDevice() string {
	return getEnvVarWithDefault("TEST_SCRATCH_DEVICE", "/dev/nvme0n1")
}

// getDeviceFilter get the device name used for OSD
func getDeviceFilter() string {
	return getEnvVarWithDefault("DEVICE_FILTER", `""`)
}

func getEnvVarWithDefault(env, defaultValue string) string {
	val := os.Getenv(env)
	if val == "" {
		logger.Infof("test environment variable (default) %q=%q", env, defaultValue)
		return defaultValue
	}
	logger.Infof("test environment variable %q=%q", env, val)
	return val
}


text:
 A way to control the books you've read and still have to read.
 Project developed as part as a selection process.

## Techologies

This projects uses

- React.js
- Babel
- Gulp
- Bootstrap
- Sass
- NPM
- Bower

## Installing and Running

1 - You need to have instaled

- node.js
- git
- gulp

2 - Clone this repository into your local machine
```
git clone https://github.com/astartar/my-reading-control.git
```

3 - Install the project dependencies
```
$ npm install
```

4 - Start the project
```
$ npm start
```


text:
extern crate quote;
extern crate syn;
extern crate proc_macro2;

use syn::{Lit, TokenTree};
use proc_macro2::{TokenNode, Spacing, Delimiter, TokenStream, Term};
use proc_macro2::Delimiter::*;

fn alone(c: char) -> TokenTree {
    TokenTree(proc_macro2::TokenTree {
        span: Default::default(),
        kind: TokenNode::Op(c, Spacing::Alone),
    })
}

fn joint(c: char) -> TokenTree {
    TokenTree(proc_macro2::TokenTree {
        span: Default::default(),
        kind: TokenNode::Op(c, Spacing::Joint),
    })
}

fn delimited(delim: Delimiter, tokens: Vec<TokenTree>) -> TokenTree {
    TokenTree(proc_macro2::TokenTree {
        span: Default::default(),
        kind: TokenNode::Group(delim, tokens.into_iter().map(|t| t.0).collect()),
    })
}

fn word(sym: &str) -> TokenTree {
    TokenTree(proc_macro2::TokenTree {
        span: Default::default(),
        kind: TokenNode::Term(Term::intern(sym)),
    })
}

#[test]
fn test_struct() {
    let raw = "
        #[derive(Debug, Clone)]
        pub struct Item {
            pub ident: Ident,
            pub attrs: Vec<Attribute>,
        }
    ";

    let expected = vec![
        alone('#'),
        delimited(Bracket, vec![
           word("derive"),
           delimited(Parenthesis, vec![
               word("Debug"),
               alone(','),
               word("Clone"),
           ]),
        ]),
        word("pub"),
        word("struct"),
        word("Item"),
        delimited(Brace, vec![
           word("pub"),
           word("ident"),
           alone(':'),
           word("Ident"),
           alone(','),

           word("pub"),
           word("attrs"),
           alone(':'),
           word("Vec"),
           alone('<'),
           word("Attribute"),
           joint('>'),
           alone(','),
        ],
    )];

    let result = raw.parse::<TokenStream>().unwrap()
                    .into_iter()
                    .map(TokenTree)
                    .collect::<Vec<_>>();
    if result != expected {
        panic!("{:#?}\n!=\n{:#?}", result, expected);
    }
}

#[test]
fn test_literal_mangling() {
    let raw = "0_4";
    let parsed: Lit = syn::parse_str(raw).unwrap();
    assert_eq!(raw, quote!(#parsed).to_string());
}


text:
define([

], function () {
  function Query (decorated, $element, options) {
    if (window.console && console.warn) {
      console.warn(
        'Select2: The `query` option has been deprecated in favor of a ' +
        'custom data adapter that overrides the `query` method. Support ' +
        'will be removed for the `query` option in future versions of ' +
        'Select2.'
      );
    }

    decorated.call(this, $element, options);
  }

  Query.prototype.query = function (_, params, callback) {
    params.callback = callback;

    var query = this.options.get('query');

    query.call(null, params);
  };

  return Query;
});


text:
/*

Exercise 3: Design and implement a Java program for programming exercise 7.15, page 279 (name it
EliminateDuplicates), as specified in the problem statement. Follow the instructions in the problem
statement to design your method. Design the main method of your program such that it allows the user to rerun
the program with different sets of inputs. Use the givens ample run to test your code. Document your code,
and organize and space the outputs properly. Use escape characters and formatting objects when applicable.

(Eliminate duplicates) Write a method that returns a new array by eliminating the
duplicate values in the array using the following method header:
public static int[] eliminateDuplicates(int[] list)
Write a test program that reads in ten integers, invokes the method, and displays
the result. Here is the sample run of the program:

Programming Exercises 279
Enter ten numbers: 1 2 3 2 1 6 3 4 5 2
The distinct numbers are: 1 2 3 6 4 5

*/

import java.util.Scanner;
public class EliminateDuplicates
{
   public static void main(String[] args)
   {
      while (true)
      {
         java.util.Scanner input = new java.util.Scanner(System.in);
         int[] numbers = new int[10];
         System.out.print("Enter 10 numbers sparated by a space: ");
         for (int i = 0; i < numbers.length; i++)
         {
            numbers[i] = input.nextInt();
         }
         System.out.println("Distinct elements Array: ");
         eliminateDuplicates(numbers);
         System.out.println("Distinct elements Array: ");

      }
   }

   // method for elimination of duplicate values
   public static void eliminateDuplicates(int[] numbers) {
      int temporary;
      int val_temp = 0;
      int val_temp2 = 1;
      int y = 0;
      for (int i = 0; i < 10; i++)
      {
         temporary = numbers[i];
         for (int j = 0; j < val_temp; j++)
         {
            if (numbers[j] == temporary)
            {
               val_temp2 = 2;
               break;
            }
            else {
               val_temp2 = 1;
            }
         }
         if (val_temp2 == 1)
         {
            val_temp = val_temp + 1;
            numbers[y] = temporary;
            System.out.print(temporary + " ");
            y = y + 1;
         }
      }
   }
}


text:
// Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ash/system/unified/hps_notify_controller.h"

#include <memory>

#include "ash/constants/ash_features.h"
#include "ash/constants/ash_pref_names.h"
#include "ash/constants/ash_switches.h"
#include "ash/session/session_controller_impl.h"
#include "ash/session/test_session_controller_client.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "base/test/scoped_command_line.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "base/time/time.h"
#include "chromeos/dbus/hps/fake_hps_dbus_client.h"
#include "chromeos/dbus/hps/hps_dbus_client.h"
#include "chromeos/dbus/hps/hps_service.pb.h"
#include "components/account_id/account_id.h"
#include "components/user_manager/user_type.h"

namespace ash {
namespace {

// The minimum positive window length will be in the range of a few seconds.
// Here we define two windows that will surely be shorter and longer resp. than
// the positive window length.
constexpr base::TimeDelta kShortTime = base::Milliseconds(30);
constexpr base::TimeDelta kLongTime = base::Seconds(30);

// A fixture that provides access to a fake daemon and an instance of the
// controller hooked up to the test environment.
class HpsNotifyControllerTestBase : public NoSessionAshTestBase {
 public:
  // Arguments control the state of the feature and service on controller
  // construction. We can't set this value in individual tests since it must be
  // done before AshTestBase::SetUp() executes.
  HpsNotifyControllerTestBase(bool service_available,
                              bool service_state,
                              const std::map<std::string, std::string>& params)
      : NoSessionAshTestBase(
            base::test::TaskEnvironment::TimeSource::MOCK_TIME),
        service_available_(service_available),
        service_state_(service_state),
        params_(params) {
    scoped_feature_list_.InitAndEnableFeatureWithParameters(
        ash::features::kSnoopingProtection, params_);
    scoped_command_line_.GetProcessCommandLine()->AppendSwitch(
        switches::kHasHps);
  }

  HpsNotifyControllerTestBase(const HpsNotifyControllerTestBase&) = delete;
  HpsNotifyControllerTestBase& operator=(const HpsNotifyControllerTestBase&) =
      delete;
  ~HpsNotifyControllerTestBase() override = default;

  void SetUp() override {
    chromeos::HpsDBusClient::InitializeFake();
    dbus_client_ = chromeos::FakeHpsDBusClient::Get();
    dbus_client_->set_hps_service_is_available(service_available_);
    dbus_client_->set_hps_notify_result(
        service_state_ ? hps::HpsResult::POSITIVE : hps::HpsResult::NEGATIVE);

    AshTestBase::SetUp();

    controller_ = Shell::Get()->hps_notify_controller();

    // The controller has now been initialized, part of which entails sending a
    // method to the DBus service. Here we wait for the service to
    // asynchronously respond.
    task_environment()->FastForwardBy(kShortTime);
  }

  void TearDown() override {
    AshTestBase::TearDown();
    chromeos::HpsDBusClient::Shutdown();
  }

 protected:
  base::test::ScopedFeatureList scoped_feature_list_;
  base::test::ScopedCommandLine scoped_command_line_;

  const bool service_available_;
  const bool service_state_;
  const std::map<std::string, std::string> params_;

  chromeos::FakeHpsDBusClient* dbus_client_ = nullptr;
  HpsNotifyController* controller_ = nullptr;

  // Simulates a login. This will trigger a DBus call if and only if logging in
  // was the final precondition required for the feature. Hence we wait for any
  // asynchronous logic to complete, revealing whether a DBus call was correctly
  // or incorrectly made.
  void SimulateLogin() {
    SimulateUserLogin("testuser@gmail.com");
    task_environment()->FastForwardBy(kShortTime);
  }

  // Enables or disables the user pref for the feature. This will trigger a DBus
  // call if and only if logging in was the final precondition required for the
  // feature. Hence we wait for any asynchronous logic to complete, revealing
  // whether a DBus call was correctly or incorrectly made.
  void SetEnabledPref(bool enabled) {
    Shell::Get()->session_controller()->GetActivePrefService()->SetBoolean(
        prefs::kSnoopingProtectionEnabled, enabled);
    task_environment()->FastForwardBy(kShortTime);
  }
};

// A test fixture where no snooper is initially detected (using a minimal set of
// valid params).
class HpsNotifyControllerTestAbsent : public HpsNotifyControllerTestBase {
 public:
  HpsNotifyControllerTestAbsent()
      : HpsNotifyControllerTestBase(
            /*service_available=*/true,
            /*service_state=*/false,
            /*params=*/{{"SnoopingProtection_filter_config_case", "1"}}) {}
};

// Test that icon is hidden by default.
TEST_F(HpsNotifyControllerTestAbsent, Hidden) {
  SimulateLogin();
  SetEnabledPref(false);

  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  EXPECT_FALSE(controller_->SnooperPresent());
}

// Test that messages from the daemon toggle the icon.
TEST_F(HpsNotifyControllerTestAbsent, HpsStateChange) {
  SimulateLogin();
  SetEnabledPref(true);

  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  EXPECT_FALSE(controller_->SnooperPresent());

  controller_->OnHpsNotifyChanged(hps::HpsResult::POSITIVE);
  task_environment()->FastForwardBy(kLongTime);

  EXPECT_TRUE(controller_->SnooperPresent());

  controller_->OnHpsNotifyChanged(hps::HpsResult::NEGATIVE);
  task_environment()->FastForwardBy(kLongTime);

  EXPECT_FALSE(controller_->SnooperPresent());
}

// Test that daemon signals are only enabled when session and pref state means
// they will be used.
TEST_F(HpsNotifyControllerTestAbsent, ReconfigureOnPrefs) {
  // When the service becomes available for the first time, one disable is
  // performed in case the last session ended in a crash without de-configuring
  // the daemon.
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  SimulateLogin();
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  // Shouldn't configure or message the daemon until the user is ready to start
  // using the feature.
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  // Should de-configure the signal when it isn't being used.
  SetEnabledPref(false);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 2);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  // Should re-configure and re-poll when the signal becomes relevant again.
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 2);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 2);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 2);
}

// Test that daemon signals are correctly enabled/disabled when the daemon
// starts and stops.
TEST_F(HpsNotifyControllerTestAbsent, ReconfigureOnRestarts) {
  SimulateLogin();
  SetEnabledPref(true);

  // Should configure when we're both logged in and have our pref enabled. The
  // clean-up deconfigure always occurs.
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  // No deconfigure sent when the service shuts down, because it's unreachable.
  controller_->OnShutdown();
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  // Should reconfigure as soon as the service becomes available again.
  controller_->OnRestart();
  task_environment()->FastForwardBy(kLongTime);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 2);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 2);
}

// Test that the service is only re-configured when the user is _both_ logged-in
// and has enabled the preference.
TEST_F(HpsNotifyControllerTestAbsent, ReconfigureOnlyIfNecessary) {
  // Only the clean-up de-configure should have been sent.
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  // Not logged in, so should not configure the service.
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  // Only configure when both logged in and pref enabled.
  SimulateLogin();
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);
}

// A test fixture where a snooper is initially detected (using a minimal set of
// valid params).
class HpsNotifyControllerTestPresent : public HpsNotifyControllerTestBase {
 public:
  HpsNotifyControllerTestPresent()
      : HpsNotifyControllerTestBase(
            /*service_available=*/true,
            /*service_state=*/true,
            /*params=*/{{"SnoopingProtection_filter_config_case", "1"}}) {}
};

// Test that initial daemon state is considered.
TEST_F(HpsNotifyControllerTestPresent, HpsState) {
  SimulateLogin();
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  EXPECT_TRUE(controller_->SnooperPresent());
}

// Test that a user changing their preference toggles the icon.
TEST_F(HpsNotifyControllerTestPresent, PrefChanged) {
  SimulateLogin();
  SetEnabledPref(false);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  EXPECT_FALSE(controller_->SnooperPresent());

  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  EXPECT_TRUE(controller_->SnooperPresent());
}

// Test that eye icon isn't shown during the OOBE.
TEST_F(HpsNotifyControllerTestPresent, Oobe) {
  TestSessionControllerClient* session = GetSessionControllerClient();

  // Simulate end of OOBE when user is logged in.
  session->AddUserSession("testuser@gmail.com", user_manager::USER_TYPE_REGULAR,
                          /*provide_pref_service=*/true,
                          /*is_new_profile=*/true);
  session->SwitchActiveUser(AccountId::FromUserEmail("testuser@gmail.com"));
  session->SetSessionState(session_manager::SessionState::OOBE);

  // Shouldn't configure, as the session isn't active.
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  EXPECT_FALSE(controller_->SnooperPresent());

  // Triggers an asynchronous DBus method call.
  session->SetSessionState(session_manager::SessionState::ACTIVE);
  task_environment()->FastForwardBy(kLongTime);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  EXPECT_TRUE(controller_->SnooperPresent());
}

// Test that the eye icon isn't shown at the login page.
TEST_F(HpsNotifyControllerTestPresent, Login) {
  // Note: login deferred.

  // Shouldn't configure, as the session isn't active.
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  EXPECT_FALSE(controller_->SnooperPresent());

  SimulateLogin();

  // Don't show until new user has enabled their preference.
  EXPECT_FALSE(controller_->SnooperPresent());

  SetEnabledPref(true);
  EXPECT_TRUE(controller_->SnooperPresent());
}

// Test that the controller handles service restarts.
TEST_F(HpsNotifyControllerTestPresent, Restarts) {
  SimulateLogin();
  SetEnabledPref(true);

  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);
  EXPECT_TRUE(controller_->SnooperPresent());

  // Icon is hidden when service goes down. Could erroneously trigger an
  // asynchronous DBus method call.
  dbus_client_->set_hps_service_is_available(false);
  controller_->OnShutdown();
  task_environment()->FastForwardBy(kLongTime);
  EXPECT_FALSE(controller_->SnooperPresent());

  // Icon returns when service restarts. Controller now polls the DBus service
  // which responds asynchronously.
  dbus_client_->set_hps_service_is_available(true);
  controller_->OnRestart();
  task_environment()->FastForwardBy(kLongTime);

  EXPECT_EQ(dbus_client_->hps_notify_count(), 2);
  EXPECT_TRUE(controller_->SnooperPresent());
}

// Check that the controller state stays consistent even when the daemon starts
// and stops.
TEST_F(HpsNotifyControllerTestPresent, ClearHpsState) {
  SimulateLogin();
  SetEnabledPref(true);
  EXPECT_EQ(controller_->SnooperPresent(), true);

  // This should internally clear the cached daemon state.
  SetEnabledPref(false);
  EXPECT_EQ(controller_->SnooperPresent(), false);

  // Note: we don't exhaust the run loop here since we want to check the
  // controller state _before_ it is updated by asynchronous DBus calls.
  Shell::Get()->session_controller()->GetActivePrefService()->SetBoolean(
      prefs::kSnoopingProtectionEnabled, true);
  EXPECT_EQ(controller_->SnooperPresent(), false);
}

// Test that detection is started and stopped based on whether the device's
// physical orientation is suitable for sensing.
TEST_F(HpsNotifyControllerTestPresent, Orientation) {
  SimulateLogin();
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);
  EXPECT_TRUE(controller_->SnooperPresent());

  // When the orientation becomes unsuitable, we should disable the daemon.
  controller_->OnOrientationChanged(/*suitable_for_hps=*/false);
  task_environment()->FastForwardBy(kLongTime);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 2);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);
  EXPECT_FALSE(controller_->SnooperPresent());

  // When the orientation becomes suitable again, we should re-enable the
  // daemon.
  controller_->OnOrientationChanged(/*suitable_for_hps=*/true);
  task_environment()->FastForwardBy(kLongTime);
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 2);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 2);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 2);
  EXPECT_TRUE(controller_->SnooperPresent());
}

// Test that the minimum positive window is respected.
TEST_F(HpsNotifyControllerTestPresent, PositiveWindow) {
  SimulateLogin();
  SetEnabledPref(true);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  EXPECT_TRUE(controller_->SnooperPresent());
  controller_->OnHpsNotifyChanged(hps::HpsResult::NEGATIVE);

  // The snooping status shouldn't immediately change, since we have a minimum
  // length that it should remain positive.
  task_environment()->FastForwardBy(kShortTime);
  EXPECT_TRUE(controller_->SnooperPresent());

  // After the window, it should become false.
  task_environment()->FastForwardBy(kLongTime);
  EXPECT_FALSE(controller_->SnooperPresent());

  // Snooping status should always immediately become true and stay true.
  controller_->OnHpsNotifyChanged(hps::HpsResult::POSITIVE);
  EXPECT_TRUE(controller_->SnooperPresent());
  task_environment()->FastForwardBy(kLongTime);
  EXPECT_TRUE(controller_->SnooperPresent());

  // Snooping status should immediately become false if there is an HPS
  // reconfiguration (v.s. state change).
  controller_->OnShutdown();
  task_environment()->FastForwardBy(kShortTime);
  EXPECT_FALSE(controller_->SnooperPresent());
}

// Fixture with the DBus service initially unavailable (using a minimal set of
// valid params).
class HpsNotifyControllerTestUnavailable : public HpsNotifyControllerTestBase {
 public:
  HpsNotifyControllerTestUnavailable()
      : HpsNotifyControllerTestBase(
            /*service_available=*/false,
            /*service_state=*/true,
            /*params=*/{{"SnoopingProtection_filter_config_case", "1"}}) {}
};

// Test that the controller waits for the DBus service to be available and
// doesn't communicate until it is.
TEST_F(HpsNotifyControllerTestUnavailable, WaitForService) {
  SimulateLogin();
  SetEnabledPref(true);

  // Shouldn't send any signals (even the clean-up deconfigure) to a service
  // that isn't available.
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);

  EXPECT_FALSE(controller_->SnooperPresent());

  // Triggers an asynchronous DBus method call.
  dbus_client_->set_hps_service_is_available(true);
  controller_->OnRestart();
  task_environment()->FastForwardBy(kLongTime);

  // Should now configure and send the initial poll.
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 1);

  // Controller now polls the DBus service which responds asynchronously.
  EXPECT_TRUE(controller_->SnooperPresent());
}

// Fixture with an invalid feature config.
class HpsNotifyControllerTestBadParams : public HpsNotifyControllerTestBase {
 public:
  HpsNotifyControllerTestBadParams()
      : HpsNotifyControllerTestBase(
            /*service_available=*/true,
            /*service_state=*/true,
            /*params=*/{{"SnoopingProtection_filter_config_case", "0"}}) {}
};

// Test that the controller gracefully handles invalid feature parameters.
TEST_F(HpsNotifyControllerTestBadParams, BadParams) {
  SimulateLogin();
  SetEnabledPref(true);

  // Should send the clean-up disable even if we currently have a bad config.
  EXPECT_EQ(dbus_client_->enable_hps_notify_count(), 0);
  EXPECT_EQ(dbus_client_->disable_hps_notify_count(), 1);
  EXPECT_EQ(dbus_client_->hps_notify_count(), 0);
}

}  // namespace
}  // namespace ash


text:
<?php

namespace Broadway\Saga\Metadata;

use Broadway\Saga\MetadataInterface;
use RuntimeException;

class Metadata implements MetadataInterface
{
    private $criteria;

    /**
     * @param array $criteria
     */
    public function __construct($criteria)
    {
        $this->criteria = $criteria;
    }

    /**
     * {@inheritDoc}
     */
    public function handles($event)
    {
        $eventName = $this->getClassName($event);

        return isset($this->criteria[$eventName]);
    }

    /**
     * {@inheritDoc}
     */
    public function criteria($event)
    {
        $eventName = $this->getClassName($event);

        if (! isset($this->criteria[$eventName])) {
            throw new RuntimeException(sprintf("No criteria for event '%s'.", $eventName));
        }

        return $this->criteria[$eventName]($event);
    }

    private function getClassName($event)
    {
        $classParts = explode('\\', get_class($event));

        return end($classParts);
    }
}


text:
This script demonstrates a method of setting up a communication channel between
a dialog and a sidebar in Apps Script. This helps solve the common problem
of having your sidebar know when a dialog is opened, is submitted, closed, etc.

With the introduction of the IFRAME sandbox mode, HtmlService UIs can take
advantage of the
[HTML5 localStorage API](https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage).
The open source library [intercom.js](https://github.com/diy/intercom.js/)
builds a messaging system on top of this API, allowing for dialogs and sidebars
in the same browser to communicate with each other.

An overview of the process is as follows:

* The sidebar requests a new dialog to be opened.
* The backend generates a new ID for the dialog, opens the dialog (passing in
  that ID as a template parameter), and sends the ID back to the sidebar.
* The sidebar listens for events on the dialog's intercom.js channel.
* The dialog regularly "checks in" with the sidebar, resetting a
  [timer](https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers).
* When the user completes the dialog (by clicking either the "OK" or "Cancel"
  button) it sends this status change to the sidebar.
* If the sidebar's timer actually fires, that means the dialog hasn't checked in
  recently, and it is considered "lost".