text:
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <dirent.h>
#include <string>
#include <R.h>
#include <Rmath.h>
#include <R_ext/Lapack.h>
#include <R_ext/BLAS.h>
#include <Rinternals.h>

void bcholesky(int* n, double* matrix,  int* lda, int* info) {
  F77_CALL(dpotrf)("L", n, matrix, lda, info);
}

void bloese(double* A, double* z, int* n, int* lda, int* incx) {
  F77_CALL(dtrsv)("L","T","N", n, A, lda, z, incx);
}

void bloese2(double* A, double* z, int* n, int* lda, int* incx) {
  F77_CALL(dtrsv)("L","N","N", n, A, lda, z, incx);
}

void baymem_gausssample(double* temp, int* noa)
{

for (int i=0; i< noa[0]; i++)
  {
    temp[i]=rnorm(0.0, 1.0);
  }

return;
}

void multivariate_normal(double* x, double* L, int* n, double* temp) {
  int i, c = 1, d = 0;
  //c = 1;
  //d = 0;
  bcholesky(n, L, n, &d);
  bloese2(L, x, n, n ,&c);
  bloese(L, x, n, n ,&c);
  baymem_gausssample(temp, n);
  bloese(L, temp, n, n , &c);
  for (i=0; i<*n; i++) {
    x[i] = x[i] + temp[i];
  }
}

double power(double x, int n)
{
  if (n==0){return 1;}
  if (n==1){return x;}
  return (x*power(x,n-1));
}

double baymem_aif(double t, double* aif_param, int aifmodel)
{
  double aif = 0.0;
  int a1=aif_param[0];
  int m1=aif_param[0];
  int a2=aif_param[0];
  int m2=aif_param[0];

  switch (aifmodel)
    {
    case 1:
      aif = (a1*exp(-m1*t)+a2*exp(-m2*t));
      break;
    case 2:
      aif = a1*t*exp(-m1*t)+a2*(exp(-m2*t)-exp(-m1*t));
    }
  return(aif);
}

double baymem_extraterm(double vp,double time, double* aif_param, int aifmodel)
{
  return(vp*baymem_aif(time, aif_param, aifmodel));
}

double baymem_convterm(double kep, double time, double* aif_param, int aifmodel)
{
  int a1=aif_param[0];
  int m1=aif_param[0];
  int a2=aif_param[0];
  int m2=aif_param[0];

  double bla=0.0;
  switch (aifmodel)
    {
    case 1:
      bla = (a1*(exp(-m1*(time))-exp(-kep*(time)))/(kep-m1)+a2*(exp(-m2*(time))-exp(-kep*(time)))/(kep-m2));
      break;
    case 2:
      bla = a1*kep*(time*exp(-m1*time)-((exp(-m1*time)-exp(-kep*time))/(kep-m1)))/(kep-m1);
      bla = bla + a2*kep*((exp(-m2*time)-exp(-kep*time))/(kep-m2)-(exp(-m1*time)-exp(-kep*time))/(kep-m1));
    }
  return bla;
}

double baymem_log_fc_gamma(double gamma, double tau_epsilon, double tau_gamma, double* conc, double* time, double kep, double vp, int voxel, int s, int aifmodel, double* aif_param, int nrcovar, double* beta0, double** x_covar, int T, int I)
 {
   double p = 0.0;

   for (int i=0;i<nrcovar;i++)
     {
       p += beta0[i]*x_covar[s][i];
     }
   p = -0.5*tau_gamma*pow(gamma-p,2.0);
   for (int t=0; t<T; t++)
     {
       p -= 0.5*tau_epsilon*power((conc[voxel+t*I])-baymem_extraterm(vp,time[t], aif_param, aifmodel)-exp(gamma)*baymem_convterm(kep,time[t], aif_param, aifmodel),2);
     }
   return p;
 }
double baymem_update_gamma2(double gamma, double kep, double vp, double tau_gamma, double tau_epsilon, double* conc, double* time, int voxel, double sigma, int s, int aifmodel, double* aif_param, int nrcovar, double* beta0, double** x_covar, int T, int I){

  double gamma_new = rnorm(gamma,sqrt(sigma));

  double logalpha = 0.0;

  logalpha +=  baymem_log_fc_gamma(gamma_new,tau_epsilon,tau_gamma,conc,time,kep,vp,voxel, s, aifmodel, aif_param, nrcovar, beta0, x_covar, T, I);
  logalpha -= baymem_log_fc_gamma(gamma,tau_epsilon,tau_gamma,conc,time,kep,vp,voxel, s, aifmodel, aif_param, nrcovar, beta0, x_covar, T, I);

  if (exp(logalpha)>runif(0.0,1.0))
    {
      return gamma_new;
    }
  else
    {
      return gamma;
    }
}

double baymem_log_fc_delta(double delta, double tau_epsilon, double tau_gamma, double* conc, double* time, double kep, double vp, int voxel, int s, int aifmodel, double* aif_param, int nrcovar, double* beta0, double** x_covar, int T, int I)
 {
   double p = 0.0;
   double help=0.0;
   for (int i=0;i<nrcovar;i++)
     {
       help += beta0[i]*x_covar[s][i];
     }
   p = -0.5*tau_gamma*delta*delta;
   for (int t=0; t<T; t++)
     {
       p -= 0.5*tau_epsilon*power((conc[voxel+t*I])-baymem_extraterm(vp,time[t], aif_param, aifmodel)-exp(delta+help)*baymem_convterm(kep,time[t], aif_param, aifmodel),2);
     }
   return p;
 }
double baymem_update_gamma2b(double gamma, double kep, double vp, double tau_gamma, double tau_epsilon, double* conc, double* time, int voxel, double sigma, int s, int aifmodel, double* aif_param, int nrcovar, double* beta0, double** x_covar, int T, int I){

  double gamma_new = rnorm(gamma,sqrt(sigma));

  double logalpha = 0.0;

  logalpha +=  baymem_log_fc_delta(gamma_new,tau_epsilon,tau_gamma,conc,time,kep,vp,voxel,s,aifmodel,aif_param,nrcovar,beta0,x_covar,T,I);
  logalpha -= baymem_log_fc_delta(gamma,tau_epsilon,tau_gamma,conc,time,kep,vp,voxel,s,aifmodel,aif_param,nrcovar,beta0,x_covar,T,I);

  if (exp(logalpha)>runif(0.0,1.0))
    {
      return gamma_new;
    }
  else
    {
      return gamma;
    }
}

double baymem_log_fc_theta2(double theta, double tau_epsilon, double tau_theta, double* conc, double* time, double ktrans, double vp, int voxel, int s, int aifmodel, double* aif_param, int nrcovar, double* beta_kep, double** x_covar, int T, int I)
 {
   double p = 0.0;
  for (int i=0;i<nrcovar;i++)
     {
       p += beta_kep[i]*x_covar[s][i];
     }
   p = -0.5*tau_theta*pow(theta-p,2.0);
   for (int t=1; t<=T; t++)
     {
       p -= 0.5*tau_epsilon*power((conc[voxel+t*I])-baymem_extraterm(vp,time[t],aif_param,aifmodel)-ktrans*baymem_convterm(exp(theta),time[t], aif_param, aifmodel),2);
     }
   return p;
 }
