text:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <arkode/arkode.h>            /* prototypes for ARKODE fcts. */
#include <arkode/arkode_spgmr.h>      /* prototypes and constants for ARKSPGMR */
#include <arkode/arkode_bbdpre.h>     /* prototypes for ARKBBDPRE module */
#include <nvector/nvector_parallel.h> /* def. of N_Vector, macro NV_DATA_P */
#include <sundials/sundials_types.h>  /* definitions of realtype, booleantype */
#include <sundials/sundials_math.h>   /* definition of macros SUNSQR and EXP */
#include <mpi.h>                      /* MPI constants and types */

/* Problem Constants */
#define ZERO         RCONST(0.0)
#define NVARS        2                 /* number of species         */
#define KH           RCONST(4.0e-6)    /* horizontal diffusivity Kh */
#define VEL          RCONST(0.001)     /* advection velocity V      */
#define KV0          RCONST(1.0e-8)    /* coefficient in Kv(y)      */
#define Q1           RCONST(1.63e-16)  /* coefficients q1, q2, c3   */
#define Q2           RCONST(4.66e-16)
#define C3           RCONST(3.7e16)
#define A3           RCONST(22.62)     /* coefficient in expression for q3(t) */
#define A4           RCONST(7.601)     /* coefficient in expression for q4(t) */
#define C1_SCALE     RCONST(1.0e6)     /* coefficients in initial profiles    */
#define C2_SCALE     RCONST(1.0e12)

#define T0           ZERO                /* initial time */
#define NOUT         12                  /* number of output times */
#define TWOHR        RCONST(7200.0)      /* number of seconds in two hours  */
#define HALFDAY      RCONST(4.32e4)      /* number of seconds in a half day */
#define PI       RCONST(3.1415926535898) /* pi */

#define XMIN         ZERO                /* grid boundaries in x  */
#define XMAX         RCONST(20.0)
#define YMIN         RCONST(30.0)        /* grid boundaries in y  */
#define YMAX         RCONST(50.0)

#define NPEX         2              /* no. PEs in x direction of PE array */
#define NPEY         2              /* no. PEs in y direction of PE array */
                                    /* Total no. PEs = NPEX*NPEY */
#define MXSUB        5              /* no. x points per subgrid */
#define MYSUB        5              /* no. y points per subgrid */

#define MX           (NPEX*MXSUB)   /* MX = number of x mesh points */
#define MY           (NPEY*MYSUB)   /* MY = number of y mesh points */
                                    /* Spatial mesh is MX by MY */
/* ARKodeInit Constants */
#define RTOL    RCONST(1.0e-5)    /* scalar relative tolerance */
#define FLOOR   RCONST(100.0)     /* value of C1 or C2 at which tolerances */
                                  /* change from relative to absolute      */
#define ATOL    (RTOL*FLOOR)      /* scalar absolute tolerance */

/* Type : UserData
   contains problem constants, extended dependent variable array,
   grid constants, processor indices, MPI communicator */
typedef struct {
  realtype q4, om, dx, dy, hdco, haco, vdco;
  realtype uext[NVARS*(MXSUB+2)*(MYSUB+2)];
  int my_pe, isubx, isuby;
  long int nvmxsub, nvmxsub2, Nlocal;
  MPI_Comm comm;
} *UserData;

/* Prototypes of private helper functions */
static void InitUserData(int my_pe, long int local_N, MPI_Comm comm,
                         UserData data);
static void SetInitialProfiles(N_Vector u, UserData data);
static void PrintIntro(int npes, long int mudq, long int mldq,
		       long int mukeep, long int mlkeep);
static void PrintOutput(void *arkode_mem, int my_pe, MPI_Comm comm,
                        N_Vector u, realtype t);
static void PrintFinalStats(void *arkode_mem);
static void BSend(MPI_Comm comm,
                  int my_pe, int isubx, int isuby,
                  long int dsizex, long int dsizey,
                  realtype uarray[]);
static void BRecvPost(MPI_Comm comm, MPI_Request request[],
                      int my_pe, int isubx, int isuby,
		      long int dsizex, long int dsizey,
		      realtype uext[], realtype buffer[]);
static void BRecvWait(MPI_Request request[],
                      int isubx, int isuby,
                      long int dsizex, realtype uext[],
                      realtype buffer[]);
static void fucomm(realtype t, N_Vector u, void *user_data);

/* Prototype of function called by the solver */
static int f(realtype t, N_Vector u, N_Vector udot, void *user_data);

/* Prototype of functions called by the ARKBBDPRE module */
static int flocal(long int Nlocal, realtype t, N_Vector u,
                  N_Vector udot, void *user_data);

/* Private function to check function return values */
static int check_flag(void *flagvalue, char *funcname, int opt, int id);

/***************************** Main Program ******************************/
int main(int argc, char *argv[])
{
  UserData data;
  void *arkode_mem;
  realtype abstol, reltol, t, tout;
  N_Vector u;
  int iout, my_pe, npes, flag, jpre;
  long int neq, local_N, mudq, mldq, mukeep, mlkeep;
  MPI_Comm comm;

  data = NULL;
  arkode_mem = NULL;
  u = NULL;

  /* Set problem size neq */
  neq = NVARS*MX*MY;

  /* Get processor number and total number of pe's */
  MPI_Init(&argc, &argv);
  comm = MPI_COMM_WORLD;
  MPI_Comm_size(comm, &npes);
  MPI_Comm_rank(comm, &my_pe);

  if (npes != NPEX*NPEY) {
    if (my_pe == 0)
      fprintf(stderr, "\nMPI_ERROR(0): npes = %d is not equal to NPEX*NPEY = %d\n\n",
              npes, NPEX*NPEY);
    MPI_Finalize();
    return(1);
  }

  /* Set local length */
  local_N = NVARS*MXSUB*MYSUB;

  /* Allocate and load user data block */
  data = (UserData) malloc(sizeof *data);
  if(check_flag((void *)data, "malloc", 2, my_pe)) MPI_Abort(comm, 1);
  InitUserData(my_pe, local_N, comm, data);

  /* Allocate and initialize u, and set tolerances */
  u = N_VNew_Parallel(comm, local_N, neq);
  if(check_flag((void *)u, "N_VNew_Parallel", 0, my_pe)) MPI_Abort(comm, 1);
  SetInitialProfiles(u, data);
  abstol = ATOL;
  reltol = RTOL;

  /* Call ARKodeCreate to create the solver memory */
  arkode_mem = ARKodeCreate();
  if(check_flag((void *)arkode_mem, "ARKodeCreate", 0, my_pe)) MPI_Abort(comm, 1);

  /* Set the pointer to user-defined data */
  flag = ARKodeSetUserData(arkode_mem, data);
  if(check_flag(&flag, "ARKodeSetUserData", 1, my_pe)) MPI_Abort(comm, 1);

  /* Call ARKodeInit to initialize the integrator memory and specify the
     user's right hand side functions in u'=fe(t,u)+fi(t,u) [here fe is NULL],
     the inital time T0, and the initial dependent variable vector u. */
  flag = ARKodeInit(arkode_mem, NULL, f, T0, u);
  if(check_flag(&flag, "ARKodeInit", 1, my_pe)) return(1);

  /* Call ARKodeSetMaxNumSteps to increase default */
  flag = ARKodeSetMaxNumSteps(arkode_mem, 10000);
  if (check_flag(&flag, "ARKodeSetMaxNumSteps", 1, my_pe)) return(1);

  /* Call ARKodeSStolerances to specify the scalar relative tolerance
     and scalar absolute tolerances */
  flag = ARKodeSStolerances(arkode_mem, reltol, abstol);
  if (check_flag(&flag, "ARKodeSStolerances", 1, my_pe)) return(1);

  /* Call ARKSpgmr to specify the linear solver ARKSPGMR with left
     preconditioning and the default Krylov dimension maxl */
  flag = ARKSpgmr(arkode_mem, PREC_LEFT, 0);
  if(check_flag(&flag, "ARKBBDSpgmr", 1, my_pe)) MPI_Abort(comm, 1);

  /* Initialize BBD preconditioner */
  mudq = mldq = NVARS*MXSUB;
  mukeep = mlkeep = NVARS;
  flag = ARKBBDPrecInit(arkode_mem, local_N, mudq, mldq,
			mukeep, mlkeep, ZERO, flocal, NULL);
  if(check_flag(&flag, "ARKBBDPrecAlloc", 1, my_pe)) MPI_Abort(comm, 1);

  /* Print heading */
  if (my_pe == 0) PrintIntro(npes, mudq, mldq, mukeep, mlkeep);

  /* Loop over jpre (= PREC_LEFT, PREC_RIGHT), and solve the problem */
  for (jpre=PREC_LEFT; jpre<=PREC_RIGHT; jpre++) {

    /* On second run, re-initialize u, the integrator, ARKBBDPRE, and ARKSPGMR */
    if (jpre == PREC_RIGHT) {

      SetInitialProfiles(u, data);

      flag = ARKodeReInit(arkode_mem, NULL, f, T0, u);
      if(check_flag(&flag, "ARKodeReInit", 1, my_pe)) MPI_Abort(comm, 1);

      flag = ARKBBDPrecReInit(arkode_mem, mudq, mldq, ZERO);
      if(check_flag(&flag, "ARKBBDPrecReInit", 1, my_pe)) MPI_Abort(comm, 1);

      flag = ARKSpilsSetPrecType(arkode_mem, PREC_RIGHT);
      check_flag(&flag, "ARKSpilsSetPrecType", 1, my_pe);

      if (my_pe == 0) {
	printf("\n\n-------------------------------------------------------");
	printf("------------\n");
      }

    }

    if (my_pe == 0) {
      printf("\n\nPreconditioner type is:  jpre = %s\n\n",
	     (jpre == PREC_LEFT) ? "PREC_LEFT" : "PREC_RIGHT");
    }

    /* In loop over output points, call ARKode, print results, test for error */
    for (iout=1, tout=TWOHR; iout<=NOUT; iout++, tout+=TWOHR) {
      flag = ARKode(arkode_mem, tout, u, &t, ARK_NORMAL);
      if(check_flag(&flag, "ARKode", 1, my_pe)) break;
      PrintOutput(arkode_mem, my_pe, comm, u, t);
    }

    /* Print final statistics */
    if (my_pe == 0) PrintFinalStats(arkode_mem);

  } /* End of jpre loop */

  /* Free memory */
  N_VDestroy_Parallel(u);
  free(data);
  ARKodeFree(&arkode_mem);
  MPI_Finalize();
  return(0);
}

/*********************** Private Helper Functions ************************/

/* Load constants in data */
static void InitUserData(int my_pe, long int local_N, MPI_Comm comm,
                         UserData data)
{
  int isubx, isuby;

  /* Set problem constants */
  data->om = PI/HALFDAY;
  data->dx = (XMAX-XMIN)/((realtype)(MX-1));
  data->dy = (YMAX-YMIN)/((realtype)(MY-1));
  data->hdco = KH/SUNSQR(data->dx);
  data->haco = VEL/(RCONST(2.0)*data->dx);
  data->vdco = (RCONST(1.0)/SUNSQR(data->dy))*KV0;

  /* Set machine-related constants */
  data->comm = comm;
  data->my_pe = my_pe;
  data->Nlocal = local_N;
  /* isubx and isuby are the PE grid indices corresponding to my_pe */
  isuby = my_pe/NPEX;
  isubx = my_pe - isuby*NPEX;
  data->isubx = isubx;
  data->isuby = isuby;
  /* Set the sizes of a boundary x-line in u and uext */
  data->nvmxsub = NVARS*MXSUB;
  data->nvmxsub2 = NVARS*(MXSUB+2);
}

/* Set initial conditions in u */
static void SetInitialProfiles(N_Vector u, UserData data)
{
  int isubx, isuby;
  int lx, ly, jx, jy;
  long int offset;
  realtype dx, dy, x, y, cx, cy, xmid, ymid;
  realtype *uarray;

  /* Set pointer to data array in vector u */
  uarray = NV_DATA_P(u);

  /* Get mesh spacings, and subgrid indices for this PE */
  dx = data->dx;         dy = data->dy;
  isubx = data->isubx;   isuby = data->isuby;

  /* Load initial profiles of c1 and c2 into local u vector.
  Here lx and ly are local mesh point indices on the local subgrid,
  and jx and jy are the global mesh point indices. */
  offset = 0;
  xmid = RCONST(0.5)*(XMIN + XMAX);
  ymid = RCONST(0.5)*(YMIN + YMAX);
  for (ly = 0; ly < MYSUB; ly++) {
    jy = ly + isuby*MYSUB;
    y = YMIN + jy*dy;
    cy = SUNSQR(RCONST(0.1)*(y - ymid));
    cy = RCONST(1.0) - cy + RCONST(0.5)*SUNSQR(cy);
    for (lx = 0; lx < MXSUB; lx++) {
      jx = lx + isubx*MXSUB;
      x = XMIN + jx*dx;
      cx = SUNSQR(RCONST(0.1)*(x - xmid));
      cx = RCONST(1.0) - cx + RCONST(0.5)*SUNSQR(cx);
      uarray[offset  ] = C1_SCALE*cx*cy;
      uarray[offset+1] = C2_SCALE*cx*cy;
      offset = offset + 2;
    }
  }
}

/* Print problem introduction */
static void PrintIntro(int npes, long int mudq, long int mldq,
		       long int mukeep, long int mlkeep)
{
  printf("\n2-species diurnal advection-diffusion problem\n");
  printf("  %d by %d mesh on %d processors\n", MX, MY, npes);
  printf("  Using ARKBBDPRE preconditioner module\n");
  printf("    Difference-quotient half-bandwidths are");
  printf(" mudq = %ld,  mldq = %ld\n", mudq, mldq);
  printf("    Retained band block half-bandwidths are");
  printf(" mukeep = %ld,  mlkeep = %ld", mukeep, mlkeep);
  return;
}

/* Print current t, step count, order, stepsize, and sampled c1,c2 values */
static void PrintOutput(void *arkode_mem, int my_pe, MPI_Comm comm,
                        N_Vector u, realtype t)
{
  int flag, npelast;
  long int i0, i1, nst;
  realtype hu, *uarray, tempu[2];
  MPI_Status status;

  npelast = NPEX*NPEY - 1;
  uarray = NV_DATA_P(u);

  /* Send c1,c2 at top right mesh point to PE 0 */
  if (my_pe == npelast) {
    i0 = NVARS*MXSUB*MYSUB - 2;
    i1 = i0 + 1;
    if (npelast != 0)
      MPI_Send(&uarray[i0], 2, PVEC_REAL_MPI_TYPE, 0, 0, comm);
    else {
      tempu[0] = uarray[i0];
      tempu[1] = uarray[i1];
    }
  }

  /* On PE 0, receive c1,c2 at top right, then print performance data
     and sampled solution values */
  if (my_pe == 0) {
    if (npelast != 0)
      MPI_Recv(&tempu[0], 2, PVEC_REAL_MPI_TYPE, npelast, 0, comm, &status);
    flag = ARKodeGetNumSteps(arkode_mem, &nst);
    check_flag(&flag, "ARKodeGetNumSteps", 1, my_pe);
    flag = ARKodeGetLastStep(arkode_mem, &hu);
    check_flag(&flag, "ARKodeGetLastStep", 1, my_pe);
#if defined(SUNDIALS_EXTENDED_PRECISION)
    printf("t = %.2Le   no. steps = %ld   stepsize = %.2Le\n",
           t, nst, hu);
    printf("At bottom left:  c1, c2 = %12.3Le %12.3Le \n", uarray[0], uarray[1]);
    printf("At top right:    c1, c2 = %12.3Le %12.3Le \n\n", tempu[0], tempu[1]);
#elif defined(SUNDIALS_DOUBLE_PRECISION)
    printf("t = %.2e   no. steps = %ld   stepsize = %.2e\n",
           t, nst, hu);
    printf("At bottom left:  c1, c2 = %12.3e %12.3e \n", uarray[0], uarray[1]);
    printf("At top right:    c1, c2 = %12.3e %12.3e \n\n", tempu[0], tempu[1]);
#else
    printf("t = %.2e   no. steps = %ld   stepsize = %.2e\n",
           t, nst, hu);
    printf("At bottom left:  c1, c2 = %12.3e %12.3e \n", uarray[0], uarray[1]);
    printf("At top right:    c1, c2 = %12.3e %12.3e \n\n", tempu[0], tempu[1]);
#endif
  }
}

/* Print final statistics contained in iopt */
static void PrintFinalStats(void *arkode_mem)
{
  long int lenrw, leniw ;
  long int lenrwLS, leniwLS;
  long int lenrwBBDP, leniwBBDP, ngevalsBBDP;
  long int nst, nfe, nfi, nsetups, nni, ncfn, netf;
  long int nli, npe, nps, ncfl, nfeLS;
  int flag;

  flag = ARKodeGetWorkSpace(arkode_mem, &lenrw, &leniw);
  check_flag(&flag, "ARKodeGetWorkSpace", 1, 0);
  flag = ARKodeGetNumSteps(arkode_mem, &nst);
  check_flag(&flag, "ARKodeGetNumSteps", 1, 0);
  flag = ARKodeGetNumRhsEvals(arkode_mem, &nfe, &nfi);
  check_flag(&flag, "ARKodeGetNumRhsEvals", 1, 0);
  flag = ARKodeGetNumLinSolvSetups(arkode_mem, &nsetups);
  check_flag(&flag, "ARKodeGetNumLinSolvSetups", 1, 0);
  flag = ARKodeGetNumErrTestFails(arkode_mem, &netf);
  check_flag(&flag, "ARKodeGetNumErrTestFails", 1, 0);
  flag = ARKodeGetNumNonlinSolvIters(arkode_mem, &nni);
  check_flag(&flag, "ARKodeGetNumNonlinSolvIters", 1, 0);
  flag = ARKodeGetNumNonlinSolvConvFails(arkode_mem, &ncfn);
  check_flag(&flag, "ARKodeGetNumNonlinSolvConvFails", 1, 0);

  flag = ARKSpilsGetWorkSpace(arkode_mem, &lenrwLS, &leniwLS);
  check_flag(&flag, "ARKSpilsGetWorkSpace", 1, 0);
  flag = ARKSpilsGetNumLinIters(arkode_mem, &nli);
  check_flag(&flag, "ARKSpilsGetNumLinIters", 1, 0);
  flag = ARKSpilsGetNumPrecEvals(arkode_mem, &npe);
  check_flag(&flag, "ARKSpilsGetNumPrecEvals", 1, 0);
  flag = ARKSpilsGetNumPrecSolves(arkode_mem, &nps);
  check_flag(&flag, "ARKSpilsGetNumPrecSolves", 1, 0);
  flag = ARKSpilsGetNumConvFails(arkode_mem, &ncfl);
  check_flag(&flag, "ARKSpilsGetNumConvFails", 1, 0);
  flag = ARKSpilsGetNumRhsEvals(arkode_mem, &nfeLS);
  check_flag(&flag, "ARKSpilsGetNumRhsEvals", 1, 0);

  printf("\nFinal Statistics: \n\n");
  printf("lenrw   = %5ld     leniw   = %5ld\n", lenrw, leniw);
  printf("lenrwls = %5ld     leniwls = %5ld\n", lenrwLS, leniwLS);
  printf("nst     = %5ld     nfe     = %5ld\n", nst, nfe);
  printf("nfe     = %5ld     nfels   = %5ld\n", nfi, nfeLS);
  printf("nni     = %5ld     nli     = %5ld\n", nni, nli);
  printf("nsetups = %5ld     netf    = %5ld\n", nsetups, netf);
  printf("npe     = %5ld     nps     = %5ld\n", npe, nps);
  printf("ncfn    = %5ld     ncfl    = %5ld\n\n", ncfn, ncfl);

  flag = ARKBBDPrecGetWorkSpace(arkode_mem, &lenrwBBDP, &leniwBBDP);
  check_flag(&flag, "ARKBBDPrecGetWorkSpace", 1, 0);
  flag = ARKBBDPrecGetNumGfnEvals(arkode_mem, &ngevalsBBDP);
  check_flag(&flag, "ARKBBDPrecGetNumGfnEvals", 1, 0);
  printf("In ARKBBDPRE: real/integer local work space sizes = %ld, %ld\n",
	 lenrwBBDP, leniwBBDP);
  printf("             no. flocal evals. = %ld\n",ngevalsBBDP);
}

/* Routine to send boundary data to neighboring PEs */
static void BSend(MPI_Comm comm,
                  int my_pe, int isubx, int isuby,
                  long int dsizex, long int dsizey,
                  realtype uarray[])
{
  int i, ly;
  long int offsetu, offsetbuf;
  realtype bufleft[NVARS*MYSUB], bufright[NVARS*MYSUB];

  /* If isuby > 0, send data from bottom x-line of u */
  if (isuby != 0)
    MPI_Send(&uarray[0], dsizex, PVEC_REAL_MPI_TYPE, my_pe-NPEX, 0, comm);

  /* If isuby < NPEY-1, send data from top x-line of u */
  if (isuby != NPEY-1) {
    offsetu = (MYSUB-1)*dsizex;
    MPI_Send(&uarray[offsetu], dsizex, PVEC_REAL_MPI_TYPE, my_pe+NPEX, 0, comm);
  }

  /* If isubx > 0, send data from left y-line of u (via bufleft) */
  if (isubx != 0) {
    for (ly = 0; ly < MYSUB; ly++) {
      offsetbuf = ly*NVARS;
      offsetu = ly*dsizex;
      for (i = 0; i < NVARS; i++)
        bufleft[offsetbuf+i] = uarray[offsetu+i];
    }
    MPI_Send(&bufleft[0], dsizey, PVEC_REAL_MPI_TYPE, my_pe-1, 0, comm);
  }

  /* If isubx < NPEX-1, send data from right y-line of u (via bufright) */
  if (isubx != NPEX-1) {
    for (ly = 0; ly < MYSUB; ly++) {
      offsetbuf = ly*NVARS;
      offsetu = offsetbuf*MXSUB + (MXSUB-1)*NVARS;
      for (i = 0; i < NVARS; i++)
        bufright[offsetbuf+i] = uarray[offsetu+i];
    }
    MPI_Send(&bufright[0], dsizey, PVEC_REAL_MPI_TYPE, my_pe+1, 0, comm);
  }
}

/* Routine to start receiving boundary data from neighboring PEs.
   Notes:
   1) buffer should be able to hold 2*NVARS*MYSUB realtype entries, should be
   passed to both the BRecvPost and BRecvWait functions, and should not
   be manipulated between the two calls.
   2) request should have 4 entries, and should be passed in both calls also. */
static void BRecvPost(MPI_Comm comm, MPI_Request request[],
                      int my_pe, int isubx, int isuby,
		      long int dsizex, long int dsizey,
		      realtype uext[], realtype buffer[])
{
  long int offsetue;
  /* Have bufleft and bufright use the same buffer */
  realtype *bufleft = buffer, *bufright = buffer+NVARS*MYSUB;

  /* If isuby > 0, receive data for bottom x-line of uext */
  if (isuby != 0)
    MPI_Irecv(&uext[NVARS], dsizex, PVEC_REAL_MPI_TYPE,
    					 my_pe-NPEX, 0, comm, &request[0]);

  /* If isuby < NPEY-1, receive data for top x-line of uext */
  if (isuby != NPEY-1) {
    offsetue = NVARS*(1 + (MYSUB+1)*(MXSUB+2));
    MPI_Irecv(&uext[offsetue], dsizex, PVEC_REAL_MPI_TYPE,
                                         my_pe+NPEX, 0, comm, &request[1]);
  }

  /* If isubx > 0, receive data for left y-line of uext (via bufleft) */
  if (isubx != 0) {
    MPI_Irecv(&bufleft[0], dsizey, PVEC_REAL_MPI_TYPE,
                                         my_pe-1, 0, comm, &request[2]);
  }

  /* If isubx < NPEX-1, receive data for right y-line of uext (via bufright) */
  if (isubx != NPEX-1) {
    MPI_Irecv(&bufright[0], dsizey, PVEC_REAL_MPI_TYPE,
                                         my_pe+1, 0, comm, &request[3]);
  }
}

/* Routine to finish receiving boundary data from neighboring PEs.
   Notes:
   1) buffer should be able to hold 2*NVARS*MYSUB realtype entries, should be
   passed to both the BRecvPost and BRecvWait functions, and should not
   be manipulated between the two calls.
   2) request should have 4 entries, and should be passed in both calls also. */
static void BRecvWait(MPI_Request request[],
                      int isubx, int isuby,
                      long int dsizex, realtype uext[],
                      realtype buffer[])
{
  int i, ly;
  long int dsizex2, offsetue, offsetbuf;
  realtype *bufleft = buffer, *bufright = buffer+NVARS*MYSUB;
  MPI_Status status;

  dsizex2 = dsizex + 2*NVARS;

  /* If isuby > 0, receive data for bottom x-line of uext */
  if (isuby != 0)
    MPI_Wait(&request[0],&status);

  /* If isuby < NPEY-1, receive data for top x-line of uext */
  if (isuby != NPEY-1)
    MPI_Wait(&request[1],&status);

  /* If isubx > 0, receive data for left y-line of uext (via bufleft) */
  if (isubx != 0) {
    MPI_Wait(&request[2],&status);

    /* Copy the buffer to uext */
    for (ly = 0; ly < MYSUB; ly++) {
      offsetbuf = ly*NVARS;
      offsetue = (ly+1)*dsizex2;
      for (i = 0; i < NVARS; i++)
        uext[offsetue+i] = bufleft[offsetbuf+i];
    }
  }

  /* If isubx < NPEX-1, receive data for right y-line of uext (via bufright) */
  if (isubx != NPEX-1) {
    MPI_Wait(&request[3],&status);

    /* Copy the buffer to uext */
    for (ly = 0; ly < MYSUB; ly++) {
      offsetbuf = ly*NVARS;
      offsetue = (ly+2)*dsizex2 - NVARS;
      for (i = 0; i < NVARS; i++)
	uext[offsetue+i] = bufright[offsetbuf+i];
    }
  }
}