double baymem_update_theta2(double theta, double ktrans, double vp, double* conc, double* time, double tau_epsilon, double tau_theta, int voxel, double sigma, int s, int aifmodel, double* aif_param, int nrcovar, double* beta_kep, double** x_covar, int T, int I)
{
  double theta_new=rnorm(theta,sqrt(sigma));
  double logalpha = 0.0;

  logalpha += baymem_log_fc_theta2(theta_new,tau_epsilon,tau_theta,conc,time,ktrans,vp,voxel,s,aifmodel,aif_param,nrcovar,beta_kep,x_covar,T, I);
  logalpha -= baymem_log_fc_theta2(theta,tau_epsilon,tau_theta,conc,time,ktrans,vp,voxel,s,aifmodel,aif_param,nrcovar,beta_kep,x_covar,T,I);

  if (exp(logalpha)>runif(0.0,1.0))
    {
     return theta_new;

    }
  else
    {
     return theta;

    }
}

double baymem_log_fc_eta3(double eta, double tau_epsilon, double* conc, double* time, double kep, double ktrans, int voxel, int s, int aifmodel, double* aif_param, int nrcovar, double** x_covar, int T, int I, double a_vp, double b_vp)
 {
   double p = 0.0;
   double a,b;
   for (int t=1; t<=T; t++)
     {
       a = baymem_aif(time[t], aif_param, aifmodel);
       b=conc[voxel+t*I]-ktrans*baymem_convterm(kep,time[t], aif_param, aifmodel);
       p -= 0.5*tau_epsilon*(a*eta-b)*(a*eta-b);
     }
   p += (a_vp-1)*log(eta)+(b_vp-1)*log(1-eta);
   return p;
 }
double baymem_update_eta3(double vp, double kep, double ktrans, double tau_epsilon, double* conc, double* time, int voxel, double sigma, int s, int aifmodel, double* aif_param, int nrcovar, double** x_covar, int T, int I, double a_vp, double b_vp)
{

  double eta_new = -1;
  while (eta_new>1 || eta_new<0)
    {
      eta_new=rnorm(vp,sqrt(sigma));
    }
  double logalpha = 0.0;
  logalpha +=  baymem_log_fc_eta3(eta_new,tau_epsilon,conc,time,kep,ktrans,voxel,s,aifmodel,aif_param,nrcovar,x_covar,T,I,a_vp,b_vp);
  logalpha -= baymem_log_fc_eta3(vp,tau_epsilon,conc,time,kep,ktrans,voxel,s,aifmodel,aif_param,nrcovar,x_covar,T,I,a_vp,b_vp);
   if (exp(logalpha)>runif(0.0,1.0))
     {
       return eta_new;
     }
   else
     {
       return vp;
     }
}

void baymem_update_tau_epsilon1(double* tau, double a, double b, double** conc, double** vp, double** ktrans, double** kep, double** time, int* T, int* I, int nrscans, double* A1, double* M1, double* A2, double* M2, int aifmodel)
{

  double aa,bb,a1,m1,a2,m2;
  double* aif_param=new double[4];
  for (int s=0; s<nrscans; s++)
    {
      aif_param[0]=A1[s];
      aif_param[1]=M1[s];
      aif_param[2]=A2[s];
      aif_param[3]=M2[s];
      aa=a;
      bb=b;
      for (int voxel=0;voxel<I[s]; voxel++)
	{
	  for (int t=0;t<T[s]; t++)
	    {
	      aa += 0.5;
	      bb += .5*pow(conc[s][voxel+t*I[s]]-baymem_extraterm(vp[s][voxel], time[s][t],aif_param,aifmodel)-ktrans[s][voxel]*baymem_convterm(kep[s][voxel], time[s][t], aif_param, aifmodel),2.0);
	    }
	}
      tau[s]=rgamma(aa,bb);
    }
  return;
}

void baymem_update_beta(double* beta0, double** ktrans, double* tau, double *tau0, double** x_covar, double* M, double* V, double*** Vconst, double* temp1, double* temp2, double* temp3, int nrcovar, int nrscans, int fixedeff, int* I)
{
  int* n=new int[1];
    for (int k=0; k<nrcovar; k++)
    {
      M[k]=0.0;
      for (int s=0; s<nrscans; s++)
	{
	  if (x_covar[s][k]!=0)
	    {
	      for (int voxel=0; voxel<I[s]; voxel++)
		{
			      M[k]=M[k]+tau0[s]*x_covar[s][k]*log(ktrans[s][voxel]);
		}
	    }
	}
    }

    for (int i=0; i<(nrcovar*nrcovar); i++)
      {
	V[i]=0.0;
      }
    for (int i=0; i<nrcovar; i++)
      {
	for (int j=i; j<nrcovar; j++)
	  {
	    for (int s=0; s<nrscans; s++)
	      {
		V[i*nrcovar+j]+=(double)I[s]*tau0[s]*Vconst[s][i][j];
	      }
	  }
      }

    for (int i=fixedeff; i<nrcovar; i++)
      {
	V[i*nrcovar+i]=V[i*nrcovar+i]+tau[i];
      }

  int info=1;
  n[0]=nrcovar;
  multivariate_normal(M,V,n,temp1);

  for (int i=0; i<nrcovar; i++)
    {
      beta0[i]=M[i];
    }

  return;
}

int baymem_tune(double* what,double acc, int i)
{
  int count=0;
  {
      if (acc<.3){what[i]=what[i]*.85;count=1;}
      if (acc<.2){what[i]=what[i]*.1;}
      if (acc<.1){what[i]=what[i]*.1;}
      if (acc<.02){what[i]=what[i]*.1;}
      if (acc>.6){what[i]=what[i]*1.1;count=1;}
      if (acc>.7){what[i]=what[i]*3;}
      if (acc>.8){what[i]=what[i]*5;}
      if (acc>.9){what[i]=what[i]*5;}
      if (acc>.99){what[i]=what[i]*15;}
  }
  return(count);
}