/* fucomm routine.  This routine performs all inter-processor
   communication of data in u needed to calculate f.         */
static void fucomm(realtype t, N_Vector u, void *user_data)
{
  UserData data;
  realtype *uarray, *uext, buffer[2*NVARS*MYSUB];
  MPI_Comm comm;
  int my_pe, isubx, isuby;
  long int nvmxsub, nvmysub;
  MPI_Request request[4];

  data = (UserData) user_data;
  uarray = NV_DATA_P(u);

  /* Get comm, my_pe, subgrid indices, data sizes, extended array uext */
  comm = data->comm;  my_pe = data->my_pe;
  isubx = data->isubx;   isuby = data->isuby;
  nvmxsub = data->nvmxsub;
  nvmysub = NVARS*MYSUB;
  uext = data->uext;

  /* Start receiving boundary data from neighboring PEs */
  BRecvPost(comm, request, my_pe, isubx, isuby, nvmxsub, nvmysub, uext, buffer);

  /* Send data from boundary of local grid to neighboring PEs */
  BSend(comm, my_pe, isubx, isuby, nvmxsub, nvmysub, uarray);

  /* Finish receiving boundary data from neighboring PEs */
  BRecvWait(request, isubx, isuby, nvmxsub, uext, buffer);
}

/***************** Function called by the solver **************************/

/* f routine.  Evaluate f(t,y).  First call fucomm to do communication of
   subgrid boundary data into uext.  Then calculate f by a call to flocal. */
static int f(realtype t, N_Vector u, N_Vector udot, void *user_data)
{
  UserData data;

  data = (UserData) user_data;

  /* Call fucomm to do inter-processor communication */
  fucomm (t, u, user_data);

  /* Call flocal to calculate all right-hand sides */
  flocal (data->Nlocal, t, u, udot, user_data);

  return(0);
}

/***************** Functions called by the ARKBBDPRE module ****************/

/* flocal routine.  Compute f(t,y).  This routine assumes that all
   inter-processor communication of data needed to calculate f has already
   been done, and this data is in the work array uext.                    */
static int flocal(long int Nlocal, realtype t, N_Vector u,
                  N_Vector udot, void *user_data)
{
  realtype *uext;
  realtype q3, c1, c2, c1dn, c2dn, c1up, c2up, c1lt, c2lt;
  realtype c1rt, c2rt, cydn, cyup, hord1, hord2, horad1, horad2;
  realtype qq1, qq2, qq3, qq4, rkin1, rkin2, s, vertd1, vertd2, ydn, yup;
  realtype q4coef, dely, verdco, hordco, horaco;
  int i, lx, ly, jy;
  int isubx, isuby;
  long int nvmxsub, nvmxsub2, offsetu, offsetue;
  UserData data;
  realtype *uarray, *duarray;

  uarray = NV_DATA_P(u);
  duarray = NV_DATA_P(udot);

  /* Get subgrid indices, array sizes, extended work array uext */
  data = (UserData) user_data;
  isubx = data->isubx;   isuby = data->isuby;
  nvmxsub = data->nvmxsub; nvmxsub2 = data->nvmxsub2;
  uext = data->uext;

  /* Copy local segment of u vector into the working extended array uext */
  offsetu = 0;
  offsetue = nvmxsub2 + NVARS;
  for (ly = 0; ly < MYSUB; ly++) {
    for (i = 0; i < nvmxsub; i++) uext[offsetue+i] = uarray[offsetu+i];
    offsetu = offsetu + nvmxsub;
    offsetue = offsetue + nvmxsub2;
  }

  /* To facilitate homogeneous Neumann boundary conditions, when this is
  a boundary PE, copy data from the first interior mesh line of u to uext */

  /* If isuby = 0, copy x-line 2 of u to uext */
  if (isuby == 0) {
    for (i = 0; i < nvmxsub; i++) uext[NVARS+i] = uarray[nvmxsub+i];
  }

  /* If isuby = NPEY-1, copy x-line MYSUB-1 of u to uext */
  if (isuby == NPEY-1) {
    offsetu = (MYSUB-2)*nvmxsub;
    offsetue = (MYSUB+1)*nvmxsub2 + NVARS;
    for (i = 0; i < nvmxsub; i++) uext[offsetue+i] = uarray[offsetu+i];
  }

  /* If isubx = 0, copy y-line 2 of u to uext */
  if (isubx == 0) {
    for (ly = 0; ly < MYSUB; ly++) {
      offsetu = ly*nvmxsub + NVARS;
      offsetue = (ly+1)*nvmxsub2;
      for (i = 0; i < NVARS; i++) uext[offsetue+i] = uarray[offsetu+i];
    }
  }

  /* If isubx = NPEX-1, copy y-line MXSUB-1 of u to uext */
  if (isubx == NPEX-1) {
    for (ly = 0; ly < MYSUB; ly++) {
      offsetu = (ly+1)*nvmxsub - 2*NVARS;
      offsetue = (ly+2)*nvmxsub2 - NVARS;
      for (i = 0; i < NVARS; i++) uext[offsetue+i] = uarray[offsetu+i];
    }
  }

  /* Make local copies of problem variables, for efficiency */
  dely = data->dy;
  verdco = data->vdco;
  hordco = data->hdco;
  horaco = data->haco;

  /* Set diurnal rate coefficients as functions of t, and save q4 in
  data block for use by preconditioner evaluation routine            */

  s = sin((data->om)*t);
  if (s > ZERO) {
    q3 = SUNRexp(-A3/s);
    q4coef = SUNRexp(-A4/s);
  } else {
    q3 = ZERO;
    q4coef = ZERO;
  }
  data->q4 = q4coef;

  /* Loop over all grid points in local subgrid */
  for (ly = 0; ly < MYSUB; ly++) {

    jy = ly + isuby*MYSUB;

    /* Set vertical diffusion coefficients at jy +- 1/2 */
    ydn = YMIN + (jy - RCONST(0.5))*dely;
    yup = ydn + dely;
    cydn = verdco*SUNRexp(RCONST(0.2)*ydn);
    cyup = verdco*SUNRexp(RCONST(0.2)*yup);
    for (lx = 0; lx < MXSUB; lx++) {

      /* Extract c1 and c2, and set kinetic rate terms */
      offsetue = (lx+1)*NVARS + (ly+1)*nvmxsub2;
      c1 = uext[offsetue];
      c2 = uext[offsetue+1];
      qq1 = Q1*c1*C3;
      qq2 = Q2*c1*c2;
      qq3 = q3*C3;
      qq4 = q4coef*c2;
      rkin1 = -qq1 - qq2 + 2.0*qq3 + qq4;
      rkin2 = qq1 - qq2 - qq4;

      /* Set vertical diffusion terms */
      c1dn = uext[offsetue-nvmxsub2];
      c2dn = uext[offsetue-nvmxsub2+1];
      c1up = uext[offsetue+nvmxsub2];
      c2up = uext[offsetue+nvmxsub2+1];
      vertd1 = cyup*(c1up - c1) - cydn*(c1 - c1dn);
      vertd2 = cyup*(c2up - c2) - cydn*(c2 - c2dn);

      /* Set horizontal diffusion and advection terms */
      c1lt = uext[offsetue-2];
      c2lt = uext[offsetue-1];
      c1rt = uext[offsetue+2];
      c2rt = uext[offsetue+3];
      hord1 = hordco*(c1rt - RCONST(2.0)*c1 + c1lt);
      hord2 = hordco*(c2rt - RCONST(2.0)*c2 + c2lt);
      horad1 = horaco*(c1rt - c1lt);
      horad2 = horaco*(c2rt - c2lt);

      /* Load all terms into duarray */
      offsetu = lx*NVARS + ly*nvmxsub;
      duarray[offsetu]   = vertd1 + hord1 + horad1 + rkin1;
      duarray[offsetu+1] = vertd2 + hord2 + horad2 + rkin2;
    }
  }

  return(0);
}

/* Check function return value...
     opt == 0 means SUNDIALS function allocates memory so check if
              returned NULL pointer
     opt == 1 means SUNDIALS function returns a flag so check if
              flag >= 0
     opt == 2 means function allocates memory so check if returned
              NULL pointer */
static int check_flag(void *flagvalue, char *funcname, int opt, int id)
{
  int *errflag;

  /* Check if SUNDIALS function returned NULL pointer - no memory allocated */
  if (opt == 0 && flagvalue == NULL) {
    fprintf(stderr, "\nSUNDIALS_ERROR(%d): %s() failed - returned NULL pointer\n\n",
            id, funcname);
    return(1); }

  /* Check if flag < 0 */
  else if (opt == 1) {
    errflag = (int *) flagvalue;
    if (*errflag < 0) {
      fprintf(stderr, "\nSUNDIALS_ERROR(%d): %s() failed with flag = %d\n\n",
              id, funcname, *errflag);
      return(1); }}

  /* Check if function returned NULL pointer - no memory allocated */
  else if (opt == 2 && flagvalue == NULL) {
    fprintf(stderr, "\nMEMORY_ERROR(%d): %s() failed - returned NULL pointer\n\n",
            id, funcname);
    return(1); }

  return(0);
}


text: SELECT * FROM table WHERE foo='bar' AND baz='nothing to see here

redpajama_set_name: RedPajamaGithub


text:
<TITLE>Review for Basket, The (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

Basket, The (1999)

reviewed by
Steve Rhodes

THE BASKET
A film review by Steve Rhodes
Copyright 2000 Steve Rhodes
RATING (0 TO ****):  ***

Opera, basketball and prejudice: an unlikely combination for any film,
especially for one set in small town America towards the end of World
War I.

Rich Cowan's THE BASKET is a simple and poetic film whose magic comes
from many sources, particularly two beautifully understated performances
by Peter Coyote and Karen Allen.  The director makes the bold assumption
that the audience has both intelligence and patience.  In a film filled
with messages -- "To defend a mighty wall, each one must fight for
something small," the opera says -- most are delivered with quiet
delicacy, leaving the viewers to ascertain the fullness of their
meanings and their portent for the story at hand.

Two teenage, German war orphans, Helmut and his sister Brigitta, played
with touching resoluteness by Robert Karl Burke and Amber Willenborg,
are taken from their internment camp to live in Waterville, Washington
with Reverend Simms, M.D. (Tony Lincoln).  Waterville is so small that
Rev. Simms is in charge of both birthing and baptizing.  Although their
parents were killed by Americans, the orphans carry little resentment;
they're just thankful to be alive.  But it's not easy since the members
of the town carry varying amounts of prejudice against them.  "I thought
the war for us had finally ended, but it hadn't," Helmut explains in
voice-over.  "Only the battlefield had changed,"

The one most against the orphans is Mr. Emery (Jock MacDonald), whose
oldest son, Ben (Elwon Bakly), has just returned home from the war.
Having lost his good health and his left leg, Ben has been transformed
from his father's chief helper into "just another mouth to feed."
Unlike her headstrong husband, Mrs. Emery (Karen Allen) wants to pick up
the pieces of their lives and get on with it.

Another outsider in Waterville is Mr. Conlon (Peter Coyote), the new
teacher for the town's one-room school.  With a Bostonian accent as
thick as Helmut's German one, Mr. Conlon sticks out like a peach basket
nailed up to a wall.  He once played under the man who invented
basketball and that's how it was played back then.  Things having not
advanced much, that's exactly how the teacher introduces the game to his
pupils, who had barely heard of the sport.

Meanwhile, back in the schoolroom (he sleeps in its small anteroom), Mr.
Conlon teaches the class a continuing lesson with the aid of a German
opera ("The Basket").  This creates a buzz of excitement in the village
because he dribbles out the story like episodes of a soap opera.  The
whole town becomes enthralled with the latest happenings in the story,
as if they were the latest installments of "Dallas."  His choice of a
"German" opera, even with its popularity, causes great consternation to
some residents.

The goings-on at the school have ramifications throughout the town.  In
a delicately nuanced performance, Karen Allen's Mrs. Emery finds the
teacher fascinating because he represents life away from the farm.
"Boston -- I always wanted to visit Boston," she sighs when Mr. Conlon
tells her of his home.  "Or any place for that matter."

Helmut, a source of derision among his fellow students for being German,
is also the shortest of those near his age.  This means that he isn't
allowed in the basketball games that the older and much taller boys try
without much skill or luck.  Nevertheless, using laundry and a laundry
basket, or whatever he can find, Helmut practices in the hope that the
day will come when he can join in the game.

The seemingly disparate stories of opera and basketball come together
when the town needs the down payment for a harvester.  If they can
defeat the undefeatable Spokane Spartans, they can win enough to get the
down payment.

Filmed frequently with the warm glow of the setting sun, the rolling
pastures of Washington state look invitingly bucolic.  This little
filmed area of the United States clearly deserves to have more movies
set there.

Although the journey is the reward in this movie, its big game ending
manages more surprises than you'd ever expect, one being the half-time
refreshments of the other team: beer and big cigars.  And the rules back
then were quite a bit different than they are now.  Even the game's
slower pacing, which matches that of the movie, possesses an undeniable
charm.

A heartfelt motion picture, THE BASKET is a delightful film worth
savoring for those willing to take the time to enjoy its methodical
rhythms.  It's a film that gives family entertainment a good name and
one that will have you still enjoying it in your memory after you leave
the theater.

THE BASKET runs 1:45.  It is rated PG for some mild violence and brief
language and would be fine for all ages.  Children with short attention
spans, however, are unlikely to find it worthwhile.

Email: Steve.Rhodes@InternetReviews.com
Web: http://www.InternetReviews.com

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], '../../')))
sys.path.insert(0, os.path.abspath(os.path.join(os.path.split(__file__)[0], '..')))

args = ['CMi/manage.py', 'runserver', '0.0.0.0:19817', '--noreload']

if __name__ == "__main__":
    sys.stderr = sys.stdout
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CMi.settings")

    from CMi import migrate
    migrate()

    from django.core.management import execute_from_command_line

    execute_from_command_line(args)


text:
package de.stefanhoth.android.got2048.fragments;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.TextView;
import android.widget.Toast;

import com.deploygate.sdk.DeployGate;

import java.util.Random;

import butterknife.ButterKnife;
import butterknife.InjectView;
import de.stefanhoth.android.got2048.GameEngineService;
import de.stefanhoth.android.got2048.R;
import de.stefanhoth.android.got2048.helpers.SettingsHelper;
import de.stefanhoth.android.got2048.logic.MCP;
import de.stefanhoth.android.got2048.logic.model.MOVE_DIRECTION;
import de.stefanhoth.android.got2048.logic.model.MovementChanges;
import de.stefanhoth.android.got2048.widgets.SquareGridView;

/**
 * A simple {@link android.support.v4.app.Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link de.stefanhoth.android.got2048.fragments.PlayingFieldFragment.OnPlayingFieldEventListener} interface
 * to handle interaction events.
 * Use the {@link PlayingFieldFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PlayingFieldFragment extends Fragment {

    private static final String KEY_HIGHSCORE = "KEY_HIGHSCORE";
    private static final String TAG = PlayingFieldFragment.class.getName();
    private static final String PREF_USER_LEARNED_SWIPE = "PREF_USER_LEARNED_SWIPE";

    private int mCurrentScore;
    private int mHighscore;

    @InjectView(R.id.playing_field)
    SquareGridView mSquareGridView;

    @InjectView(R.id.game_status)
    TextView mGameStatus;

    @InjectView(R.id.txt_score_current)
    TextView mTvCurrentScore;

    @InjectView(R.id.txt_score_best)
    TextView mTvHighscore;

    private OnPlayingFieldEventListener mPlayingFieldEventListener;
    private GestureDetector mGestureDetector;
    private View.OnTouchListener mGestureListener;
    private McpEventReceiver mMcpEventReceiver;
    private boolean mReadyAnnounced;
    private boolean mUserLearnedSwipe;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param lastHighscore The last mHighscore of the player
     * @return A new instance of fragment PlayingFieldFragment.
     */
    public static PlayingFieldFragment newInstance(int lastHighscore) {
        PlayingFieldFragment fragment = new PlayingFieldFragment();
        Bundle args = new Bundle();
        args.putInt(KEY_HIGHSCORE, lastHighscore);
        fragment.setArguments(args);
        return fragment;
    }

    public PlayingFieldFragment() {
        // Required empty public constructor
        super();
        mHighscore = 0;
        mCurrentScore = 0;
        mReadyAnnounced = false;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);

        if (getArguments() != null) {
            mHighscore = getArguments().getInt(KEY_HIGHSCORE);
        }

        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_SWIPE for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedSwipe = sp.getBoolean(PREF_USER_LEARNED_SWIPE, false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_playing_field, container, false);
        ButterKnife.inject(this, view);

        if (mHighscore > 0) {
            mTvHighscore.setText(String.valueOf(mHighscore));
        } else {
            mTvHighscore.setText("-");
        }
        mTvCurrentScore.setText(String.valueOf(mCurrentScore));

        // Gesture detection
        mGestureDetector = new GestureDetector(container.getContext(), new MyGestureDetector(getActivity()));
        mGestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {

                ViewGroup vg = (ViewGroup) v;
                vg.requestDisallowInterceptTouchEvent(true);

                if (mGestureDetector.onTouchEvent(event)) {
                    return true;
                }

                if (event.getAction() == MotionEvent.ACTION_UP) {

//                    if (mIsScrolling) {
//                        mIsScrolling = false;
//                        handleScrollFinished();
//                        return true;
//                    }
                }

                return false;
            }
        };

        mSquareGridView.setOnTouchListener(mGestureListener);

        setHasOptionsMenu(true);

        return view;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mPlayingFieldEventListener = (OnPlayingFieldEventListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnPlayingFieldEventListener");
        }

        mMcpEventReceiver = new McpEventReceiver();
        IntentFilter mStatusIntentFilter = new IntentFilter();
        mStatusIntentFilter.addAction(MCP.BROADCAST_ACTION_MOVE_START);
        mStatusIntentFilter.addAction(MCP.BROADCAST_ACTION_MOVE_DONE);
        mStatusIntentFilter.addAction(MCP.BROADCAST_ACTION_GAME_WON);
        mStatusIntentFilter.addAction(MCP.BROADCAST_ACTION_GAME_OVER);

        LocalBroadcastManager
                .getInstance(getActivity().getBaseContext())
                .registerReceiver(
                        mMcpEventReceiver,
                        mStatusIntentFilter
                );

        Log.d(TAG, "onAttach: View is ready for playing.");
    }

    @Override
    public void onStart() {
        super.onStart();
        announceReady();
    }

    @Override
    public void onDetach() {
        super.onDetach();

        if (mMcpEventReceiver != null && getActivity() != null && getActivity().getBaseContext() != null) {
            LocalBroadcastManager.getInstance(getActivity().getBaseContext()).unregisterReceiver(mMcpEventReceiver);
            mMcpEventReceiver = null;
        }
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     */
    public interface OnPlayingFieldEventListener {
        public void onMovementRecognized(MOVE_DIRECTION direction);
        public void onPlayingFieldReady();
        public void onGameOver(int score, int bestScore, boolean won);
    }

    class MyGestureDetector extends GestureDetector.SimpleOnGestureListener {

        private static final int SWIPE_MIN_DISTANCE = 80;
        private static final int SWIPE_MAX_OFF_PATH = 100;
        private static final int SWIPE_THRESHOLD_VELOCITY = 150;

        Activity mActivity;

        public MyGestureDetector(Activity act) {
            this.mActivity = act;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
            mActivity.finish();
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
//        if (Math.abs(e1.getX() - e2.getX()) > SWIPE_MAX_OFF_PATH) {
//            return false;
//        }

            if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                //move up
                announceMovement(MOVE_DIRECTION.UP);
            } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                //move down
                announceMovement(MOVE_DIRECTION.DOWN);
            } else if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                //move left
                announceMovement(MOVE_DIRECTION.LEFT);
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                //move right
                announceMovement(MOVE_DIRECTION.RIGHT);
            }

            mUserLearnedSwipe = true;
            SharedPreferences sp = PreferenceManager
                    .getDefaultSharedPreferences(getActivity());
            sp.edit().putBoolean(PREF_USER_LEARNED_SWIPE, mUserLearnedSwipe).apply();

            return true;
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        /*int id = item.getItemId();
        Log.d(TAG, "onOptionsItemSelected: id=" + id);

        if (id == R.id.action_restart) {
            handleRestartAction();
            return true;
        } else if (id == R.id.action_random) {
            Toast.makeText(getActivity().getBaseContext(), "Making a move…", Toast.LENGTH_SHORT).show();
            announceMovement(MOVE_DIRECTION.values()[new Random().nextInt(MOVE_DIRECTION.values().length)]);
            return true;
        }
        */
        return super.onOptionsItemSelected(item);
    }

    private void handleRestartAction() {

        new AlertDialog.Builder(getActivity())
                .setTitle(R.string.action_restart)
                .setMessage(R.string.dialog_restart_question)
                .setPositiveButton(R.string.dialog_restart_yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        GameEngineService.startActionRestartGame(getActivity().getBaseContext());
                    }
                })
                .setNegativeButton(R.string.dialog_restart_no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create()
                .show();
    }

    private void announceReady() {

        if (mReadyAnnounced) {
            return;
        }

        if (mPlayingFieldEventListener != null) {
            mPlayingFieldEventListener.onPlayingFieldReady();
        }

        mReadyAnnounced = true;

        teachSwipeMovement();

        Toast.makeText(getActivity(), R.string.long_press_to_exit, Toast.LENGTH_LONG).show();
    }

    private void teachSwipeMovement() {
        if (mUserLearnedSwipe) {
            return;
        }

        float translateBy = 50f;
        int startDelay = 1000;
        int duration = 300;

        ObjectAnimator animXRight = ObjectAnimator.ofFloat(mSquareGridView, "translationX", translateBy);
        ObjectAnimator animXLeft = ObjectAnimator.ofFloat(mSquareGridView, "translationX", -translateBy);
        ObjectAnimator animXReset = ObjectAnimator.ofFloat(mSquareGridView, "translationX", 0);
        ObjectAnimator animYUp = ObjectAnimator.ofFloat(mSquareGridView, "translationY", -translateBy);
        ObjectAnimator animYDown = ObjectAnimator.ofFloat(mSquareGridView, "translationY", translateBy);
        ObjectAnimator animYReset = ObjectAnimator.ofFloat(mSquareGridView, "translationY", 0);

        AnimatorSet bouncer = new AnimatorSet();
        bouncer.playSequentially(animXRight, animXLeft, animXReset, animYUp, animYDown, animYReset);

        bouncer.setStartDelay(startDelay);
        bouncer.setDuration(duration);
        bouncer.setInterpolator(new AccelerateDecelerateInterpolator());
        bouncer.start();
    }

    private void announceMovement(MOVE_DIRECTION direction) {

        if (mPlayingFieldEventListener != null) {
            mPlayingFieldEventListener.onMovementRecognized(direction);
        }

        String property;
        float movement = 50f;

        switch (direction) {

            case UP:
                property = "translationY";
                movement = -movement;
                break;
            case DOWN:
                property = "translationY";
                break;
            case LEFT:
                property = "translationX";
                movement = -movement;
                break;
            case RIGHT:
                property = "translationX";
                break;
            default:
                return;
        }

        ObjectAnimator animOut = ObjectAnimator.ofFloat(mSquareGridView, property, movement);
        ObjectAnimator animIn = ObjectAnimator.ofFloat(mSquareGridView, property, 0);

        AnimatorSet bouncer = new AnimatorSet();
        bouncer.playSequentially(animOut, animIn);
        bouncer.setDuration(200);
        bouncer.setInterpolator(new AccelerateDecelerateInterpolator());
        bouncer.start();

    }

    private void checkHighscore() {

        if (mCurrentScore > mHighscore) {
            //TODO do something visually fancy
            Toast.makeText(getActivity().getBaseContext(), "NEW HIGHSCORE!", Toast.LENGTH_SHORT).show();
            mHighscore = mCurrentScore;

            if (!SettingsHelper.storeSettings(getActivity().getBaseContext(), mCurrentScore)) {
                Log.e(TAG, "checkHighscore: Could not persist highscore into shared prefs.");
                return;
            }
        }
    }

    // Broadcast receiver for receiving status updates from the IntentService
    private class McpEventReceiver extends BroadcastReceiver {

        private final String TAG = McpEventReceiver.class.getName();

        // Prevents instantiation
        private McpEventReceiver() {
        }

        // Called when the BroadcastReceiver gets an Intent it's registered to receive
        public void onReceive(Context context, Intent intent) {

            if (intent == null || intent.getAction() == null || intent.getAction().isEmpty()) {
                Log.d(TAG, "Invalid intent received. Null or no action named.");
                return;
            }

            String action = intent.getAction();

            if (action.equalsIgnoreCase(MCP.BROADCAST_ACTION_MOVE_START)) {
                handleMoveStart(intent);
            } else if (action.equalsIgnoreCase(MCP.BROADCAST_ACTION_MOVE_DONE)) {
                handleMoveDone(intent);
            } else if (action.equalsIgnoreCase(MCP.BROADCAST_ACTION_GAME_OVER)) {
                handleGameOver(intent);
            } else if (action.equalsIgnoreCase(MCP.BROADCAST_ACTION_GAME_WON)) {
                handleGameWon(intent);
            } else {
                Log.e(TAG, "Unrecognized action received=" + action);
            }
        }

        private void handleMoveStart(Intent intent) {

            try {
                MOVE_DIRECTION direction = MOVE_DIRECTION.values()[intent.getIntExtra(MCP.KEY_DIRECTION, 0)];
                //Toast.makeText(getActivity().getBaseContext(), "Movement to "+direction+" received.", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Log.e(TAG, "Could not read movements from broadcast.", e);
            }
        }

        private void handleMoveDone(Intent intent) {
            try {

                MovementChanges changes = intent.getParcelableExtra(MCP.KEY_MOVEMENT_CHANGES);

                mSquareGridView.updateGrid(changes.gridStatus);
                mSquareGridView.addCells(changes.getAddedCells(), changes.addedCellsValue);

                if (changes.isRestart()) {
                    mCurrentScore = 0;
                    mGameStatus.setText("");
                } else {
                    mCurrentScore += changes.pointsEarned;
                }
                //TODO animate new points
                mTvCurrentScore.setText(String.valueOf(mCurrentScore));

            } catch (Exception e) {
                Log.e(TAG, "Could not read movements from broadcast.", e);
            }
        }

        private void handleGameOver(Intent intent) {

            checkHighscore();

            if(mPlayingFieldEventListener != null)
                mPlayingFieldEventListener.onGameOver(mCurrentScore, mHighscore, false);
        }

        private void handleGameWon(Intent intent) {

            checkHighscore();

            if(mPlayingFieldEventListener != null)
                mPlayingFieldEventListener.onGameOver(mCurrentScore, mHighscore, true);
        }
    }
}