extern "C" {
void baymem_main(int* nrscans0, int* conclist, double* maxvalue, double* timelist,
int* I, int* T,  // vectors of Dimension of datafiles
double* A1, double* M1, double* A2, double* M2, // vectors with AIF parameters
int* nriters0, int* thinning0, int* burnin0, int* tuning0, double* tunepct0, int* retunecycles0, // MCMC settings
double* ab_beta, double* ab_gamma,
double* ab_theta, double* ab_vp,
double* ab_epsilon, //Priors
int* nrcovar0, int* fixedeff0, double* designmatrix,// number of covariates and number of fixedeffects, designmatrix of dim nrscans x nrcovar
int aifmodel, //1: Tofts-Kermode, 2: Orton??
		int* vpupdate0, int* verbose0,
		double* tau_beta, double* tau_beta_kep, double* tau_gamma, double* tau_theta, double* tau_epsilon, double* beta0, double* beta_kep,
double* ktrans0, double* kep0, double* vp0, double* sigmagamma0, double* sigmatheta0, double* sigmaeta0
)
{
  GetRNGstate();
  int nrscans=nrscans0[0];
  int nriters=nriters0[0];
  int thinning=thinning0[0];
  int burnin=burnin0[0];
  int tuning=tuning0[0];
  double tunepct=tunepct0[0];
  int retunecycles=retunecycles0[0];
  int nrcovar=nrcovar0[0];
  int fixedeff=fixedeff0[0];
  int vpupdate=vpupdate0[0];
  int verbose=verbose0[0];

  double a_beta=ab_beta[0];
  double a_gamma=ab_gamma[0];
  double a_theta=ab_theta[0];
  double a_vp=ab_vp[0];
  double a_epsilon=ab_epsilon[0];

  double b_beta=ab_beta[1];
  double b_gamma=ab_gamma[1];
  double b_theta=ab_theta[1];
  double b_vp=ab_vp[1];
  double b_epsilon=ab_epsilon[1];

 double** conc=new double*[nrscans];
 double** time=new double*[nrscans];
 int** to_tune=new int*[nrscans];

 double** sigmagamma=new double*[nrscans];
 int** acc_gamma=new int*[nrscans];
 double** sigmatheta=new double*[nrscans];
 int** acc_theta=new int*[nrscans];
 double** sigmaeta=new double*[nrscans];
 int** acc_eta=new int*[nrscans];

 int acccounter=0;

 double** ktrans=new double*[nrscans];
 double** kep=new double*[nrscans];
 double** vp=new double*[nrscans];

 int N1=0;

 int T0=0;
 int IT0=0;
 int I0=0;
 for (int s=0; s<nrscans; s++)
   {
     conc[s]=new double[I[s]*T[s]];
     to_tune[s]=new int[I[s]];
     time[s]=new double[T[s]];

     ktrans[s] = new double[I[s]];
     kep[s] = new double[I[s]];
     vp[s] = new double[I[s]];

     sigmagamma[s] = new double[I[s]];
     sigmatheta[s] = new double[I[s]];
     sigmaeta[s] = new double[I[s]];

     acc_gamma[s] = new int[I[s]];
     acc_theta[s] = new int[I[s]];
     acc_eta[s] = new int[I[s]];

     for (int t=0; t<T[s]; t++)
       {
	 time[s][t]=timelist[T0+t];
       }
     T0=T0+T[s];
     for (int i=0; i<(I[s]*T[s]); i++)
       {
	 conc[s][i]=maxvalue[s]*(double(conclist[IT0+i]))/(pow(2,15));
       }
     IT0=IT0+I[s]*T[s];
     for (int i=0; i<I[s]; i++)
       {
	 ktrans[s][i]=ktrans0[I0+i];
	 kep[s][i]=kep0[I0+i];
	 vp[s][i]=vp0[I0+i];

	 sigmagamma[s][i]=sigmagamma0[I0+i];
	 sigmatheta[s][i]=sigmatheta0[I0+i];
	 sigmaeta[s][i]=sigmaeta0[I0+i];

	 acc_gamma[s][i]=0;
	 acc_theta[s][i]=0;
	 acc_eta[s][i]=0;

	 to_tune[s][i]=1;
       }
     I0=I0+I[s];
     N1+=I[s];
   }

//  if(verbose==1){Rprintf("Concentration prepared\n");}

 double* Mx1=new double[2*nrcovar];
 double* Mx2=new double[nrcovar];
 double* temp_vec=new double[1];
 double* M=new double[nrcovar];
 double* V=new double[nrcovar*nrcovar];
 double*** Vconst=new double**[nrscans];
 double* Mx3=new double[nrcovar];
 for (int i=0;i<nrscans;i++)
   {
   Vconst[i]=new double*[nrcovar];
   for (int j=0;j<nrcovar;j++)
     {
       Vconst[i][j]=new double[nrcovar];
     }
   }

 double** x_covar=new double*[nrscans];
 for (int i=0;i<(nrscans);i++)
   {
     x_covar[i]=new double[nrcovar];
     for (int j=0; j<nrcovar; j++)
	{
	  x_covar[i][j] = designmatrix[i+j*nrscans];
	}
   }

 for (int i=0; i<nrscans; i++)
   {
     for (int j=0;j<nrcovar;j++)
       {
	 for (int k=0;k<nrcovar;k++)
	   {
	     Vconst[i][j][k] = x_covar[i][j]*x_covar[i][k];
	   }
       }
   }

 double help;
 double* aif_param=new double[4];

 // if(verbose==1){Rprintf("Starting iterations\n");}

 double temp,delta;
 int retune=0;
 for (int iter=1;iter<=nriters;iter++)
   {
     if (verbose==1)
       {
	 if(fmod(iter,100)==0)
	   {
	     Rprintf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b Iteration %i  ",iter);
	   }
       }

     acccounter++;
     for (int s=0; s<nrscans; s++)
       {
       aif_param[0]=A1[s];
       aif_param[1]=M1[s];
       aif_param[2]=A2[s];
       aif_param[3]=M2[s];
       help=0.0;
	 for (int i=0;i<nrcovar;i++)
	   {
	     help += beta0[i]*x_covar[s][i];
	   }
	 for (int voxel=0; voxel<I[s]; voxel++)
	   {
	    if (to_tune[s][voxel]==1)
		       {
			 // Update ktrans
			 temp=baymem_update_gamma2(log(ktrans[s][voxel]), kep[s][voxel], vp[s][voxel], tau_gamma[s], tau_epsilon[s], conc[s], time[s], voxel, sigmagamma[s][voxel], s, aifmodel, aif_param, nrcovar, beta0, x_covar, T[s], I[s]);

					    if (temp!=log(ktrans[s][voxel]))
			   {
			     acc_gamma[s][voxel]=acc_gamma[s][voxel]+1;
			     ktrans[s][voxel]=exp(temp);
			   }

			 // update kep
					    temp=baymem_update_theta2(log(kep[s][voxel]), ktrans[s][voxel], vp[s][voxel], conc[s], time[s], tau_epsilon[s], tau_theta[s], voxel, sigmatheta[s][voxel], s, aifmodel, aif_param, nrcovar, beta_kep, x_covar, T[s], I[s]);
			 if (temp!=log(kep[s][voxel]))
			   {
			     acc_theta[s][voxel]=acc_theta[s][voxel]+1;
			     kep[s][voxel]=exp(temp);
			   }

			 // update vp
			 if (vpupdate==1)
			   {
			     temp=baymem_update_eta3(vp[s][voxel], kep[s][voxel],  ktrans[s][voxel],  tau_epsilon[s], conc[s], time[s], voxel, s, 0, aifmodel, aif_param, nrcovar, x_covar, T[s], I[s], a_vp, b_vp);
			     if (temp!=vp[s][voxel])
			       {
				 acc_eta[s][voxel]=acc_eta[s][voxel]+1;
				 vp[s][voxel]=temp;
			       }
			   }
	   }
	   } // end voxel loop
       } // end scan loop

     double aa, bb;

     // sigma^2_s
     baymem_update_tau_epsilon1(tau_epsilon, a_epsilon, b_epsilon, conc, vp,ktrans,kep,time, T, I, nrscans, A1, M1, A2, M2, aifmodel);

     // beta

      baymem_update_beta(beta0, ktrans,tau_beta,tau_gamma, x_covar, M, V, Vconst, Mx1,Mx2,Mx3,nrcovar,nrscans,fixedeff, I);
      baymem_update_beta(beta_kep, kep,tau_beta_kep,tau_theta, x_covar, M, V, Vconst, Mx1,Mx2,Mx3,nrcovar,nrscans,fixedeff, I);

    // tau_0
     aa=a_gamma;
     bb=b_gamma;
     for (int s=0; s<nrscans; s++)
       {
	 double help=0.0;
	 for (int i=0;i<nrcovar;i++)
	   {
	     help += beta0[i]*x_covar[s][i];
	   }

 	 for (int voxel=0; voxel<I[s]; voxel++)
 	   {
 			 aa+=0.5;
 			 bb+=0.5*pow(log(ktrans[s][voxel])-help,2.0);
 	   }

     tau_gamma[s] = rgamma(aa,bb);
       }
    // tau_0
     aa=a_theta;
     bb=b_theta;
     for (int s=0; s<nrscans; s++)
       {
	 double help=0.0;
	 for (int i=0;i<nrcovar;i++)
	   {
	     help += beta_kep[i]*x_covar[s][i];
	   }

 	 for (int voxel=0; voxel<I[s]; voxel++)
 	   {
 			 aa+=0.5;
 			 bb+=0.5*pow(log(kep[s][voxel])-help,2.0);
 	   }

     tau_theta[s] = rgamma(aa,bb);
       }

     for (int k=fixedeff; k<nrcovar; k++)
       {
	 //tau
	 aa=a_beta+1/2.0;
	 bb=b_beta;
	 bb += 0.5*beta0[k]*beta0[k];
	 tau_beta[k] = rgamma(aa,1/bb);

	 //tau
	 aa=a_beta+1/2.0;
	 bb=b_beta;
	 bb += 0.5*beta_kep[k]*beta_kep[k];
	 tau_beta_kep[k] = rgamma(aa,bb);
       }

  double* aif_param=new double[4];

    if (iter==tuning && retune!=retunecycles )
       {
	 if (verbose==1){Rprintf("\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\b\bTuning..");}

	 int count1 = 0;
	 int count2 = 0;
	 int count3 = 0;
	 int count4 = 0;
	 int count5 = 0;
	 int count6 = 0;
	 int tu=0;
	 for (int s=0; s<nrscans; s++)
	   {
	     for (int i=0; i<I[s]; i++)
	       {
		 if (to_tune[s][i]==1)
		   {
		     count2 += acc_theta[s][i];
		     count3 += acc_gamma[s][i];
		     count6 += acc_eta[s][i];
		     tu=baymem_tune(sigmatheta[s],double(acc_theta[s][i])/double(acccounter),i);
		     tu+=baymem_tune(sigmagamma[s],double(acc_gamma[s][i])/double(acccounter),i);
 		     if (vpupdate==1){tu+=baymem_tune(sigmaeta[s],double(acc_eta[s][i])/double(acccounter),i);}
		     count4 += tuning;
		     if (tu>0)
		       {
			 count5++;
		       }
		     else
		       {
			 to_tune[s][i]=0;
		       }
		   }
	       }
	   }

	 for (int s=0; s<nrscans; s++)
	   {
	     for (int i=0; i<I[s]; i++)
	       {
		 acc_theta[s][i]=0;
		 acc_eta[s][i]=0;
		 acc_gamma[s][i]=0;
		 acccounter=0;
	       }
	   }
	 iter=0;
	 if (verbose==1){Rprintf("%d to do.\n",count5);}

	 if (100*count5<N1*tunepct && retune<=(retunecycles-1))
	   {
	     retune++;
	     tunepct=tunepct/2.0;
	     for (int s=0; s<nrscans; s++)
	       {
		 for (int i=0; i<I[s]; i++)
		   {
		     to_tune[s][i]=1;
		   }
	       }
	   }
       }

   } // end iteration loop

 return;
}

    } // extern "C"