text:
TOP_LEVEL_NAME="fp_div"
QSYS_SIMDIR="./../"
QUARTUS_INSTALL_DIR="/opt/Quartus_17/quartus/"
SKIP_FILE_COPY=0
SKIP_DEV_COM=0
SKIP_COM=0
SKIP_ELAB=0
SKIP_SIM=0
USER_DEFINED_ELAB_OPTIONS=""
USER_DEFINED_SIM_OPTIONS="-input \"@run 100; exit\""

# ----------------------------------------
# overwrite variables - DO NOT MODIFY!
# This block evaluates each command line argument, typically used for
# overwriting variables. An example usage:
#   sh <simulator>_setup.sh SKIP_SIM=1
for expression in "$@"; do
  eval $expression
  if [ $? -ne 0 ]; then
    echo "Error: This command line argument, \"$expression\", is/has an invalid expression." >&2
    exit $?
  fi
done

# ----------------------------------------
# initialize simulation properties - DO NOT MODIFY!
ELAB_OPTIONS=""
SIM_OPTIONS=""
if [[ `ncsim -version` != *"ncsim(64)"* ]]; then
  :
else
  :
fi

# ----------------------------------------
# create compilation libraries
mkdir -p ./libraries/work/
mkdir -p ./libraries/altera/
mkdir -p ./libraries/lpm/
mkdir -p ./libraries/sgate/
mkdir -p ./libraries/altera_mf/
mkdir -p ./libraries/altera_lnsim/
mkdir -p ./libraries/fiftyfivenm/

# ----------------------------------------
# copy RAM/ROM files to simulation directory
if [ $SKIP_FILE_COPY -eq 0 ]; then
  cp -f $QSYS_SIMDIR/fp_div_memoryC0_uid113_invTables_lutmem.hex ./
  cp -f $QSYS_SIMDIR/fp_div_memoryC1_uid116_invTables_lutmem.hex ./
  cp -f $QSYS_SIMDIR/fp_div_memoryC2_uid120_invTables_lutmem.hex ./
  cp -f $QSYS_SIMDIR/fp_div_memoryC1_uid117_invTables_lutmem.hex ./
  cp -f $QSYS_SIMDIR/fp_div_memoryC0_uid112_invTables_lutmem.hex ./
fi

# ----------------------------------------
# compile device library files
if [ $SKIP_DEV_COM -eq 0 ]; then
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_syn_attributes.vhd"          -work altera
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_standard_functions.vhd"      -work altera
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/alt_dspbuilder_package.vhd"         -work altera
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_europa_support_lib.vhd"      -work altera
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_primitives_components.vhd"   -work altera
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_primitives.vhd"              -work altera
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/220pack.vhd"                        -work lpm
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/220model.vhd"                       -work lpm
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/sgate_pack.vhd"                     -work sgate
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/sgate.vhd"                          -work sgate
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_mf_components.vhd"           -work altera_mf
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_mf.vhd"                      -work altera_mf
  ncvlog -sv $USER_DEFINED_COMPILE_OPTIONS  "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_lnsim.sv"                    -work altera_lnsim
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/altera_lnsim_components.vhd"        -work altera_lnsim
  ncvlog $USER_DEFINED_COMPILE_OPTIONS      "$QUARTUS_INSTALL_DIR/eda/sim_lib/cadence/fiftyfivenm_atoms_ncrypt.v" -work fiftyfivenm
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/fiftyfivenm_atoms.vhd"              -work fiftyfivenm
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QUARTUS_INSTALL_DIR/eda/sim_lib/fiftyfivenm_components.vhd"         -work fiftyfivenm
fi

# ----------------------------------------
# compile design files in correct order
if [ $SKIP_COM -eq 0 ]; then
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QSYS_SIMDIR/dspba_library_package.vhd"
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QSYS_SIMDIR/dspba_library.vhd"
  ncvhdl -v93 $USER_DEFINED_COMPILE_OPTIONS "$QSYS_SIMDIR/fp_div.vhd"
fi

# ----------------------------------------
# elaborate top level design
if [ $SKIP_ELAB -eq 0 ]; then
  export GENERIC_PARAM_COMPAT_CHECK=1
  ncelab -access +w+r+c -namemap_mixgen -relax $ELAB_OPTIONS $USER_DEFINED_ELAB_OPTIONS $TOP_LEVEL_NAME
fi

# ----------------------------------------
# simulate
if [ $SKIP_SIM -eq 0 ]; then
  eval ncsim -licqueue $SIM_OPTIONS $USER_DEFINED_SIM_OPTIONS $TOP_LEVEL_NAME
fi


text:
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt

#include <linux/bitops.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/device.h>
#include <linux/err.h>
#include <linux/fs.h>
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/notifier.h>
#include <linux/of.h>
#include <linux/pm.h>
#include <linux/platform_device.h>
#include <linux/reboot.h>
#include <linux/timer.h>
#include <linux/uaccess.h>
#include <linux/watchdog.h>

#define WDOG_CONTROL_REG_OFFSET		    0x00
#define WDOG_CONTROL_REG_WDT_EN_MASK	    0x01
#define WDOG_TIMEOUT_RANGE_REG_OFFSET	    0x04
#define WDOG_TIMEOUT_RANGE_TOPINIT_SHIFT    4
#define WDOG_CURRENT_COUNT_REG_OFFSET	    0x08
#define WDOG_COUNTER_RESTART_REG_OFFSET     0x0c
#define WDOG_COUNTER_RESTART_KICK_VALUE	    0x76

/* The maximum TOP (timeout period) value that can be set in the watchdog. */
#define DW_WDT_MAX_TOP		15

#define DW_WDT_DEFAULT_SECONDS	30

static bool nowayout = WATCHDOG_NOWAYOUT;
module_param(nowayout, bool, 0);
MODULE_PARM_DESC(nowayout, "Watchdog cannot be stopped once started "
		 "(default=" __MODULE_STRING(WATCHDOG_NOWAYOUT) ")");

#define WDT_TIMEOUT		(HZ / 2)

static struct {
	void __iomem		*regs;
	struct clk		*clk;
	unsigned long		in_use;
	unsigned long		next_heartbeat;
	struct timer_list	timer;
	int			expect_close;
	struct notifier_block	restart_handler;
} dw_wdt;

static inline int dw_wdt_is_enabled(void)
{
	return readl(dw_wdt.regs + WDOG_CONTROL_REG_OFFSET) &
		WDOG_CONTROL_REG_WDT_EN_MASK;
}

static inline int dw_wdt_top_in_seconds(unsigned top)
{
	/*
	 * There are 16 possible timeout values in 0..15 where the number of
	 * cycles is 2 ^ (16 + i) and the watchdog counts down.
	 */
	return (1U << (16 + top)) / clk_get_rate(dw_wdt.clk);
}

static int dw_wdt_get_top(void)
{
	int top = readl(dw_wdt.regs + WDOG_TIMEOUT_RANGE_REG_OFFSET) & 0xF;

	return dw_wdt_top_in_seconds(top);
}

static inline void dw_wdt_set_next_heartbeat(void)
{
	dw_wdt.next_heartbeat = jiffies + dw_wdt_get_top() * HZ;
}

static void dw_wdt_keepalive(void)
{
	writel(WDOG_COUNTER_RESTART_KICK_VALUE, dw_wdt.regs +
	       WDOG_COUNTER_RESTART_REG_OFFSET);
}

static int dw_wdt_set_top(unsigned top_s)
{
	int i, top_val = DW_WDT_MAX_TOP;

	/*
	 * Iterate over the timeout values until we find the closest match. We
	 * always look for >=.
	 */
	for (i = 0; i <= DW_WDT_MAX_TOP; ++i)
		if (dw_wdt_top_in_seconds(i) >= top_s) {
			top_val = i;
			break;
		}

	/*
	 * Set the new value in the watchdog.  Some versions of dw_wdt
	 * have have TOPINIT in the TIMEOUT_RANGE register (as per
	 * CP_WDT_DUAL_TOP in WDT_COMP_PARAMS_1).  On those we
	 * effectively get a pat of the watchdog right here.
	 */
	writel(top_val | top_val << WDOG_TIMEOUT_RANGE_TOPINIT_SHIFT,
		dw_wdt.regs + WDOG_TIMEOUT_RANGE_REG_OFFSET);

	/*
	 * Add an explicit pat to handle versions of the watchdog that
	 * don't have TOPINIT.  This won't hurt on versions that have
	 * it.
	 */
	dw_wdt_keepalive();

	dw_wdt_set_next_heartbeat();

	return dw_wdt_top_in_seconds(top_val);
}

static int dw_wdt_restart_handle(struct notifier_block *this,
				unsigned long mode, void *cmd)
{
	u32 val;

	writel(0, dw_wdt.regs + WDOG_TIMEOUT_RANGE_REG_OFFSET);
	val = readl(dw_wdt.regs + WDOG_CONTROL_REG_OFFSET);
	if (val & WDOG_CONTROL_REG_WDT_EN_MASK)
		writel(WDOG_COUNTER_RESTART_KICK_VALUE, dw_wdt.regs +
			WDOG_COUNTER_RESTART_REG_OFFSET);
	else
		writel(WDOG_CONTROL_REG_WDT_EN_MASK,
		       dw_wdt.regs + WDOG_CONTROL_REG_OFFSET);

	/* wait for reset to assert... */
	mdelay(500);

	return NOTIFY_DONE;
}

static void dw_wdt_ping(unsigned long data)
{
	if (time_before(jiffies, dw_wdt.next_heartbeat) ||
	    (!nowayout && !dw_wdt.in_use)) {
		dw_wdt_keepalive();
		mod_timer(&dw_wdt.timer, jiffies + WDT_TIMEOUT);
	} else
		pr_crit("keepalive missed, machine will reset\n");
}

static int dw_wdt_open(struct inode *inode, struct file *filp)
{
	if (test_and_set_bit(0, &dw_wdt.in_use))
		return -EBUSY;

	/* Make sure we don't get unloaded. */
	__module_get(THIS_MODULE);

	if (!dw_wdt_is_enabled()) {
		/*
		 * The watchdog is not currently enabled. Set the timeout to
		 * something reasonable and then start it.
		 */
		dw_wdt_set_top(DW_WDT_DEFAULT_SECONDS);
		writel(WDOG_CONTROL_REG_WDT_EN_MASK,
		       dw_wdt.regs + WDOG_CONTROL_REG_OFFSET);
	}

	dw_wdt_set_next_heartbeat();

	return nonseekable_open(inode, filp);
}

static ssize_t dw_wdt_write(struct file *filp, const char __user *buf,
			    size_t len, loff_t *offset)
{
	if (!len)
		return 0;

	if (!nowayout) {
		size_t i;

		dw_wdt.expect_close = 0;

		for (i = 0; i < len; ++i) {
			char c;

			if (get_user(c, buf + i))
				return -EFAULT;

			if (c == 'V') {
				dw_wdt.expect_close = 1;
				break;
			}
		}
	}

	dw_wdt_set_next_heartbeat();
	dw_wdt_keepalive();
	mod_timer(&dw_wdt.timer, jiffies + WDT_TIMEOUT);

	return len;
}

static u32 dw_wdt_time_left(void)
{
	return readl(dw_wdt.regs + WDOG_CURRENT_COUNT_REG_OFFSET) /
		clk_get_rate(dw_wdt.clk);
}

static const struct watchdog_info dw_wdt_ident = {
	.options	= WDIOF_KEEPALIVEPING | WDIOF_SETTIMEOUT |
			  WDIOF_MAGICCLOSE,
	.identity	= "Synopsys DesignWare Watchdog",
};

static long dw_wdt_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
	unsigned long val;
	int timeout;

	switch (cmd) {
	case WDIOC_GETSUPPORT:
		return copy_to_user((void __user *)arg, &dw_wdt_ident,
				    sizeof(dw_wdt_ident)) ? -EFAULT : 0;

	case WDIOC_GETSTATUS:
	case WDIOC_GETBOOTSTATUS:
		return put_user(0, (int __user *)arg);

	case WDIOC_KEEPALIVE:
		dw_wdt_set_next_heartbeat();
		return 0;

	case WDIOC_SETTIMEOUT:
		if (get_user(val, (int __user *)arg))
			return -EFAULT;
		timeout = dw_wdt_set_top(val);
		return put_user(timeout , (int __user *)arg);

	case WDIOC_GETTIMEOUT:
		return put_user(dw_wdt_get_top(), (int __user *)arg);

	case WDIOC_GETTIMELEFT:
		/* Get the time left until expiry. */
		if (get_user(val, (int __user *)arg))
			return -EFAULT;
		return put_user(dw_wdt_time_left(), (int __user *)arg);

	default:
		return -ENOTTY;
	}
}

static int dw_wdt_release(struct inode *inode, struct file *filp)
{
	clear_bit(0, &dw_wdt.in_use);

	if (!dw_wdt.expect_close) {
		del_timer(&dw_wdt.timer);

		if (!nowayout)
			pr_crit("unexpected close, system will reboot soon\n");
		else
			pr_crit("watchdog cannot be disabled, system will reboot soon\n");
	}

	dw_wdt.expect_close = 0;

	return 0;
}

#ifdef CONFIG_PM_SLEEP
static int dw_wdt_suspend(struct device *dev)
{
	clk_disable_unprepare(dw_wdt.clk);

	return 0;
}

static int dw_wdt_resume(struct device *dev)
{
	int err = clk_prepare_enable(dw_wdt.clk);

	if (err)
		return err;

	dw_wdt_keepalive();

	return 0;
}
#endif /* CONFIG_PM_SLEEP */

static SIMPLE_DEV_PM_OPS(dw_wdt_pm_ops, dw_wdt_suspend, dw_wdt_resume);

static const struct file_operations wdt_fops = {
	.owner		= THIS_MODULE,
	.llseek		= no_llseek,
	.open		= dw_wdt_open,
	.write		= dw_wdt_write,
	.unlocked_ioctl	= dw_wdt_ioctl,
	.release	= dw_wdt_release
};

static struct miscdevice dw_wdt_miscdev = {
	.fops		= &wdt_fops,
	.name		= "watchdog",
	.minor		= WATCHDOG_MINOR,
};

static int dw_wdt_drv_probe(struct platform_device *pdev)
{
	int ret;
	struct resource *mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);

	dw_wdt.regs = devm_ioremap_resource(&pdev->dev, mem);
	if (IS_ERR(dw_wdt.regs))
		return PTR_ERR(dw_wdt.regs);

	dw_wdt.clk = devm_clk_get(&pdev->dev, NULL);
	if (IS_ERR(dw_wdt.clk))
		return PTR_ERR(dw_wdt.clk);

	ret = clk_prepare_enable(dw_wdt.clk);
	if (ret)
		return ret;

	ret = misc_register(&dw_wdt_miscdev);
	if (ret)
		goto out_disable_clk;

	dw_wdt.restart_handler.notifier_call = dw_wdt_restart_handle;
	dw_wdt.restart_handler.priority = 128;
	ret = register_restart_handler(&dw_wdt.restart_handler);
	if (ret)
		pr_warn("cannot register restart handler\n");

	dw_wdt_set_next_heartbeat();
	setup_timer(&dw_wdt.timer, dw_wdt_ping, 0);
	mod_timer(&dw_wdt.timer, jiffies + WDT_TIMEOUT);

	return 0;

out_disable_clk:
	clk_disable_unprepare(dw_wdt.clk);

	return ret;
}

static int dw_wdt_drv_remove(struct platform_device *pdev)
{
	unregister_restart_handler(&dw_wdt.restart_handler);

	misc_deregister(&dw_wdt_miscdev);

	clk_disable_unprepare(dw_wdt.clk);

	return 0;
}

#ifdef CONFIG_OF
static const struct of_device_id dw_wdt_of_match[] = {
	{ .compatible = "snps,dw-wdt", },
	{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, dw_wdt_of_match);
#endif

static struct platform_driver dw_wdt_driver = {
	.probe		= dw_wdt_drv_probe,
	.remove		= dw_wdt_drv_remove,
	.driver		= {
		.name	= "dw_wdt",
		.of_match_table = of_match_ptr(dw_wdt_of_match),
		.pm	= &dw_wdt_pm_ops,
	},
};

module_platform_driver(dw_wdt_driver);

MODULE_AUTHOR("Jamie Iles");
MODULE_DESCRIPTION("Synopsys DesignWare Watchdog Driver");
MODULE_LICENSE("GPL");


text:
typedef void (^AsyncTaskBlock)();

@class ASIHTTPRequest;
@class ApiError;

@interface AsyncTask : NSObject
@property(nonatomic,strong) ASIHTTPRequest* request;
@property(nonatomic,strong) id<CheckOperatorDelegate> checkOperator;
@property(nonatomic,strong) id<ParserDelegate> parser;
@property (copy, nonatomic) AsyncTaskBlock finishBlock;

-(void)cancel;

-(void)start;

-(id)result;

-(int)statusCode;

-(NSString*)errorMessage;

-(NSData*)responseData;

@end


text:
from Bio import SeqIO
import numpy as np
from mutation_creator import Mutation_Creator
from mutation_tracker import Mutation_Tracker
import logging
from probabilities_config import structural_variations_probabilities, snv_probabilities

class Mutation_Orchestrator:
    """ Mutation_Orchestrator is a class that operates on a genome to make a mutation.
        It chooses the type, length, and start of the mutation probabilistically, using
        the probabilities defined in probabilities_config. It stores a record of the mutations
        in the Mutation_Tracker class, and modifies the genome string using Mutation_Creator"""
    def __init__(self):
        self.tracker = Mutation_Tracker()
        self.creator = Mutation_Creator()
        self.structural_variations = {
        'deletion': self.orchestrate_deletion,
        'translocation': self.orchestrate_translocation,
        'duplication' : self.orchestrate_duplication,
        'inversion' : self.orchestrate_inversion,
        'insertion' : self.orchestrate_insertion
        }

        self.logger = logging.basicConfig(filename='example.log',level=logging.DEBUG)

    def snv_fast(self, genome, number):
        chroms = self.pick_chromosomes(genome, number)
        ### assume for normal bases
        new_bases = np.random.choice(list(snv_probabilities.keys()), number, snv_probabilities.values())
        for i in range(number):
            start = self.get_location_on_sequence(genome[chroms[i]])
            genome[chroms[i]] = self.creator.create_snv(genome[chroms[i]], start, new_bases[i])
            logging.info('Added base {} at position {} in chrom {}'.format(new_bases[i], str(start), chroms[i]))
        return genome

    def pick_chromosomes(self, genome, number=1, replace=True):
        relative_lengths = np.array([len(genome[x]) for x in genome])
        probabilities = relative_lengths / float(relative_lengths.sum())
        chroms = np.random.choice(list(genome.keys()), number, replace=replace ,p=probabilities.tolist())
        return chroms

    def get_location_on_sequence(self, seq, distribution='uniform'):
        if distribution == 'uniform':
            # Don't select a location with a N
            while True:
                location = np.random.randint(len(seq))
                if seq[location] != 'N':
                    return location
        else:
            raise NotImplementedError("Only Uniform is implemented!")

    # Default to being a big deletion, but p=0.6 makes it a small deletion
    def orchestrate_deletion(self, genome, distribution='uniform', p=0.001):
        chrom = self.pick_chromosomes(genome)[0]
        start = self.get_location_on_sequence(genome[chrom])
        end = self.get_end_of_event(start, genome[chrom], p)
        self.tracker.create_deletion(chrom, start, end)
        logging.info('Orchestrated deletion from {} to {} in chrom {}'.format(start, end, chrom))

    def orchestrate_translocation(self, genome, distribution='uniform'):
        if len(genome) == 1:
            print('No translocations allowed: genome too small')
            return
        (chrom_source, chrom_target) = self.pick_chromosomes(genome, number = 2, replace = False)
        start_source = self.get_location_on_sequence(genome[chrom_source])
        start_target = self.get_location_on_sequence(genome[chrom_target])
        end_source = self.get_end_of_event(start_source, genome[chrom_source], p=0.001)
        end_target = self.get_end_of_event(start_target, genome[chrom_target], p=0.001)
        new_seq_source = genome[chrom_target][start_target:end_target]
        new_seq_target = genome[chrom_source][start_source:end_source]
        self.tracker.create_translocation(chrom_source, chrom_target, start_source,
                        start_target, end_source, end_target, new_seq_source, new_seq_target)
        logging.info('Orchestrated translocation at position {} to position {} on chrom {} at position {} to position {} on chrom {}'.format(
            start_source, end_source, chrom_source, start_target, end_target, chrom_target))

    # Guarantees the end of the event isn't outside the sequence
    def get_end_of_event(self, start_pos, seq, p):
        length = self.get_event_length(p)
        return np.min([start_pos + length, len(seq)])

    # Models exponential decay, discretely
    # Expected value of event is 1/p
    def get_event_length(self, p=0.6, number = 1):
        z = np.random.geometric(p, size=number)
        return z[0]

    # Duplication currently only goes one direction (forward)
    # Creates a variable amount of duplications (num_duplications, drawn from geometric dist)
    def orchestrate_duplication(self, genome, distribution='uniform'):
        chrom = self.pick_chromosomes(genome, number = 1)[0]
        start = self.get_location_on_sequence(genome[chrom])
        end = self.get_end_of_event(start, genome[chrom], p=0.001)
        num_duplications = self.get_event_length(p=0.6) # exponential ranging from 1 to 10
        new_seq = str(genome[chrom][start:end]) * num_duplications
        self.tracker.create_insertion(chrom, start, new_seq,
             name='duplication (times {})'.format(num_duplications))
        logging.info('Orchestrated duplication at po`tion {} to {} on chrom {}'.format(start, end, chrom))

    def orchestrate_inversion(self, genome, distribution='uniform'):
        chrom = self.pick_chromosomes(genome, number = 1)[0]
        start = self.get_location_on_sequence(genome[chrom])
        end = self.get_end_of_event(start, genome[chrom], p=0.001)
        self.tracker.create_inversion(chrom, start, end)
        logging.info('Orchestrated inversion at position {} to {} on chrom {}'.format(start, end, chrom))

    def orchestrate_insertion(self, genome, distribution='uniform', p=0.001):
        chrom = self.pick_chromosomes(genome, number = 1)[0]
        start = self.get_location_on_sequence(genome[chrom])
        new_seq_start = self.get_location_on_sequence(genome[chrom])
        new_seq_end = self.get_end_of_event(new_seq_start, genome[chrom], p)
        new_seq = genome[chrom][new_seq_start:new_seq_end]
        self.tracker.create_insertion(chrom, start, new_seq)
        logging.info('Orchestrated insertion at position {} on chrom {} adding bases from position {} to {}'.format(start,
         chrom, new_seq_start, new_seq_end))

    def generate_structural_variations(self, genome, number):
        variations = np.random.choice(list(structural_variations_probabilities.keys()),
                number, structural_variations_probabilities.values())
        for variation in variations:
            self.structural_variations[variation](genome)

    # Create small insertions and small deletions
    def generate_indels(self, genome, number):
        variations = np.random.choice(list(['insertion', 'deletion']), number)
        for variation in variations:
            self.structural_variations[variation](genome, p=0.6)

    # Actually collapses the list of changes
    def generate_fasta_and_bed(self, genome):
        (genome, log_data_frame) =  self.tracker.collapse_list(genome)
        return (genome, self.bed_correct(log_data_frame))

    # We need to store insertions as same start and end. Let's correct that when outputting bed files
    def bed_correct(self, df):
        same_vals = df[df['start'] == df['end']]
        df.ix[same_vals.index, 'end'] +=1
        return df


text:
import gc
import logging
import time

from datetime import datetime
from bson.son import SON
from bson.code import Code
from pymongo import MongoClient
from settings import BULK_TIMEOUT, BULK_MAX_OPS

logging.basicConfig(level=logging.CRITICAL, format='%(asctime)s : %(levelname)s : %(message)s')

def output_latest(dbconnstr):
    """Generate and store latest validation results in database"""
    logging.info("CALL output_latest, with mongodb: " +dbconnstr)
    # open db connection
    client = MongoClient(dbconnstr)
    database = client.get_default_database()
    f_map = Code(
        "function() {"
        "  var key = this.prefix;"
        "  var value = {timestamp: this.timestamp, type: this.type, validated_route: null};"
        "  if (this.type == 'announcement') {"
        "    value['validated_route'] = this.validated_route;"
        "  }"
        "  emit (key, value);"
        "}"
    )
    f_reduce = Code(
        "function (key, values) {"
        "  var robj = { timestamp: 0, type: null, validated_route: null};"
        "  values.forEach(function(value) {"
        "    if ((value != null) && (value.timestamp > robj.timestamp)) {"
        "      robj.timestamp = value.timestamp;"
        "      robj.type = value.type;"
        "      if (value.type == 'announcement') {"
        "        robj.validated_route = value.validated_route;"
        "      }"
        "      else {"
        "        robj.validated_route = null;"
        "      }"
        "    }"
        "  } );"
        "  return robj;"
        "}"
    )
    last_validity_count = 0
    while True:
        try:
            if database.validity.count() != last_validity_count:
                database.validity.map_reduce(
                    f_map, f_reduce,
                    out=SON([("replace", "validity_latest")])
                )
                last_validity_count = database.validity.count()
        except Exception as errmsg:
            logging.exception("MapReduce failed with: " + str(errmsg))
        # end try
        time.sleep(BULK_TIMEOUT)

def output_stat(dbconnstr, interval):
    """Generate and store validation statistics in database"""
    logging.info("CALL output_stat, with mongodb: " +dbconnstr)
    # open db connection
    client = MongoClient(dbconnstr)
    database = client.get_default_database()
    while True:
        # create stats
        stats = dict()
        stats['ts'] = 'now'
        stats['num_Valid'] = 0
        stats['num_InvalidAS'] = 0
        stats['num_InvalidLength'] = 0
        stats['num_NotFound'] = 0
        try:
            pipeline = [
                {"$match": {'value.type': 'announcement'}},
                {"$group": {"_id": "$value.validated_route.validity.state",
                            "count": {"$sum": 1}}}
            ]
            results = list(database.validity_latest.aggregate(pipeline, allowDiskUse=True))
            for i in range(0, len(results)):
                stats["num_"+results[i]['_id']] = results[i]['count']
            ts_tmp = database.validity_latest.find_one(
                projection={'value.timestamp': True, '_id': False},
                sort=[('value.timestamp', -1)])['value']['timestamp']
            stats['ts'] = int(ts_tmp)
        except Exception as errmsg:
            logging.exception("QUERY on validity_latest failed with: " + str(errmsg))
        # end try
        if stats['ts'] != 'now':
            try:
                database.validity_stats.replace_one({'ts': stats['ts']}, stats, True)
            except Exception as errmsg:
                logging.exception("INSERT into stats failed with: " + str(errmsg))
            # end try
        # end if
        time.sleep(interval)
    # end while

def output_data(dbconnstr, pipe, dropdata):
    """Store validation results into database"""
    logging.debug("CALL output_data mongodb, with " + dbconnstr)
    client = MongoClient(dbconnstr)
    database = client.get_default_database()
    if dropdata:
        database.validity.drop()
        database.validity_stats.drop()
        database.validity_latest.drop()
    # end dropdata
    bulk = database.validity.initialize_unordered_bulk_op()
    bulk_len = 0
    begin = datetime.now()
    while True:
        data = pipe.recv()
        if data == 'DONE':
            break
        if (data['type'] == 'announcement') or (data['type'] == 'withdraw'):
            logging.debug("process announcement or withdraw of prefix: " + data['prefix'])
            try:
                bulk.insert(data)
            except Exception as errmsg:
                logging.exception("bulk insert, failed with: " + str(errmsg))
            else:
                bulk_len += 1
        else:
            logging.warning("Type not supported, must be either announcement or withdraw!")
            continue

        now = datetime.now()
        timeout = now - begin
        # exec bulk validity
        if (bulk_len > BULK_MAX_OPS) or (timeout.total_seconds() > BULK_TIMEOUT):
            logging.info("do mongo bulk operation ...")
            # end try create file
            try:
                bulk.execute({'w': 0})
            except Exception as errmsg:
                logging.exception("bulk operation, failed with: " + str(errmsg))
            # end try bulk
            bulk = database.validity.initialize_unordered_bulk_op()
            bulk_len = 0
            cleanup_data(dbconnstr)
            gc.collect()
            begin = datetime.now()

def cleanup_data(dbconnstr):
    """Cleanup data: remove old validation results from database"""
    logging.debug("CALL cleanup_data mongodb, with " +dbconnstr)
    client = MongoClient(dbconnstr)
    database = client.get_default_database()
    counter = 0
    try:
        bulk_remove = database.validity.initialize_unordered_bulk_op()
        pipeline = [
            {"$group": {
                "_id": '$prefix',
                "plist": {"$push" : {"pid": "$_id", "timestamp": "$timestamp"}},
                "maxts": {"$max" : '$timestamp'}}
            },
            {"$unwind": "$plist"},
            {"$project": {
                "mark": {"$cond": [{"$lt": ["$plist.timestamp", "$maxts"]}, "true", "false"]},
                "_id": '$plist.pid',
                'maxts': '$maxts',
                'timestamp': '$plist.timestamp'}
            },
            {"$match": {'mark': "true"}}
        ]
        results = database.validity.aggregate(pipeline, allowDiskUse=True)
        for res in results:
            counter += 1
            bulk_remove.find({"_id": res['_id']}).remove_one()
        if counter > 0:
            bulk_remove.execute()
    except Exception as errmsg:
        logging.exception("cleanup_data failed with: " + str(errmsg))
    # end try


text:
package sharedmux

import (
	"fmt"
	"net/http"
	"strings"
	"sync"
)

var (
	// Admin is the schelling point for those who want to provide admin
	// actions and those who want to install the admin portal in some port.
	Admin = NewAdminMux()
)

// ConcurrentMux is safe to call HandleFunc on even after it's started serving
// requests.
type ConcurrentMux struct {
	mux      *http.ServeMux
	pathList []string
	lock     sync.RWMutex
}

// NewConcurrentMux constructs a mux.
func NewConcurrentMux(mux *http.ServeMux) *ConcurrentMux {
	return &ConcurrentMux{
		mux: mux,
	}
}

func NewAdminMux() *ConcurrentMux {
	c := NewConcurrentMux(http.NewServeMux())
	c.Handle("/", http.HandlerFunc(c.listHTTP))
	return c
}

// Handle installs the given handler.
func (c *ConcurrentMux) Handle(pattern string, handler http.Handler) {
	c.lock.Lock()
	defer c.lock.Unlock()
	c.mux.Handle(pattern, handler)
	c.pathList = append(c.pathList, pattern)
}

// HandleFunc installs the given handler function.
func (c *ConcurrentMux) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
	c.Handle(pattern, http.HandlerFunc(handler))
}