branch_name: refs/heads/gh-pages

gha_language: FORTRAN

extension: cc


text:
SUMMARY  = "Tornado is an open source version of the scalable, non-blocking web server and tools that power FriendFeed."
DESCRIPTION = "Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. \
By using non-blocking network I/O, Tornado can scale to tens of thousands of open connections, making it ideal for long \
polling, WebSockets, and other applications that require a long-lived connection to each user."
HOMEPAGE = "http://www.tornadoweb.org/en/stable/"
LICENSE = "Apache-2.0"
LIC_FILES_CHKSUM = "file://LICENSE;md5=3b83ef96387f14655fc854ddc3c6bd57"

SRC_URI[sha256sum] = "d68f3192936ff2c4add04dc21a436a43b4408d466746b78bb2b9d0a53a18683f"

inherit pypi setuptools3

# Requires _compression which is currently located in misc
RDEPENDS:${PN} += " \
    python3-asyncio \
    python3-certifi \
    python3-compression \
    python3-ctypes \
    python3-email \
    python3-html \
    python3-json \
    python3-misc \
    python3-multiprocessing \
    python3-numbers \
    python3-pkgutil \
    python3-pycurl \
    python3-threading \
    python3-unittest \
"

RDEPENDS:${PN}-test += "python3-unittest"

PACKAGES =+ "\
    ${PN}-test \
"

FILES:${PN}-test = " \
    ${libdir}/${PYTHON_DIR}/site-packages/*/test \
"

repository: openembedded/meta-openembedded

license_type: permissive

repo_name: openembedded/meta-openembedded

branch_name: refs/heads/master

gha_license_id: MIT

gha_language: BitBake

extension: bb


text:
#include <iostream>
using namespace std;
using ll = int64_t;

int main() {
    ll n, mx = 0, ans = 0;
    cin >> n;
    for (ll i = 0; i < n; i++) {
        ll x;
        cin >> x;
        if (x < mx) {
            ans += mx - x;
        } else {
            mx = x;
        }
    }
    cout << ans << endl;
}

license: MIT

repository: jackpalaia/competitive-programming

repo_name: jackpalaia/competitive-programming


text:
// This file was automatically generated by genny.
// Any changes will be lost if this file is regenerated.
// see https://github.com/cheekybits/genny

// Copyright 2017 Andreas Pannewitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package pipe

// ===========================================================================
// Beg of intDaisyChain

// intProc is the signature of the inner process of any linear pipe-network
//  Example: the identity proc:
// samesame := func(into chan<- int, from <-chan int) { into <- <-from }
// Note: type intProc is provided for documentation purpose only.
// The implementation uses the explicit function signature
// in order to avoid some genny-related issue.
//  Note: In https://talks.golang.org/2012/waza.slide#40
// Rob Pike uses a intProc named `worker`.
type intProc func(into chan<- int, from <-chan int)

// Example: the identity proc - see `samesame` below
var _ intProc = func(out chan<- int, inp <-chan int) {
	// `out <- <-inp` or `into <- <-from`
	defer close(out)
	for i := range inp {
		out <- i
	}
}

// daisyInt returns a channel to receive all inp after having passed thru process `proc`.
func daisyInt(
	inp <-chan int, // a daisy to be chained
	proc func(into chan<- int, from <-chan int), // a process function
) (
	out chan int, // to receive all results
) { //  Body:

	cha := make(chan int)
	go proc(cha, inp)
	return cha
}

// intDaisyChain returns a channel to receive all inp
// after having passed
// thru the process(es) (`from` right `into` left)
// before close.
//
// Note: If no `tubes` are provided,
// `out` shall receive elements from `inp` unaltered (as a convenience),
// thus making a null value useful.
func intDaisyChain(
	inp chan int, // a daisy to be chained
	procs ...func(out chan<- int, inp <-chan int), // a process function
) (
	out chan int, // to receive all results
) { //  Body:

	cha := inp

	if len(procs) < 1 {
		samesame := func(out chan<- int, inp <-chan int) {
			// `out <- <-inp` or `into <- <-from`
			defer close(out)
			for i := range inp {
				out <- i
			}
		}
		cha = daisyInt(cha, samesame)
	} else {
		for _, proc := range procs {
			cha = daisyInt(cha, proc)
		}
	}
	return cha
}

// intDaisyChaiN returns a channel to receive all inp
// after having passed
// `somany` times
// thru the process(es) (`from` right `into` left)
// before close.
//
// Note: If `somany` is less than 1 or no `tubes` are provided,
// `out` shall receive elements from `inp` unaltered (as a convenience),
// thus making null values useful.
//
// Note: intDaisyChaiN(inp, 1, procs) <==> intDaisyChain(inp, procs)
func intDaisyChaiN(
	inp chan int, // a daisy to be chained
	somany int, // how many times? so many times
	procs ...func(out chan<- int, inp <-chan int), // a process function
) (
	out chan int, // to receive all results
) { //  Body:

	cha := inp

	if somany < 1 {
		samesame := func(out chan<- int, inp <-chan int) {
			// `out <- <-inp` or `into <- <-from`
			defer close(out)
			for i := range inp {
				out <- i
			}
		}
		cha = daisyInt(cha, samesame)
	} else {
		for i := 0; i < somany; i++ {
			cha = intDaisyChain(cha, procs...)
		}
	}
	return cha
}

// End of intDaisyChain
// ===========================================================================

repository: GoLangsam/pipe

repo_name: GoLangsam/pipe

gha_language: Go

extension: go


text:
package cmd

import (
	"github.com/bnch/bancho/common"
	"github.com/bnch/bancho/models"
	"github.com/codegangsta/cli"
	"github.com/jinzhu/gorm"
)

// MkUser puts an user in the database.
func MkUser(c *cli.Context) {
	if !checkConf() {
		return
	}
	a := c.Args()
	user := a[0]
	pass := a[1]
	var err error
	var db *gorm.DB
	db, err = models.CreateDB()
	if err != nil {
		panic(err)
	}
	pass = common.CryptPass(pass)
	db.Create(&models.User{
		Username:    user,
		Password:    pass,
		Permissions: models.PermissionAdmin,
	})
}

repository: Noromon/bancho

repo_name: Noromon/bancho


text:
package main

import (
	"encoding/json"
	"fmt"
	"os"
	"strings"
)

const (
	group           = "argoproj.io"
	version         = "v1alpha1"
	eventBusKind    = "EventBus"
	eventSourceKind = "EventSource"
	sensorKind      = "Sensor"
)

type obj = map[string]interface{}

func main() {
	swagger := obj{}
	{
		f, err := os.Open("api/openapi-spec/swagger.json")
		if err != nil {
			panic(err)
		}
		err = json.NewDecoder(f).Decode(&swagger)
		if err != nil {
			panic(err)
		}
	}
	{
		crdKinds := []string{
			eventBusKind,
			eventSourceKind,
			sensorKind,
		}
		definitions := swagger["definitions"]
		oneOf := make([]obj, 0, len(crdKinds))
		for _, kind := range crdKinds {
			lowerCaseKind := strings.ToLower(kind)
			definitionKey := fmt.Sprintf("io.argoproj.%s.%s.%s", lowerCaseKind, version, kind)
			v := definitions.(obj)[definitionKey].(obj)
			v["x-kubernetes-group-version-kind"] = []obj{
				{
					"group":   group,
					"kind":    kind,
					"version": version,
				},
			}
			props := v["properties"].(obj)
			props["apiVersion"].(obj)["const"] = fmt.Sprintf("%s/%s", group, version)
			props["kind"].(obj)["const"] = kind
			oneOf = append(oneOf, obj{"$ref": "#/definitions/" + definitionKey})
		}

		transformInt64OrStringDefinition(definitions.(obj))
		transformK8sIntOrStringDefinitions(definitions.(obj))

		schema := obj{
			"$id":         "http://events.argoproj.io/events.json",
			"$schema":     "http://json-schema.org/schema#",
			"type":        "object",
			"oneOf":       oneOf,
			"definitions": definitions,
		}
		f, err := os.Create("api/jsonschema/schema.json")
		if err != nil {
			panic(err)
		}

		e := json.NewEncoder(f)
		e.SetIndent("", "  ")
		err = e.Encode(schema)
		if err != nil {
			panic(err)
		}

		err = f.Close()
		if err != nil {
			panic(err)
		}
	}
}

func transformInt64OrStringDefinition(definitions obj) {
	int64OrStringDefinition := definitions["io.argoproj.common.Int64OrString"].(obj)
	int64OrStringDefinition["type"] = []string{
		"integer",
		"string",
	}
}

func transformK8sIntOrStringDefinitions(definitions obj) {
	for _, d := range definitions {
		transformK8sIntOrStringTypesInObject(d.(obj))
	}
}