// ServeHTTP serves according to the added handlers.
func (c *ConcurrentMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	c.lock.RLock()
	defer c.lock.RUnlock()
	c.mux.ServeHTTP(w, r)
}

// listHTTP lists handlers that have been added.
func (c *ConcurrentMux) listHTTP(w http.ResponseWriter, r *http.Request) {
	c.lock.RLock()
	defer c.lock.RUnlock()
	fmt.Fprintf(w, "Possible paths:\n%v\n", strings.Join(c.pathList, "\n"))
}


text:
<?php

namespace spec\Malas\BounceHandler\MailImport;

use Malas\BounceHandler\MailImport\IMAPMailImport;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class IMAPMailImportSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
    	$this->beConstructedWith(['mailbox' => '{localhost:143/imap/notls}']);
        $this->shouldHaveType(IMAPMailImport::class);
    }

    function it_should_not_be_initialized_without_mailbox_option() {
    	$this->beConstructedWith(['random_option' => '']);
    	$this->shouldThrow('\InvalidArgumentException')->duringInstantiation();
    }

    function it_should_have_all_properties_set()
    {
    	$this->beConstructedWith([
    		'mailbox' => "{localhost:143/imap/notls}INBOX",
            'username' => 'examplelocalhost',
            'password' => 'p@$$word',
            'delete_mail' => false,
            'options' => 32580,
    		]);
        $this->getMailbox()->shouldBe('{localhost:143/imap/notls}INBOX');
        $this->getUsername()->shouldBe('examplelocalhost');
        $this->getPassword()->shouldBe('p@$$word');
        $this->getDeleteMail()->shouldBe(false);
        $this->getOptions()->shouldBe(32580);
    }
}


text:
var asyncAdd = (a,b)=>{
    return new Promise((resolve, reject)=>{
        setTimeout(()=>{
            if(typeof a === 'number' && typeof b === 'number'){
                resolve(a+b);
            }
            else{
                reject('fuck you arguments should be in numbers');
            }
        }, 1500);
    });
};

asyncAdd(6,5).then((res)=>{
    console.log('Result : ' , res);
},(errorMessage)=>{
    console.log(errorMessage);
});

// var somePromise = new Promise((resolve, reject)=>{
//     //resolve('Hey asshole, It worked');
//     setTimeout(()=>{
//         reject('shit bitch it didnt work out');
//     }, 2500);
// });
//
// somePromise.then((message)=>{
//     console.log('yo babe :',message);
// },(errorMessage)=>{
//     console.log('Holy fuck :', errorMessage);
// });


text:
package com.sas.unravl;

/**
 * An exception in an UnRAVL script definition, runtime, or assertion
 *
 * @author sasdjb
 */
public class UnRAVLException extends Exception {

    private static final long serialVersionUID = 1L;

    public UnRAVLException(Throwable rootCause) {
        super(rootCause);
    }

    public UnRAVLException(String message, Throwable cause) {
        super(message, cause);
    }

    public UnRAVLException(String message) {
        super(message);
    }
}


text:
package de.justgeek.swimdroid.processing;

public class Average {
    private final float decayRate;
    private final float minDistance;

    private float average;

    public Average() {
        this(0, 0.9f, 50);
    }

    public Average(float startValue, float decayRate, float minDistance) {
        this.decayRate = decayRate;
        this.minDistance = minDistance;

        average = startValue;
    }

    public AverageResult classify(float value) {
        float distance = Math.abs(value - average);
        if (distance < minDistance) {
            return AverageResult.UNDEFINED;
        }

        if (value > average) {
            return AverageResult.ABOVE;
        }

        return AverageResult.BELOW;
    }

    public AverageResult update(float value) {
        AverageResult result = classify(value);

        average = (average * decayRate) + (value * (1.0f - decayRate));
        return result;
    }

    public double getAverage() {
        return average;
    }
}


text:
title: ssh config
status: published
tags:
- ssh
---

Apparently I like ssh, because here is another post about it. This is a quick note after I encountered this error when I was trying to connect to some machine at work :

Received disconnect from 192.168.1.223: 2: Too many authentication failures

Which is very cryptic. The problem has to do with ssh-agent. When trying to connect, the agent use all keys in store to try to connect. If one has many keys (I have 6 or 7 stored) and if the right key is the last one used, the remote host shut down the connection after n failed attempts. Because it's not always possible to change the number of try on a remote machine to connect, the solution has to be local.

Hence the config ssh file. This file has to be in ~/.ssh/ with permissions set to 600, otherwise it's going to be ignored. The man page of ssh_config describe everything one needs to know about it. Below a quick snippet for the most useful configuration :

```
Host geekingfrog , 178.32.96.76
HostName geekingfrog.com
IdentityFile ~/.ssh/geekingfrog.com
User user_name

Host 192.168.1.226
IdentityFile ~/.ssh/226_dsa
User user_name2
```

Which solve the problem. In the same time, it allow one to uses host alias and username. So `ssh user@my.domain.com` becomes `ssh mydomain`. Also, the hostname and user in the config file also works with scp. \o/