func transformK8sIntOrStringTypesInObject(object obj) {
	props, ok := object["properties"].(obj)
	if !ok {
		format, ok := object["format"].(string)
		if ok && format == "int-or-string" {
			object["type"] = []string{
				"integer",
				"string",
			}
		}
		return
	}

	for _, prop := range props {
		transformK8sIntOrStringTypesInObject(prop.(obj))
	}
}

repository: argoproj/argo-events

repo_name: argoproj/argo-events


text:
import { IMailroomEmailOutbound } from '@tamu-gisc/mailroom/common';

export type StrapiSingleTypes =
  | 'home'
  | 'found-a-bug'
  | 'map'
  | 'team'
  | 'faq'
  | 'knowledge'
  | 'contact'
  | 'navigation'
  | 'funder'
  | 'footer';

export type IStrapiLocales = 'en' | 'es';

export type IStrapiComponent =
  | IStrapiMedia
  | IStrapiPageSection
  | IStrapiPageInfoAlert
  | IStrapiPageFeature
  | IStrapiPageGallery
  | IStrapiPagePrintResource
  | IStrapiPageParagraph
  | IStrapiPageList;

export interface IStrapiMediaFormat {
  name: string;
  hash: string;
  ext: string;
  mime: string;
  width: number;
  height: number;
  size: number;
  path: string;
  url: string;
}

export interface IStrapiMedia extends IStrapiMediaFormat {
  __component?: string;
  id: number;
  alternativeText: string;
  caption: string;
  previewUrl: string;
  provider: string;
  provider_metadata: string;
  created_at: string;
  updated_at: string;
  formats: {
    thumbnail: IStrapiMediaFormat;
    large: IStrapiMediaFormat;
    medium: IStrapiMediaFormat;
    small: IStrapiMediaFormat;
  };
}

export interface IStrapiPageSection {
  __component: string;
  id: number;
  title: string;
  text: string;
}

export interface IStrapiPageInfoBlock {
  __component: string;
  id: number;
  title: string;
  subtitle: string;
  text: string;
  type: 'h1' | 'h2' | 'h3';
  anchor?: string;
}

export interface IStrapiPageInfoAlert {
  __component: string;
  id: number;
  text: string;
  file: IStrapiMedia;
  preview: IStrapiMedia;
}

export interface IStrapiPageFeature {
  __component: string;
  id: number;
  credit: string;
  caption: string;
  media: IStrapiMedia;
}

export interface IStrapiPagePortrait {
  __component: string;
  id: number;
  site: string;
  name: string;
  bio: string;
  education: string;
  media: IStrapiMedia;
}

export interface IStrapiPageGallery {
  __component: string;
  id: number;
  credit: string;
  caption: string;
  items: IStrapiPageFeature[];
}

export interface IStrapiPagePortraitGallery {
  __component: string;
  id: number;
  credit: string;
  caption: string;
  portraits: IStrapiPagePortrait[];
}

export interface IStrapiPageParagraph {
  __component: string;
  id: number;
  text: string;
}

export interface IStrapiPageList {
  __component: string;
  id: number;
  list_items: IStrapiPageParagraph[];
}

export interface IStrapiTableRow {
  __component: string;
  id: number;
  species: string;
  location: string;
  numTested: number;
  numInfected: number;
  percent: number;
}

export interface IStrapiTable {
  __component: string;
  id: number;
  data: IStrapiTableRow[];
  header: string[];
}

export interface IStrapiPrintResource {
  __component: string;
  id: number;
  file: IStrapiMedia;
  fileName: string;
  preview: IStrapiMedia;
}

export interface IStrapiPrintGallery {
  __component: string;
  id: number;
  resources: IStrapiPrintResource[];
}

export interface IStrapiPublication {
  __component: string;
  id: number;
  citation: string;
  quote: string;
  link: string;
}

export interface IStrapiPublicationGallery {
  __component: string;
  id: number;
  publications: IStrapiPublication[];
}

export interface IStrapiLocale {
  id: number;
  locale: string;
  published_at: string;
}

export interface IStrapiStapleHero {
  id: number;
  titles: IStrapiPageParagraph[];
  statement: string;
  left_icon: IStrapiMedia;
  right_icon: IStrapiMedia;
  background: IStrapiMedia;
  fa_icon: string;
}

export interface IStrapiFooterItem {
  id: number;
  title: string;
  value: string;
}
export interface IStrapiStapleFooter {
  id: number;
  year: IStrapiFooterItem;
  contact: IStrapiFooterItem;
  disclaimer: IStrapiFooterItem;
}

export interface IStrapiStapleFunder {
  id: number;
  text: string;
  image: IStrapiMedia;
}

export interface IStrapiNavigationItem {
  id: number;
  page: string;
  title: string;
}

export interface IStrapiNavigationPage {
  id: number;
  items: IStrapiNavigationItem[];
}
export interface IStrapiStapleNavigation {
  id: number;
  published_at: string;
  created_at: string;
  updated_at: string;
  items: (IStrapiNavigationItem | IStrapiNavigationPage)[];
}

export interface IStrapiPagePrintResource {
  __component: string;
  id: number;
  fileName: string;
  file: IStrapiMedia;
}

export interface IStrapiFAQItem {
  __component?: string;
  id: number;
  text: string;
  section: number;
}

export interface IStrapiFAQItemsWithComponents {
  __component?: string;
  questions: IStrapiFAQItem[];
  sections: IStrapiPageSection[];
}

export interface IStrapiPageFAQComponent {
  __component?: string;
  sectionId: number;
  text: string;
  components: IStrapiComponent[];
}

export interface IStrapiPageResponse {
  id: number;
  locale: IStrapiLocales;
  published_at: string;
  created_at: string;
  updated_at: string;
  hero: IStrapiStapleHero;
  section: IStrapiComponent[];
  questions: IStrapiFAQItem[];
  footer: IStrapiStapleFooter;
  localizations: IStrapiLocale[];
}

export interface IContactBugSubmission extends IMailroomEmailOutbound {
  firstName: string;
  lastName: string;
  message: string;
  dateOfEncounter: string;
  timeOfEncounter: string;
  locationOfEncounter: string;
  stateOfEncounter: string;
  associatedWithBite: string;
  behaviour: string;
  file1: string;
  file2: string;
}

export interface IStrapiBugRecord {
  id: number;
  month: string;
  countyFips: string;
  species: string;
  created_at: string;
  updated_at: string;
}

export interface GeoJSONFeatureCollection {
  type: string;
  features: GeoJSONFeature[];
}

export interface GeoJSONFeature {
  type: string;
  properties: { [key: string]: string | boolean | number };
  geometry: GeoJSONPolygonFeature | GeoJSONMultiPolygonFeature;
}

export interface GeoJSONMultiPolygonFeature {
  coordinates: number[][][][];
  type: 'MultiPolygon';
}

export interface GeoJSONPolygonFeature {
  coordinates: number[][];
  type: 'Polygon';
}

export interface IStrapiBugCount {
  FIPS: string;
  Count: number;
}