text:
<?xml version="1.0" encoding="us-ascii"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://www.microsoft.com/2011/12/aaptperffun#1">

  <PerfRunConfiguration LoadProcessesPerClientMultiplier="1" LoadThreadsPerProcessMultiplier="1" SuicideTimeout="2000" />

  <commands>
    <command name="CopyWWW" wait="Exit">
      {bin}\xcopy /ecyi Microsoft.AspNet.SignalR.LoadTestHarness \\{server-01}\perftestbits\www
    </command>
    <command name="SetupIIS" wait="Exit">
      powershell -executionpolicy remotesigned -command "{bin}\RegisterIIS.ps1 {currentdir}\www
    </command>
    <command name="WebSockets-250000" wait="Exit">
      crank.exe /Url:http://{server-01}:81/TestConnection/connect /Connections:250000 /ConnectTimeout:3600 /ControllerUrl:http://{client-01}:8080 /NumClients:4 /SendTimeout:120 /SignalRInstance:testdefault /Transport:WebSockets
    </command>
    <command name="ServerSentEvents-250000" wait="Exit">
      crank.exe /Url:http://{server-01}:81/TestConnection/connect /Connections:250000 /ConnectTimeout:3600 /ControllerUrl:http://{client-01}:8080 /NumClients:4 /SendTimeout:120 /SignalRInstance:testdefault /Transport:ServerSentEvents
    </command>
    <command name="LongPolling-250000" wait="Exit">
      crank.exe /Url:http://{server-01}:81/TestConnection/connect /Connections:250000 /ConnectTimeout:3600 /ControllerUrl:http://{client-01}:8080 /NumClients:4 /SendTimeout:120 /SignalRInstance:testdefault /Transport:LongPolling
    </command>
  </commands>

  <plan>
    <run command="CopyWWW" role="controller" output="true" profile="None" />
    <run command="SetupIIS" role="server-01" output="true" profile="None" />
    <run command="WebSockets-250000" role="client-01" output="true" />

    <run command="SetupIIS" role="server-01" output="true" profile="None" />
    <run command="ServerSentEvents-250000" role="client-01" output="true" />

    <run command="SetupIIS" role="server-01" output="true" profile="None" />
    <run command="LongPolling-250000" role="client-01" output="true" />
  </plan>
</config>


text:
package com.sanluan.cms.views.directive.system;

import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.sanluan.cms.logic.service.system.SystemUserService;
import com.sanluan.common.base.BaseDirective;
import com.sanluan.common.handler.DirectiveHandler;
import com.sanluan.common.handler.PageHandler;

import freemarker.template.TemplateException;

/**
 * @author zhangxd
 *
 */
@Component
public class SystemUserListDirective extends BaseDirective {

	@Override
	public void execute(DirectiveHandler handler) throws TemplateException, IOException {
		PageHandler page = service.getPage(handler.getDate("startDateRegistered"), handler.getDate("endDateRegistered"),
				handler.getDate("startLastLoginDate"), handler.getDate("endLastLoginDate"),
				handler.getBoolean("superuserAccess"), handler.getBoolean("emailChecked"), handler.getString("name"),
				handler.getBoolean("disable", false), handler.getString("orderField"), handler.getString("orderType"),
				handler.getInteger("pageNo", 1), handler.getInteger("count", 20));
		handler.put("page", page).render();
	}

	@Autowired
	private SystemUserService service;

}


text:
$(document).ajaxError(function (event, req, setting, msg) {
    if (typeof console != undefined && console && console.log) {
        console.log(event);
        console.log(req);
        console.log(setting);
        console.log(msg);
    }
});

function getJson(url, data, success) {
    $.ajax({
        url: globalRootUrl + appendRandom(url),
        type: 'get',
        data: JSON.stringify(data || {}),
        contentType: "application/json",
        dataType: "json",
        success: function (response) {
            if (success) success(response);
        }
    });
}

function appendRandom(url) {
    var r = "r=" + Math.random();
    if (url.lastIndexOf('?') > 0) {
        return url + "&" + r;
    }
    return url + "?" + r;
}

function postJson(url, data, success, withGlobal) {
    $.ajax({
        url: !!withGlobal ? url : globalRootUrl + url,
        type: 'post',
        data: JSON.stringify(data || {}),
        contentType: "application/json",
        dataType: "json",
        success: function (response) {
            if (success) success(response);
        }
    });
}

function post(url, data, success) {
    $.ajax({
        url: globalRootUrl + url,
        type: 'post',
        data: JSON.stringify(data || {}),
        contentType: "application/json",
        success: function (response) {
            if (success) success(response);
        }
    });
}

function postPage(url, data, success) {
    $.ajax({
        type: "POST",
        url: url,
        contentType: "application/json",
        param: JSON.stringify(data || {}),
        success: function (response) {
            if (success) success(response);
        }
    });
}


text:
ConcreteObserver::ConcreteObserver(string n):
    name(n)
{
}

ConcreteObserver::~ConcreteObserver()
{
}

void ConcreteObserver::update()
{
    cout << "Updating " << name << endl;
}


text:
package jp.co.flect.soap;

public class InvalidWSDLException extends Exception {

	private static final long serialVersionUID = 5502728788191466137L;

	public InvalidWSDLException(String msg) {
		super(msg);
	}
}


text:
import e32
import _telephone

_phone=_telephone.Phone()
_answering_supported=0

if e32.s60_version_info>=(3,0):
    _answering_supported=1
    EStatusUnknown=_telephone.EStatusUnknown
    EStatusIdle=_telephone.EStatusIdle
    EStatusDialling=_telephone.EStatusDialling
    EStatusRinging=_telephone.EStatusRinging
    EStatusAnswering=_telephone.EStatusAnswering
    EStatusConnecting=_telephone.EStatusConnecting
    EStatusConnected=_telephone.EStatusConnected
    EStatusReconnectPending=_telephone.EStatusReconnectPending
    EStatusDisconnecting=_telephone.EStatusDisconnecting
    EStatusHold=_telephone.EStatusHold
    EStatusTransferring=_telephone.EStatusTransferring
    EStatusTransferAlerting=_telephone.EStatusTransferAlerting

    _phone_incoming=_telephone.Phone()
    _phone_answer=_telephone.Phone()

    _my_call_back=None

_is_closed=1

def dial(number):
    global _is_closed
    if _is_closed:
        _phone.open()
        _is_closed=0
    _phone.set_number(number)
    _phone.dial()
def hang_up():
    try:
        _phone.hang_up()
    except:
        if _answering_supported:
            try:
                _phone_answer.hang_up()
            except:
                raise

if _answering_supported:
    def call_state(cb):
        global _my_call_back
        _my_call_back=cb
        _phone_incoming.incoming_call(_telephone_call_back)
    def _answer(arg):
        # XXX state checking here?
        pass
    def incoming_call():
        _phone_answer.incoming_call(_answer)
    def answer():
        _phone_answer.answer()
    def cancel():
        _phone.cancel()
        _phone_incoming.cancel()
        _phone_answer.cancel()
    def _telephone_call_back(arg):
        global _my_call_back
        _phone_incoming.incoming_call(_telephone_call_back)
        _my_call_back(arg)


text:
OPENNI_INCLUDE_PATH=/usr/local/Cellar/openni/1.5.7.10/include/ni #You may need to adapt me

BOOST_SUFFIX=-mt        # Change this to empty if you are not using multithreaded boost
BOOST_LIBS=boost_system boost_signals boost_thread
BOOST_LDFLAGS=$(BOOST_LIBS:%=-l%$(BOOST_SUFFIX))

CXXFLAGS+=$(shell pkg-config opencv --cflags) -I$(OPENNI_INCLUDE_PATH) -Wno-attributes
LDFLAGS+=$(shell pkg-config opencv --libs) -lOpenNI $(BOOST_LDFLAGS)
debug: CXXFLAGS += -g

SRC_FILES=$(shell find . -iname "*.cpp")
HDR_FILES=$(shell find . -iname "*.h")
OBJ_FILES=$(SRC_FILES:%.cpp=%.o)
DEP_FILES=$(SRC_FILES:%.cpp=%.d)

EXENAME=assignment5

all: $(EXENAME)

debug: all

%.d: %.cpp
	$(CXX) -MM $(CXXFLAGS) $< > $@

$(EXENAME): $(OBJ_FILES) $(HDR_FILES)
	$(CXX) -o $@ $(OBJ_FILES) $(LDFLAGS)

clean:
	$(RM) $(OBJ_FILES) $(DEP_FILES)
	$(RM) $(EXENAME)

run: $(EXENAME)
	./$(EXENAME)

.PHONY: all clean run

-include $(DEP_FILES)


text:
    <meta http-equiv="Content-Type" content="text/html; charset=Windows-1252" />
    <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5" />
    <title>SqlQueryStrings.GetUDDTsList Field</title>
    <xml>
    </xml>
    <link rel="stylesheet" type="text/css" href="MSDN.css" />

            SQL Schema Tool Help

SqlQueryStrings.GetUDDTsList Field

 const ssql statement

public const string GetUDDTsList = "USE [{0}]
CREATE TABLE #temp1
(
[name] sysname COLLATE SQL_Latin1_General_CP1_CI_AS
)

INSERT INTO #temp1 SELECT [name] from master.dbo.systypes

CREATE TABLE #temp2
(
[uddt_name] sysname COLLATE SQL_Latin1_General_CP1_CI_AS,
[user_name] sysname COLLATE SQL_Latin1_General_CP1_CI_AS,
[type] sysname COLLATE SQL_Latin1_General_CP1_CI_AS,
[prec] int,
[scale] int,
[allownulls] int,
[default] sysname COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
[rule] sysname COLLATE SQL_Latin1_General_CP1_CI_AS NULL
)

INSERT INTO #temp2
SELECT
	a.name as UDDT_NAME,
	b.name as USER_NAME,
	(SELECT TOP 1 [name] FROM [{0}].dbo.systypes AS c WHERE c.xusertype = a.xtype) AS type,
	a.prec,
	a.scale,
	a.allownulls,
	(SELECT TOP 1 [name] from [{0}].dbo.sysobjects AS d WHERE d.id = a.tdefault) as [default],
	(SELECT TOP 1 [name] FROM [{0}].dbo.sysobjects AS e WHERE e.type = 'R' and e.id = a.domain) AS [Rule]
FROM [{0}].dbo.systypes AS a INNER JOIN [{0}].dbo.sysusers AS b ON b.uid = a.uid

SELECT * FROM #temp2 as a
WHERE a.UDDT_NAME NOT IN (SELECT [name] FROM #temp1) ORDER BY UDDT_NAME, USER_NAME

DROP TABLE #temp1
DROP TABLE #temp2
";

See Also

        SqlQueryStrings Class | Lewis.SST.SQLObjects Namespace

      <object type="application/x-oleobject" classid="clsid:1e2a7bd0-dab9-11d0-b93a-00c04fc99f9e" viewastext="true" style="display: none;">
        <param name="Keyword" value="GetUDDTsList field">
        </param>
        <param name="Keyword" value="GetUDDTsList field, SqlQueryStrings class">
        </param>
        <param name="Keyword" value="SqlQueryStrings.GetUDDTsList field">
        </param>
      </object>

Generated from assembly SST [1.0.2793.35291]


text:
<?php

namespace Regweb\Rest;

class RequestMetaData {

	public $title;
	public $description;
	public $url;
	public $method;

	const GET = 'GET';
	const POST = 'POST';

	/**
	 * Arguments keyed by name, with description as value
	 * @var array
	 */
	public $getParams;
	public $postParams;
	/**
	 * Array of responses keyed by status code
	 * @var array
	 */
	public $responses;

	public function __construct(	$title,
									$description,
									$url,
									$method,
									$getParams,
									$postParams,
									$responses) {
		$this->title = $title;
		$this->description = $description;
		$this->url = $url;
		$this->method = $method;
		$this->getParams = $getParams;
		$this->postParams = $postParams;
		$this->responses = $responses;
	}

	public function render() {

		// Header, description, url
		$output = '
';
		$output .= '
';
		$output .= $this->method.' /'.$this->url.' - '.$this->title.'
';
		$output .= '
'.$this->description.'
';

		// Get and post params
		foreach (array('GET', 'POST') as $method) {
			$paramsMeta = ($method == 'GET') ? $this->getParams : $this->postParams;
			if (count($paramsMeta) == 0) {
				continue;
			}

			$output .= '
'.$method.' parameters
';
			foreach ($paramsMeta as $key => $description) {
				$output .= '
'.$key.'	';
				$output .= ''.$description.'
';
			}
		}

		// Responses
		$output .= '
Responses by status code
';
		foreach ($this->responses as $statusCode => $response) {
			$output .= '
'.$statusCode.'
'.$response['description'].'
	';

			$output .= $this->renderResponseData($response['data']);

			$output .= '
';
		}
		$output .= '
';
		return $output;
	}

	public function renderResponseData($data, $title = null) {
		$output = '
';
		if ($title !== null) {
			$output .= '
'.$title.'
';
		}
		foreach ($data as $key => $description) {
			if (is_array($description)) {
				// Child properties
				$output .= '
'.$key.'	'.$description['description'];
				if (isset($description['expand'])) {
					$output .= $this->renderResponseData($description['data'], 'Default data');
					$output .= $this->renderResponseData($description['expanded_data'], 'Expanded data');
				} else {
					$output .= $this->renderResponseData($description['data']);
				}
				$output .= '
';
				continue;
			}
			$output .= '
'.$key.'	'.$description.'
';
		}
		$output .= '
';
		return $output;
	}
}