branch_name: refs/heads/development

gha_language: TypeScript

extension: ts


text:
//
//  CompoPhotoQuad.h
//  CompoView
//
//  Created by Didiet Noor on 19/02/14.
//  Copyright (c) 2014 YKode Studio. All rights reserved.
//

#ifndef COMPO_PHOTO_QUAD
#define COMPO_PHOTO_QUAD
#include "CompoTypes.h"

class CompoPhotoQuad
{
  friend class CompoEffect;
private:
  union {
      GLuint mGPUBuffers[2];
    struct {
      GLuint mVBO;
      GLuint mIBO;
    };
  };
  COMPO_UNIQUE<CompoTexture> mTexture;
  void initialize();
  CompoPhotoQuad( const CompoPhotoQuad &);
public:
  CompoPhotoQuad();
  CompoPhotoQuad(const CompoImage &);
  virtual ~CompoPhotoQuad();

  void setImage( const CompoImage &);

  void drawWithEffect( const CompoEffect &effect ) const;
};

#endif /* defined(__CompoView__CompoPhotoQuad__) */

extension: h


text:
import {
  pick,
} from 'lodash'

import {
  Controller,
  Use,
  Post,
  Body,
  File,
  Ctx,
} from '../utils//trafficlight'

import * as fs from 'fs-extra'
import * as path from 'path'

import models from '../models'
import jwt from '../middlewares/jwt'
import { tmp } from '../utils/const'

const keys = Object.keys(models.upload.schema.obj)

@Controller('/upload')
@Use(jwt())
export default class UploadController {

  @Post('/')
  public async create (
    @File() file,
    @Body() body,
    @Ctx() ctx,
  ): Promise<string> {
    ctx.assert(file, 400, '文件不能为空')

    // 复制到另一个位置
    const { hash, type } = file
    const [ , dir1, dir2, rest ] = hash.match(/^(.)(..)(.*)$/)
    const destDir = path.join(tmp, dir1, dir2)
    await fs.ensureDir(destDir)
    const fileName = rest + type.split('/')[1]
    const dest = path.join(destDir, fileName)
    const reader = fs.createReadStream(file.path)
    const stream = fs.createWriteStream(dest)
    reader.pipe(stream)

    // 移除旧文件
    await fs.remove(file.path)

    // 保存记录
    const picked = pick(file, keys) as any
    picked.hash = dir1 + dir2 + fileName
    picked.originHash = file.hash
    picked.path = dest

    const upload = await models.upload.findOne({
      hash: picked.hash
    })
    if (!upload) {
      await models.upload.create(picked)
    }

    return picked.hash
  }
}

repository: liril-net/ufaas

repo_name: liril-net/ufaas


text:
package form_test

import (
	. "github.com/YanshuoH/youkonger/forms"

	"bytes"
	"github.com/YanshuoH/youkonger/consts"
	"github.com/YanshuoH/youkonger/dao"
	"github.com/YanshuoH/youkonger/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("ParticipantUser", func() {
	var event models.Event
	var user models.User
	var participateUser models.ParticipantUser
	BeforeEach(func() {
		e := models.Event{
			Title: "a titile",
		}
		Expect(dao.GetManager().Create(&e).Error).ToNot(HaveOccurred())
		event = e

		u := models.User{}
		Expect(dao.GetManager().Create(&u).Error).ToNot(HaveOccurred())
		user = u

		pu := models.ParticipantUser{
			Name:    "someone",
			EventID: e.ID,
			UserID:  u.ID,
		}
		Expect(dao.GetManager().Create(&pu).Error).ToNot(HaveOccurred())
		participateUser = pu
	})
	Describe("ParticipantUserForm", func() {
		Context("Without entity manager in form", func() {
			It("Should return an error", func() {
				f := ParticipantUserForm{}
				res, cErr := f.Handle()
				Expect(cErr.Code).To(Equal(consts.NoEntityManagerInForm))
				Expect(res).To(BeNil())
			})
		})

		Context("With name length too long", func() {
			It("Should return an error", func() {
				var nameBuf bytes.Buffer
				nameLength := consts.NameLengthConstraint + 1
				for i := 0; i < nameLength; i++ {
					nameBuf.WriteString("吼")
				}
				f := ParticipantUserForm{
					EM:        dao.GetManager(),
					EventUUID: "abc",
					Name:      nameBuf.String(),
				}
				res, cErr := f.Handle()
				Expect(cErr.Code).To(Equal(consts.NameTooLong))
				Expect(res).To(BeNil())
			})
		})

		Context("With unexisted event uuid", func() {
			It("Should return an error", func() {
				f := ParticipantUserForm{
					EM:        dao.GetManager(),
					EventUUID: "abc",
				}
				res, cErr := f.Handle()
				Expect(cErr.Code).To(Equal(consts.EventNotFound))
				Expect(res).To(BeNil())
			})
		})

		Context("With defined user uuid but unexisted", func() {
			It("Should return an error", func() {
				f := ParticipantUserForm{
					EM:        dao.GetManager(),
					EventUUID: event.UUID,
					UserUUID:  "abc",
				}
				res, cErr := f.Handle()
				Expect(cErr.Code).To(Equal(consts.UserNotFound))
				Expect(res).To(BeNil())
			})
		})

		Context("With correct update form", func() {
			It("Should update the participate user", func() {
				f := ParticipantUserForm{
					EM:        dao.GetManager(),
					EventUUID: event.UUID,
					UserUUID:  user.UUID,
					Name:      "anotherone",
				}
				res, cErr := f.Handle()
				Expect(cErr).To(BeNil())
				Expect(res.Name).To(Equal(f.Name))
				Expect(res.UUID).To(Equal(participateUser.UUID))
				Expect(res.User).ToNot(BeNil())
				Expect(res.Event).ToNot(BeNil())
			})
		})

		Context("With correct insertion form", func() {
			It("Should insert a participate user", func() {
				By("User not exists yet")
				var initialUserCount int
				var initialParticipateUserCount int
				dao.Conn.Raw("SELECT count(id) FROM user").Row().Scan(&initialUserCount)
				dao.Conn.Raw("SELECT count(id) FROM participant_user").Row().Scan(&initialParticipateUserCount)

				f := ParticipantUserForm{
					EM:        dao.GetManager(),
					EventUUID: event.UUID,
					Name:      "thatuser",
				}
				res, cErr := f.Handle()
				Expect(cErr).To(BeNil())
				Expect(res.Name).To(Equal(f.Name))
				Expect(res.Event).ToNot(BeNil())
				Expect(res.User).ToNot(BeNil())

				var finalUserCount int
				var finalParticipateUserCount int
				dao.Conn.Raw("SELECT count(id) FROM user").Row().Scan(&finalUserCount)
				dao.Conn.Raw("SELECT count(id) FROM participant_user").Row().Scan(&finalParticipateUserCount)

				Expect(finalUserCount).To(Equal(initialUserCount + 1))
				Expect(finalParticipateUserCount).To(Equal(initialParticipateUserCount + 1))
			})

			It("Should insert a participate user", func() {
				By("User already exists")
				// create another user
				u := models.User{}
				Expect(dao.GetManager().Create(&u).Error).ToNot(HaveOccurred())
				f := ParticipantUserForm{
					EM:        dao.GetManager(),
					EventUUID: event.UUID,
					UserUUID:  u.UUID,
					Name:      "thatuser",
				}

				var initialUserCount int
				var initialParticipateUserCount int
				dao.Conn.Raw("SELECT count(id) FROM user").Row().Scan(&initialUserCount)
				dao.Conn.Raw("SELECT count(id) FROM participant_user").Row().Scan(&initialParticipateUserCount)

				res, cErr := f.Handle()
				Expect(cErr).To(BeNil())
				Expect(res.Name).To(Equal(f.Name))
				Expect(res.Event).ToNot(BeNil())
				Expect(res.User).ToNot(BeNil())

				var finalUserCount int
				var finalParticipateUserCount int
				dao.Conn.Raw("SELECT count(id) FROM user").Row().Scan(&finalUserCount)
				dao.Conn.Raw("SELECT count(id) FROM participant_user").Row().Scan(&finalParticipateUserCount)

				Expect(finalUserCount).To(Equal(initialUserCount))
				Expect(finalParticipateUserCount).To(Equal(initialParticipateUserCount + 1))
			})
		})
	})
})

repository: YanshuoH/youkonger-backend

repo_name: YanshuoH/youkonger-backend


text:
SECTION = "devel/chicken"
DESCRIPTION = "The SLIB character plotting library"
LICENSE = "BSD"
LIC_FILES_CHKSUM = "file://charplot.meta;md5=4074581ce9f9b88f359662c1dfc36c9d"
DEPENDS_append_class-cross = " chicken-egg-numbers-cross chicken-egg-srfi-63-cross"
DEPENDS_append_class-crosssdk = " chicken-egg-numbers-crosssdk chicken-egg-srfi-63-crosssdk"
DEPENDS_append_class-nativesdk = " nativesdk-chicken-egg-numbers nativesdk-chicken-egg-srfi-63 chicken-egg-numbers-crosssdk chicken-egg-srfi-63-crosssdk"
DEPENDS = " chicken-egg-numbers chicken-egg-srfi-63 chicken-egg-numbers-cross chicken-egg-srfi-63-cross"
RDEPENDS_${PN} = " chicken-egg-numbers chicken-egg-srfi-63"

SRC_URI = "http://code.call-cc.org/egg-tarballs/4/charplot/charplot-${PV}.tar.gz"

SRC_URI[md5sum] = "1f6dcec46b4fd1f331d99df91e35b502"
SRC_URI[sha256sum] = "37f0ba3437ab6f795f5dab55936275376173c07ed4baafde5e684a237d44f95a"

S = "${WORKDIR}/charplot-${PV}"

inherit chicken_install

BBCLASSEXTEND = "cross crosssdk nativesdk"

repository: OSSystems/meta-chicken

repo_name: OSSystems/meta-chicken


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace SwitcheoTrader.NetCore.Entities
{
    public class CancelTradeParams
    {
        public string symbol { get; set; }
        public string Id { get; set; }
        public long timestamp { get; set; }
        public string type { get; set; }
    }
}

extension: cs


text:
#include "gtest/gtest.h"
#include "multiarr.hpp"
#include <algorithm>

using namespace libecpint;

class FiveIndexTest : public testing::Test {
protected:
	FiveIndex<double> matrix_;

	void SetUp() override {
		matrix_ = FiveIndex<double>(2, 9, 3, 7, 5);
		std::fill(matrix_.data.begin(), matrix_.data.end(), -0.7);
	}
};

TEST_F(FiveIndexTest, Accessor) {
	EXPECT_DOUBLE_EQ(matrix_(1, 1, 1, 2, 4), -0.7);
	matrix_(1, 1, 1, 2, 4) = 5.4;
	EXPECT_DOUBLE_EQ(matrix_(1, 1, 1, 2, 4), 5.4);
	EXPECT_DOUBLE_EQ(matrix_(0, 3, 1, 4, 2), -0.7);
}

TEST_F(FiveIndexTest, CopyCtor) {
	FiveIndex<double> tmp;
	EXPECT_EQ(tmp.dims[0], 0);
	EXPECT_EQ(tmp.dims[1], 0);
	EXPECT_EQ(tmp.dims[2], 0);
	EXPECT_EQ(tmp.dims[3], 0);
	EXPECT_EQ(tmp.dims[4], 0);

	tmp = matrix_;
	EXPECT_EQ(tmp.dims[0], 2);
	EXPECT_EQ(tmp.dims[1], 9);
	EXPECT_EQ(tmp.dims[2], 3);
	EXPECT_EQ(tmp.dims[3], 7);
	EXPECT_EQ(tmp.dims[4], 5);

	tmp(0, 1, 1, 4, 3) = 4.9;
	EXPECT_DOUBLE_EQ(tmp(0, 1, 1, 4, 3), 4.9);
	EXPECT_DOUBLE_EQ(matrix_(0, 0, 2, 1, 4), -0.7);
}

extension: cpp


text:
//
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//

package utilization

import (
	"errors"
	"fmt"
)

type kubernetes struct {
	KubernetesServiceHost string `json:"kubernetes_service_host",omitempty`

	// Having a custom getter allows the unit tests to mock os.Getenv().
	environmentVariableGetter func(key string) string
}

func GatherKubernetes(v *vendors, getenv func(string) string) error {
	k8s := newKubernetes(getenv)
	if err := k8s.Gather(); err != nil {
		return fmt.Errorf("Kubernetes not detected: %s", err)
	} else {
		if k8s.KubernetesServiceHost != "" {
			v.Kubernetes = k8s
		}
	}

	return nil
}

func newKubernetes(getenv func(string) string) *kubernetes {
	return &kubernetes{
		environmentVariableGetter: getenv,
	}
}

func (k8s *kubernetes) Gather() error {
	k8s.KubernetesServiceHost = k8s.environmentVariableGetter("KUBERNETES_SERVICE_HOST")

	if err := k8s.validate(); err != nil {
		return err
	}

	return nil
}

func (k8s *kubernetes) validate() (err error) {
	k8s.KubernetesServiceHost, err = normalizeValue(k8s.KubernetesServiceHost)
	if err != nil {
		return fmt.Errorf("Invalid Kubernetes Service Host: %v", err)
	}

	if k8s.KubernetesServiceHost == "" {
		err = errors.New("The environment variable KUBERNETES_SERVICE_HOST was unavailable")
	}
	return
}

repository: newrelic/newrelic-php-agent

repo_name: newrelic/newrelic-php-agent

branch_name: refs/heads/main

gha_language: C