text:
#include <stdio.h>
#include <stdlib.h>

#include "ida_impl.h"
#include "ida_spils_impl.h"

/* Private constants */

#define ZERO   RCONST(0.0)
#define PT25   RCONST(0.25)
#define PT05   RCONST(0.05)
#define ONE    RCONST(1.0)

/* Algorithmic constants */

#define MAX_ITERS  3  /* max. number of attempts to recover in DQ J*v */

/* Readability Replacements */

#define lrw1      (IDA_mem->ida_lrw1)
#define liw1      (IDA_mem->ida_liw1)
#define tn        (IDA_mem->ida_tn)
#define cj        (IDA_mem->ida_cj)
#define res       (IDA_mem->ida_res)
#define user_data (IDA_mem->ida_user_data)
#define ewt       (IDA_mem->ida_ewt)
#define lmem      (IDA_mem->ida_lmem)

#define ils_type  (idaspils_mem->s_type)
#define sqrtN     (idaspils_mem->s_sqrtN)
#define epslin    (idaspils_mem->s_epslin)
#define ytemp     (idaspils_mem->s_ytemp)
#define yptemp    (idaspils_mem->s_yptemp)
#define xx        (idaspils_mem->s_xx)
#define ycur      (idaspils_mem->s_ycur)
#define ypcur     (idaspils_mem->s_ypcur)
#define rcur      (idaspils_mem->s_rcur)
#define npe       (idaspils_mem->s_npe)
#define nli       (idaspils_mem->s_nli)
#define nps       (idaspils_mem->s_nps)
#define ncfl      (idaspils_mem->s_ncfl)
#define njtimes   (idaspils_mem->s_njtimes)
#define nres      (idaspils_mem->s_nres)

#define jtimesDQ  (idaspils_mem->s_jtimesDQ)
#define jtimes    (idaspils_mem->s_jtimes)
#define jdata     (idaspils_mem->s_jdata)

#define last_flag (idaspils_mem->s_last_flag)

/*
 * -----------------------------------------------------------------
 * OPTIONAL INPUT and OUTPUT
 * -----------------------------------------------------------------
 */

int IDASpilsSetGSType(void *ida_mem, int gstype)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsSetGSType", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsSetGSType", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  if (ils_type != SPILS_SPGMR) {
    IDAProcessError(IDA_mem, IDASPILS_ILL_INPUT, "IDASPILS", "IDASpilsSetGSType", MSGS_BAD_LSTYPE);
    return(IDASPILS_ILL_INPUT);
  }

  /* Check for legal gstype */
  if ((gstype != MODIFIED_GS) && (gstype != CLASSICAL_GS)) {
    IDAProcessError(IDA_mem, IDASPILS_ILL_INPUT, "IDASPILS", "IDASpilsSetGSType", MSGS_BAD_GSTYPE);
    return(IDASPILS_ILL_INPUT);
  }

  idaspils_mem->s_gstype = gstype;

  return(IDASPILS_SUCCESS);
}

int IDASpilsSetMaxRestarts(void *ida_mem, int maxrs)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsSetMaxRestarts", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsSetMaxRestarts", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  if (ils_type != SPILS_SPGMR) {
    IDAProcessError(IDA_mem, IDASPILS_ILL_INPUT, "IDASPILS", "IDASpilsSetMaxRestarts", MSGS_BAD_LSTYPE);
    return(IDASPILS_ILL_INPUT);
  }

  /* Check for legal maxrs */
  if (maxrs < 0) {
    IDAProcessError(IDA_mem, IDASPILS_ILL_INPUT, "IDASPILS", "IDASpilsSetMaxRestarts", MSGS_NEG_MAXRS);
    return(IDASPILS_ILL_INPUT);
  }

  idaspils_mem->s_maxrs = maxrs;

  return(IDASPILS_SUCCESS);
}

int IDASpilsSetMaxl(void *ida_mem, int maxl)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsSetMaxl", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsSetMaxl", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  if (ils_type == SPILS_SPGMR) {
    IDAProcessError(IDA_mem, IDASPILS_ILL_INPUT, "IDASPILS", "IDASpilsSetMaxl", MSGS_BAD_LSTYPE);
    return(IDASPILS_ILL_INPUT);
  }

  idaspils_mem->s_maxl = (maxl <= 0) ? IDA_SPILS_MAXL : maxl;

  return(IDASPILS_SUCCESS);
}

int IDASpilsSetEpsLin(void *ida_mem, realtype eplifac)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsSetEpsLin", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsSetEpsLin", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  /* Check for legal maxrs */
  if (eplifac < ZERO) {
    IDAProcessError(IDA_mem, IDASPILS_ILL_INPUT, "IDASPILS", "IDASpilsSetEpsLin", MSGS_NEG_EPLIFAC);
    return(IDASPILS_ILL_INPUT);
  }

  if (eplifac == ZERO)
    idaspils_mem->s_eplifac = PT05;
  else
    idaspils_mem->s_eplifac = eplifac;

  return(IDASPILS_SUCCESS);
}

int IDASpilsSetIncrementFactor(void *ida_mem, realtype dqincfac)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsSetIncrementFactor", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsSetIncrementFactor", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  /* Check for legal maxrs */
  if (dqincfac <= ZERO) {
    IDAProcessError(IDA_mem, IDASPILS_ILL_INPUT, "IDASPILS", "IDASpilsSetIncrementFactor", MSGS_NEG_DQINCFAC);
    return(IDASPILS_ILL_INPUT);
  }

  idaspils_mem->s_dqincfac = dqincfac;

  return(IDASPILS_SUCCESS);
}

int IDASpilsSetPreconditioner(void *ida_mem,
                              IDASpilsPrecSetupFn pset, IDASpilsPrecSolveFn psolve)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsSetPreconditioner", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsSetPreconditioner", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  idaspils_mem->s_pset = pset;
  idaspils_mem->s_psolve = psolve;

  return(IDASPILS_SUCCESS);
}

int IDASpilsSetJacTimesVecFn(void *ida_mem, IDASpilsJacTimesVecFn jtv)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsSetJacTimesVecFn", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsSetJacTimesVecFn", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  if (jtv != NULL) {
    jtimesDQ = FALSE;
    jtimes = jtv;
  } else {
    jtimesDQ = TRUE;
  }

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetWorkSpace(void *ida_mem, long int *lenrwLS, long int *leniwLS)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;
  int maxl;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetWorkSpace", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetWorkSpace", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  switch(ils_type) {
  case SPILS_SPGMR:
    maxl = idaspils_mem->s_maxl;
    *lenrwLS = lrw1*(maxl + 6) + maxl*(maxl + 4) + 1;
    *leniwLS = liw1*(maxl + 6);
    break;
  case SPILS_SPBCG:
    *lenrwLS = lrw1 * 10;
    *leniwLS = liw1 * 10;
    break;
  case SPILS_SPTFQMR:
    *lenrwLS = lrw1*13;
    *leniwLS = liw1*13;
    break;
  }

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetNumPrecEvals(void *ida_mem, long int *npevals)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetNumPrecEvals", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetNumPrecEvals", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  *npevals = npe;

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetNumPrecSolves(void *ida_mem, long int *npsolves)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetNumPrecSolves", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetNumPrecSolves", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  *npsolves = nps;

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetNumLinIters(void *ida_mem, long int *nliters)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetNumLinIters", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetNumLinIters", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  *nliters = nli;

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetNumConvFails(void *ida_mem, long int *nlcfails)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetNumConvFails", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetNumConvFails", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  *nlcfails = ncfl;

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetNumJtimesEvals(void *ida_mem, long int *njvevals)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetNumJtimesEvals", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetNumJtimesEvals", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  *njvevals = njtimes;

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetNumResEvals(void *ida_mem, long int *nrevalsLS)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetNumResEvals", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetNumResEvals", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  *nrevalsLS = nres;

  return(IDASPILS_SUCCESS);
}

int IDASpilsGetLastFlag(void *ida_mem, long int *flag)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;

  /* Return immediately if ida_mem is NULL */
  if (ida_mem == NULL) {
    IDAProcessError(NULL, IDASPILS_MEM_NULL, "IDASPILS", "IDASpilsGetLastFlag", MSGS_IDAMEM_NULL);
    return(IDASPILS_MEM_NULL);
  }
  IDA_mem = (IDAMem) ida_mem;

  if (lmem == NULL) {
    IDAProcessError(IDA_mem, IDASPILS_LMEM_NULL, "IDASPILS", "IDASpilsGetLastFlag", MSGS_LMEM_NULL);
    return(IDASPILS_LMEM_NULL);
  }
  idaspils_mem = (IDASpilsMem) lmem;

  *flag = last_flag;

  return(IDASPILS_SUCCESS);
}

char *IDASpilsGetReturnFlagName(long int flag)
{
  char *name;

  name = (char *)malloc(30*sizeof(char));

  switch(flag) {
  case IDASPILS_SUCCESS:
    sprintf(name,"IDASPILS_SUCCESS");
    break;
  case IDASPILS_MEM_NULL:
    sprintf(name,"IDASPILS_MEM_NULL");
    break;
  case IDASPILS_LMEM_NULL:
    sprintf(name,"IDASPILS_LMEM_NULL");
    break;
  case IDASPILS_ILL_INPUT:
    sprintf(name,"IDASPILS_ILL_INPUT");
    break;
  case IDASPILS_MEM_FAIL:
    sprintf(name,"IDASPILS_MEM_FAIL");
    break;
  case IDASPILS_PMEM_NULL:
    sprintf(name,"IDASPILS_PMEM_NULL");
    break;
  default:
    sprintf(name,"NONE");
  }

  return(name);
}

/*
 * -----------------------------------------------------------------
 * IDASPILS private functions
 * -----------------------------------------------------------------
 */

#define psolve   (idaspils_mem->s_psolve)
#define pdata    (idaspils_mem->s_pdata)
#define dqincfac (idaspils_mem->s_dqincfac)

/*
 * This routine generates the matrix-vector product z = Jv, where
 * J is the system Jacobian, by calling either the user provided
 * routine or the internal DQ routine.
 */

int IDASpilsAtimes(void *ida_mem, N_Vector v, N_Vector z)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;
  int jtflag;

  IDA_mem = (IDAMem) ida_mem;
  idaspils_mem = (IDASpilsMem) lmem;

  jtflag = jtimes(tn, ycur, ypcur, rcur, v, z, cj, jdata, ytemp, yptemp);
  njtimes++;

  return(jtflag);
}

/*
 * This routine interfaces between the generic Solve routine and
 * the user's psolve routine.  It passes to psolve all required state
 * information from ida_mem.  Its return value is the same as that
 * returned by psolve.  Note that the generic solver guarantees
 * that IDASilsPSolve will not be called in the case psolve = NULL.
 */

int IDASpilsPSolve(void *ida_mem, N_Vector r, N_Vector z, int lr)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;
  int retval;

  IDA_mem = (IDAMem) ida_mem;
  idaspils_mem = (IDASpilsMem) lmem;

  retval = psolve(tn, ycur, ypcur, rcur, r, z, cj, epslin, pdata, ytemp);

  /* This call is counted in nps within the IDASp**Solve routine */

  return(retval);

}

/*
 * This routine generates the matrix-vector product z = Jv, where
 * J is the system Jacobian, by using a difference quotient approximation.
 * The approximation is
 *      Jv = [F(t,y1,yp1) - F(t,y,yp)]/sigma,  where
 *        y1 = y + sigma*v,  yp1 = yp + cj*sigma*v,
 *        sigma = sqrt(Neq)*dqincfac.
 * The return value from the call to res is saved in order to set the
 * return flag from IDASp**Solve.
 */

int IDASpilsDQJtimes(realtype tt,
                     N_Vector yy, N_Vector yp, N_Vector rr,
                     N_Vector v, N_Vector Jv,
                     realtype c_j, void *data,
                     N_Vector work1, N_Vector work2)
{
  IDAMem IDA_mem;
  IDASpilsMem idaspils_mem;
  N_Vector y_tmp, yp_tmp;
  realtype sig=ZERO, siginv;
  int iter, retval;

  /* data is ida_mem */
  IDA_mem = (IDAMem) data;
  idaspils_mem = (IDASpilsMem) lmem;

  switch(ils_type) {
  case SPILS_SPGMR:
    sig = sqrtN*dqincfac;
    break;
  case SPILS_SPBCG:
    sig = dqincfac/N_VWrmsNorm(v, ewt);
    break;
  case SPILS_SPTFQMR:
    sig = dqincfac/N_VWrmsNorm(v, ewt);
    break;
  }

  /* Rename work1 and work2 for readibility */
  y_tmp  = work1;
  yp_tmp = work2;

  for (iter=0; iter<MAX_ITERS; iter++) {

    /* Set y_tmp = yy + sig*v, yp_tmp = yp + cj*sig*v. */
    N_VLinearSum(sig, v, ONE, yy, y_tmp);
    N_VLinearSum(c_j*sig, v, ONE, yp, yp_tmp);

    /* Call res for Jv = F(t, y_tmp, yp_tmp), and return if it failed. */
    retval = res(tt, y_tmp, yp_tmp, Jv, user_data);
    nres++;
    if (retval == 0) break;
    if (retval < 0)  return(-1);

    sig *= PT25;
  }

  if (retval > 0) return(+1);

  /* Set Jv to [Jv - rr]/sig and return. */
  siginv = ONE/sig;
  N_VLinearSum(siginv, Jv, -siginv, rr, Jv);

  return(0);

}


text:
#!/usr/bin/python
# -*- coding: utf-8  -*-
import os
import sys, logging
import pywikibot
import csv
import MySQLdb as mdb
from MySQLdb import cursors
import traceback
import re
import time
import argparse
import utils
import pdb

NOW = time.strftime("%Y_%m_%d_%H_%M")
OUT_DIR_LOGS = os.path.expanduser('~/logs')
OUT_DIR = os.path.expanduser('~/outputs/All_Template_Users/data_11_24_2014/')

'''
Reads the language code file and return a list of language codes
'''
def getLanguageCodes(file_name):
	"""
	Read language code from csv file and return a list of laguage codes
	This is the 286 languages in current wikipedia.
	"""
	try:
		lang_code_file = open(file_name, 'r')
		lang_code = lang_code_file.read().splitlines()
		lang_code_file.close()
		reversed_lang_list = list(reversed(lang_code))
		return reversed_lang_list
	except IOError as e:
		logging.error('unable to open language code file:')
		logging.error(str(e))

'''
Reads the pipe seperated dialect codes from the file and return as a list.
'''
def getDialectCodes(file_name):
	"""
	Read iso code file that with double pipe delimiter replace the the double pipe
	with single and returns the generator. Generator gets thrown into the csvreader
	which returns iterable object (list)
	"""
	dialect_codes = set()
	d_pipe_file_handle = open(file_name, 'r')
	csv_reader = csv.reader((line.replace('||', '|') for line in d_pipe_file_handle), delimiter='|')
	for row in csv_reader:
		dialect_codes.add(row[0])
	return dialect_codes

'''
Create the logger
'''
def create_logger(logger, logLang):
	log_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
	file_handler = logging.FileHandler(filename=(os.path.join(OUT_DIR_LOGS, logLang + '-babel_Users.log')))
	file_handler.setFormatter(log_format)
	logger.setLevel(logging.INFO)
	logger.addHandler(file_handler)

class CollectUsersWithTemplate():

	def __init__(self, language, limit):
		self.disconnect_database()
		#self.con = None
		#self.cur = None
		#self.con2 = None
		#self.cur2 = None
		self.language = language
		#self.connect_database()
		self.cur = utils.connect_database(self.language)
		self.limit = limit
		if self.language == 'ho' or self.language == 'aa' or self.language == 'cho' or self.language == 'ng':
			self.translatedString = ur'''User'''
		elif self.language =='it':
			self.translatedString = ur'''Utenti'''
		elif self.language == 'es':
			self.translatedString = ur'''Wikipedia:Wikipedistas\_con\_%'''
		elif self.language == 'ast':
			self.translatedString = ur'''Usuarios\_por\_idioma\_%'''
		elif self.language == 'ay':
			self.translatedString = ur'''Aru%'''
		elif self.language == 'ang':
			self.translatedString = u"Brūcend"
		elif self.language == 'ca':
			self.translatedString = u"Usuaris"
		else:
			self.translatedString = self.getTranslatedStringForUser()
		self.filename = os.path.join(OUT_DIR + self.language + '_data.csv')

	'''
	Make an api call to get the localized version of the word "user" for given language.
	'''
	def getTranslatedStringForUser(self):
		"""
		Gets the local namespace name for User pages. e.g. Bruker on no.

		Uses pywikibot.

		API method:
			https://no.wikipedia.org/w/api.php?action=query&meta=siteinfo
				 &siprop=namespaces&format=json
		"""
		try:
			logging.info("Fetching User Namespace Name")
			format_language = self.language
			if '_' in format_language:
				wikiSite = pywikibot.getSite(format_language.replace('_','-'))
			else:
				wikiSite = pywikibot.getSite(self.language)
			#print wikiSite
			r = pywikibot.data.api.Request(
				site=wikiSite, action="query", meta="siteinfo")
			r['siprop'] = u'namespaces'
			data = r.submit()
			if self.language == 'pt':
				localized_user = data['query']['namespaces']['2']['*']
				return localized_user.split('(')[0]
			else:
				return data['query']['namespaces']['2']['*']
		except pywikibot.exceptions.NoSuchSite, e:
			logging.error(e)
	"""
	def connect_database(self):
		try:
			format_lang_string = self.language.replace('-','_')
			db_name = format_lang_string+ 'wiki_p'
			self.con = mdb.connect(db=db_name, host=format_lang_string+"wiki.labsdb", read_default_file=os.path.expanduser("~/replica.my.cnf"),  cursorclass=mdb.cursors.SSDictCursor)
			logging.info("Connection Successful: " + str(self.con))
			self.cur = self.con.cursor()
		except mdb.Error, e:
			logging.error("Unable to establish connection")
		try:
			format_lang_string = self.language.replace('-','_')
			db_name2 = format_lang_string + 'wiki_p'
			self.con2 = mdb.connect(db=db_name2, host=format_lang_string+"wiki.labsdb", read_default_file=os.path.expanduser("~/replica.my.cnf"),  cursorclass=mdb.cursors.SSDictCursor)
			logging.info("Connection Successful: " + str(self.con2))
			self.cur2 = self.con2.cursor()
		except mdb.Error, e:
			logging.error("Unable to establish connection")
	"""

	def disconnect_database(self):
		try:
			self.cur.close()
			self.con.close()
			self.cur2.close()
			self.con2.close()
			logging.info("Successfully disconnect " + self.language)
		except:
			pass

	'''
	Given a specific language get all the flag bots and return as a list.
	At some point we are going to need another method to detect bots that are not flagged.
	'''
	def get_bot_users(self):
		logging.info("Getting bot users")
		bots = list()
		bot_query = ur'''SELECT /* SLOW_OK LIMIT: 1800 */ user_id from user JOIN user_groups ON user_id = ug_user where ug_group = 'bot' '''
		success = False
		attempts = 0
		while attempts < 3 and not success:
			try:
				self.cur.execute(bot_query)
				complete = False
				while not complete:
					row = self.cur.fetchone()
					if not row:
						complete = True
						continue
				#for row in self.cur:
					bots.append(row['user_id'])
				success = True
			except Exception, e:
				attempts += 1
				traceback.print_exc()
				logging.exception(e)
		return bots

	def get_spanish_lang_categories(self):
		'''
		Spanish wiki has non conventional cats so we first capture them to match it up later.
		'''
		logging.info("Getting the spanish categories")
		cat_query = ur'''SELECT /* SLOW_OK LIMIT: 1800 */ cl_to
							FROM page
							INNER JOIN categorylinks
							ON (page_id=cl_from)
							WHERE cl_to LIKE "Wikipedia:Wikipedistas_con_%"
							AND page_namespace=2 group by cl_to'''
		cats = list()
		success = False
		attempts = 0
		while attempts < 3 and not success:
			try:
				self.cur.execute(cat_query)
				complete = False
				while not complete:
					row = self.cur.fetchone()
					if not row:
						complete = True
						continue
					cats.append(row['cl_to'])
				success = True
			except Exception, e:
				attempts += 1
				traceback.print_exc()
				logging.exception(e)
		return cats

	'''
	Method that returns all the babel users that has the babel template.
	'''
	def get_babel_template_users(self):
		logging.info("Collecting babel users")
		babel_user_query = ur'''SELECT /*SLOW_OK LIMIT: 1800 */ page_id, page_title FROM page p JOIN templatelinks tl ON page_id=tl_from WHERE tl_title = 'Babel'
								AND tl.tl_namespace=10 and page_namespace = 2 {limit}'''
		bot_users = self.get_bot_users()
		success = False
		attempts = 0
		while attempts < 3 and not success:
			try:
				self.cur.execute(babel_user_query.format(limit = self.limit))
				for babel_user in self.cur.fetchall():
					print babel_user['page_id'], babel_user['page_title'], self.language
				success = True
			except Exception, e:
				attempts += 1
				traceback.print_exc()
				logging.exception(e)

	def get_templates_sub_user_pages(self, dialectList, ISOList, langList):
		logging.info("Processing users that has templates in sub user pages")

		spanish_lang_cats = None
		if self.language == 'es':
			spanish_lang_cats = self.get_spanish_lang_categories()

		### Regular expression to catch language codes
		lang_regx = re.compile(ur'(?P<locUserCat>\w+)[_]+(?P<lcode>\w+)[-]+(?P<level>[0-5\w])$', re.I | re.U)
		### Regular expression to catcch dialect codes
		dt_regx = re.compile(ur'(?P<locUserCat>\w+)[-]+(?P<dcode>\w+)[-]+(?P<level>[0-5\w])$', re.I | re.U)
		### user without proficiency level (Sometimes en-0 gets put in to just en category)
		lang_regx_short = re.compile(ur'(?P<locUserCat>\w+)[_]+(?P<lcode>\w+)$', re.I | re.U)

		# Example: http://no.wikipedia.org/wiki/Bruker:Axezz/Presentasjon
		subpage_user_query = ur'''SELECT /* SLOW_OK LIMIT: 1800 */
			page_title, page_id, cl_to, page_namespace
			FROM page
			INNER JOIN categorylinks
			ON (page_id=cl_from)
			WHERE cl_to LIKE "{localized_usr}\_%" OR cl_to LIKE "User\_%"
			AND page_namespace=2 {limit}'''.format(localized_usr=self.translatedString, limit=self.limit)
		#print subpage_user_query
		# get user id from user_name
		query_user_id = ur'''SELECT user_id from user where user_name = "{uName}"'''
		success = False
		attempts = 0
		user_name_template_dict = {}
		bot_users = self.get_bot_users()
		while attempts < 3 and not success:
			try:
				self.cur.execute(subpage_user_query.encode('utf-8'))
				complete = False
				while not complete:
					row = self.cur.fetchone()
					if not row:
						complete = True
						continue
					page_title = unicode(row['page_title'], 'utf-8')
					template_category = unicode(row['cl_to'], 'utf-8')
					page_namespace = int(row['page_namespace'])

					'''
					Matching the regular expression of dialect template and language template
					'''
					matched_template_object = lang_regx.match(template_category)
					matched_dialect_object = dt_regx.match(template_category)
					matched_template_no_prof = lang_regx_short.match(template_category)

					query_user_id = ur'''SELECT user_id FROM user WHERE user_name = %(uName)s'''
					if page_namespace == 2:
						user_name = page_title.split("/")[0]
						formatted_user_name = user_name.replace("_", " ")
						self.cur2.execute(query_user_id, {'uName':formatted_user_name.encode('utf-8')})
						u_id = self.cur2.fetchone()
						self.cur2.fetchall()
						if u_id is not None and u_id not in bot_users:
							if self.language == 'es':
								stript_template = template_category.split("Wikipedia:Wikipedistas_con_")
								if len(stript_template) > 1:
									set_template = stript_template[1]
								else:
									set_template = template_category
								if (u_id['user_id'],user_name) not in user_name_template_dict:
									user_name_template_dict[(u_id['user_id'], user_name)] = []
									user_name_template_dict[(u_id['user_id'], user_name)].append(set_template)
								else:
									user_name_template_dict[(u_id['user_id'], user_name)].append(set_template)
							elif self.language == 'ast':
								stript_template = template_category.split('Usuarios_por_idioma_-_')
								if len(stript_template) > 1:
									set_template = stript_template[1]
								else:
									set_template = template_category
								if (u_id['user_id'],user_name) not in user_name_template_dict:
									user_name_template_dict[(u_id['user_id'], user_name)] = []
									user_name_template_dict[(u_id['user_id'], user_name)].append(set_template)
								else:
									user_name_template_dict[(u_id['user_id'], user_name)].append(set_template)
							elif self.language == 'ay':
								stript_template = template_category.split("Aru:")
								if len(stript_template) > 1:
									set_template = stript_template[1]
								else:
									set_template = template_category
								if (u_id['user_id'],user_name) not in user_name_template_dict:
									user_name_template_dict[(u_id['user_id'], user_name)] = []
									user_name_template_dict[(u_id['user_id'], user_name)].append(set_template)
								else:
									user_name_template_dict[(u_id['user_id'], user_name)].append(set_template)
							#If template regex doesn't return None then we have a successful match -> Lets process
							elif matched_template_object is not None:
								matched_lang_code = matched_template_object.group('lcode')
								'''Check if the language codes are in the langauge code list and ISO list'''
								if matched_lang_code in langList or matched_lang_code in ISOList:
									stript_template = template_category.split("_")[1]
									if (u_id['user_id'],user_name) not in user_name_template_dict:
										user_name_template_dict[(u_id['user_id'], user_name)] = []
										user_name_template_dict[(u_id['user_id'], user_name)].append(stript_template)
									else:
										user_name_template_dict[(u_id['user_id'], user_name)].append(stript_template)
							elif matched_template_no_prof is not None:
								matched_lang_without_proficiency = matched_template_no_prof.group('lcode')
								if matched_lang_without_proficiency in langList or matched_lang_without_proficiency in ISOList:
									stript_template = template_category.split("_")[1]
									if (u_id['user_id'],user_name) not in user_name_template_dict:
										user_name_template_dict[(u_id['user_id'], user_name)] = []
										user_name_template_dict[(u_id['user_id'], user_name)].append(stript_template)
									else:
										user_name_template_dict[(u_id['user_id'], user_name)].append(stript_template)
							# Matching dialects
							elif matched_dialect_object is not None:
								matched_dialect_code = matched_dialect_object.group('dcode')
								if matched_dialect_code in dialectList:
									if (u_id['user_id'],user_name) not in user_name_template_dict:
										user_name_template_dict[(u_id['user_id'], user_name)] = []
										user_name_template_dict[(u_id['user_id'], user_name)].append(stript_template)
									else:
										user_name_template_dict[(u_id['user_id'], user_name)].append(stript_template)
						else:
							logging.info("User with " + user_name + " doesn't have a user_id or its a bot in wiki" + self.language)
					else:
						logging.info("In wiki-lang" + self.language + " " + page_title + " has template " + template_category + " and namespace is " + str(page_namespace))
				success = True
				#self.cur.fetchall()
			except Exception, e:
				attempts += 1
				traceback.print_exc()
				logging.exception(e)
			except mdb.OperationalError, ex:
				logging.info("=== Caught database gone away === ")
				logging.exception(ex)
				self.disconnect_database()
				self.connect_database()
		return user_name_template_dict

	def get_all_template_users(self):
		logging.info("Collecting all template users")

		### Regular expression to catch language codes
		lang_regx = re.compile(ur'(?P<locUserCat>\w+)[_]+(?P<lcode>\w+)[-]+(?P<level>[0-5\w])$', re.I | re.U)
		### Regular expression to catcch dialect codes
		dt_regx = re.compile(ur'(?P<locUserCat>\w+)[-]+(?P<dcode>\w+)[-]+(?P<level>[0-5\w])$', re.I | re.U)
		### user without proficiency level (Sometimes en-0 gets put in to just en category)
		lang_regx_short = re.compile(ur'(?P<locUserCat>\w+)[_]+(?P<lcode>\w+)$', re.I | re.U)

		upperlanguage = self.language[0].upper() + self.language[1:]
		upperlanguage = unicode(upperlanguage, 'utf-8')

		if self.language == 'nl':
			template_user_query =  ur'''SELECT /* SLOW_OK LIMIT: 1800 */ user_id, user_name, cl_to
				FROM page
				INNER JOIN categorylinks ON (page_id=cl_from)
				INNER JOIN user ON REPLACE(page_title, "_"," ") = user_name
				WHERE (cl_to LIKE "{User}\_%" OR cl_to LIKE "User\_%")
				AND page_namespace=2 {limit}'''.format(limit=self.limit, User="Wikipedia:"+self.translatedString)
		elif self.language == 'ay':
			template_user_query =  ur'''SELECT /* SLOW_OK LIMIT: 1800 */ user_id, user_name, cl_to
				FROM page
				INNER JOIN categorylinks ON (page_id=cl_from)
				INNER JOIN user ON REPLACE(page_title, "_"," ") = user_name
				WHERE (cl_to LIKE "{User}" OR cl_to LIKE "User\_%")
				AND page_namespace=2 {limit}'''.format(limit=self.limit, User=self.translatedString)
		else:
			template_user_query =  ur'''SELECT /* SLOW_OK LIMIT: 1800 */ user_id, user_name, cl_to
				FROM page
				INNER JOIN categorylinks ON (page_id=cl_from)
				INNER JOIN user ON REPLACE(page_title, "_"," ") = user_name
				WHERE (cl_to LIKE "{User}\_%" OR cl_to LIKE "User\_%")
				AND page_namespace=2 {limit}'''.format(limit=self.limit, User=self.translatedString)

		#print template_user_query
		### Read the pipe file to get all the dialect codes and conver them to unicoded list
		pipe_file = os.path.expanduser('~/template_data/lang_codes/ISO-639-2.csv')
		dialect_list = getDialectCodes(pipe_file)
		unicode_dialect_list = [unicode(x, 'utf-8') for x in dialect_list]

		# Convert Langauge List to unicode
		file_path = os.path.expanduser('~/template_data/lang_codes/wiki_lang2_codes.csv')
		all_lang_codes = getLanguageCodes(file_path)
		unicoded_list = [unicode(x, 'utf-8') for x in all_lang_codes]

		# Get ISO Codes
		iso_file_path = os.path.expanduser('~/template_data/lang_codes/iso_lang_codes.csv')
		iso_list = getLanguageCodes(iso_file_path)
		unicode_iso_list = [unicode(x, 'utf-8') for x in iso_list]

		try:
			sub_page_user_dictionary = self.get_templates_sub_user_pages(unicode_dialect_list, unicode_iso_list, unicoded_list)
		except AttributeError, e:
			logging.exception(e)

		data_file = open(self.filename, "wt")
		bot_users = self.get_bot_users()
		success = False
		attempts = 0
		with open(os.path.expanduser(self.filename), 'w+') as data_file:
			writer = csv.writer(data_file)
			writer.writerow(('user_id', 'user_name', 'template'))
			if sub_page_user_dictionary:
				logging.info("---+ writing subpage users dictionary +---")
				for key, values in sub_page_user_dictionary.iteritems():
					for value in  values:
						try:
							writer.writerow((key[0], key[1].encode('utf-8'), value.encode('utf-8')))
						except Exception, e:
							logging.error("Something went wrong in writing user_id " + str(key[0]) + " " + self.language)
			while attempts < 3 and not success:
				try:
					self.cur.execute(template_user_query.encode('utf-8'))
					complete = False
					while not complete:
						row = self.cur.fetchone()
						if not row:
							complete = True
							continue
						#for row in self.cur:
						if row['user_id'] not in bot_users:
							uID = row['user_id']
							template_category = unicode(row['cl_to'], 'utf-8')
							### Matching the language codes regular expression
							### nl has word wikipedia infront of the template, we could write regex to pick that then
							### we might end up picking up garbage from other languages.
							matched_template_object = None
							matched_template_no_prof = None
							if self.language =='nl':
								matched_template_object = lang_regx.match(template_category.split(":")[1])
								# Add the condition as a data cleanup during if we capture en-1 we don't need to capture en without level
								# Some languages native is consider as just the main lang code ex: en-N is equivalent to en
								if matched_template_object is None:
									matched_template_no_prof = lang_regx_short.match(template_category.split(":")[1])
							else:
								matched_template_object = lang_regx.match(template_category)
								matched_template_no_prof = lang_regx_short.match(template_category)

							## if the language is nl we have already match the template so we can create a record in the csv.
							if matched_template_object is not None:
								matched_lang_code = matched_template_object.group('lcode')
								if matched_lang_code in unicoded_list or matched_lang_code in unicode_iso_list:
									user_name = unicode(row['user_name'], 'utf-8')
									template_code = unicode(row['cl_to'], 'utf-8')
									writer.writerow((row['user_id'], user_name.encode('utf-8'), template_code.encode('utf-8')))

							''' Matching dialect code regular expression '''
							matched_dialect_object = dt_regx.match(template_category)
							if matched_dialect_object is not None:
								matched_dialect_code = matched_dialect_object.group('dcode')
								if matched_dialect_code in unicode_dialect_list:
									user_name = unicode(row['user_name'], 'utf-8')
									template_code = unicode(row['cl_to'], 'utf-8')
									writer.writerow((row['user_id'], user_name.encode('utf-8'), template_code.encode('utf-8')))

							if matched_template_no_prof is not None:
								matched_lang_without_proficiency = matched_template_no_prof.group('lcode')
								if matched_lang_without_proficiency in unicoded_list or matched_lang_without_proficiency in unicode_iso_list:
									user_name = unicode(row['user_name'], 'utf-8')
									template_code = unicode(row['cl_to'], 'utf-8')
									writer.writerow((row['user_id'], user_name.encode('utf-8'), template_code.encode('utf-8')))

							if self.language == 'es':
								if uID not in sub_page_user_dictionary:
									user_name = unicode(row['user_name'], 'utf-8')
									template_code = unicode(row['cl_to'], 'utf-8')
									if "Wikipedia:Wikipedistas_con_" in template_code:
										stript_template = template_code.split("Wikipedia:Wikipedistas_con_")[1]
										writer.writerow((row['user_id'], user_name.encode('utf-8'), stript_template.encode('utf-8')))
									else:
										print template_code
										writer.writerow((row['user_id'], user_name.encode('utf-8'), template_code.encode('utf-8')))

							if self.language == 'ast':
								if uID not in sub_page_user_dictionary:
									user_name = unicode(row['user_name'], 'utf-8')
									template_code = unicode(row['cl_to'], 'utf-8')
									if "Usuarios_por_idioma_-_" in template_code:
										stript_template = template_code.split("Usuarios_por_idioma_-_")[1]
										writer.writerow((row['user_id'], user_name.encode('utf-8'), stript_template.encode('utf-8')))
									else:
										print template_code
										logging.info(row['user_id'], self.language)
										writer.writerow((row['user_id'], user_name.encode('utf-8'), template_code.encode('utf-8')))

							if self.language == 'ay':
								if uID not in sub_page_user_dictionary:
									user_name = unicode(row['user_name'], 'utf-8')
									template_code = unicode(row['cl_to'], 'utf-8')
									if "Aru:" in template_code:
										stript_template = template_code.split("Aru:")[1]
										writer.writerow((row['user_id'], user_name.encode('utf-8'), stript_template.encode('utf-8')))
									else:
										print template_code
										writer.writerow((row['user_id'], user_name.encode('utf-8'), template_code.encode('utf-8')))
							if self.language == 'ang':
								if uID not in sub_page_user_dictionary:
									user_name = unicode(row['user_name'], 'utf-8')
									template_code = unicode(row['cl_to'], 'utf-8')
									stript_template = template_code.split(u"_")[1]
									writer.writerow((row['user_id'], user_name.encode('utf-8'), stript_template.encode('utf-8')))
						else:
							logging.info(str(row['user_id']) + " is a bot " + " wiki " + self.language)
					success = True
				except Exception, e:
					attempts += 1
					traceback.print_exc()
					logging.exception(e)
				except mdb.OperationalError, ex:
					logging.info("==== Database Gone away ====")
					logging.exception(ex)
					self.disconnect_database()
					self.connect_database

def main():
	log = logging.getLogger()

	parser = argparse.ArgumentParser()
	parser.add_argument('-f','--file', type=str, help='which language file to read in as data collection', required=True)
	parser.add_argument('-l', '--limit', default='')
	args = vars(parser.parse_args())

	create_logger(log, args['file'])

	# Multiple options to pick the list of languages
	if args['file'] == 'test':
		language_list = getLanguageCodes(os.path.expanduser("~/template_data/lang_codes/test_lang.csv"))
	elif args['file'] == 'top50':
		language_list = getLanguageCodes(os.path.expanduser("~/template_data/lang_codes/top_50_langs.csv"))
	elif args['file'] == 'second50':
		language_list = getLanguageCodes(os.path.expanduser("~/template_data/lang_codes/second_50_langs.csv"))
	elif args['file'] == 'after100':
		language_list = getLanguageCodes(os.path.expanduser("~/template_data/lang_codes/after_100_langs.csv"))
	elif args['file'] == 'all':
		language_list = getLanguageCodes(os.path.expanduser("~/template_data/lang_codes/wiki_lang_codes_latest.csv"))

	# During the testing use pass limit to the query
	for language_code in language_list:
		limit = None
		if args['limit'] != '':
			limit = 'limit ' + args['limit']
		else:
			limit = args['limit']
		babelUsers = CollectUsersWithTemplate(language_code, limit)
		babelUsers.get_all_template_users()

if __name__=="__main__":
	main()

redpajama_set_name: RedPajamaGithub


text:
<?php
use ODataProducer\UriProcessor\ResourcePathProcessor\SegmentParser\KeyDescriptor;
use ODataProducer\Providers\Metadata\ResourceSet;
use ODataProducer\Providers\Metadata\ResourceProperty;
use ODataProducer\Providers\Query\IDataServiceQueryProvider;
require_once ("NorthWindMetadata.php");
require_once ("ODataProducer\Providers\Query\IDataServiceQueryProvider.php");
define('DATABASE', 'Northwind');
define('SERVER', '.\sqlexpress');

class NorthWindQueryProvider implements IDataServiceQueryProvider
{
    /**
     * Handle to connection to Database
     */
    private $_connectionHandle = null;

    /**
     * Constructs a new instance of NorthWindQueryProvider
     *
     */
    public function __construct()
    {
        $this->_connectionHandle = sqlsrv_connect(SERVER, array("Database"=> DATABASE));
        if( $this->_connectionHandle ) {
        } else {
             die( print_r( sqlsrv_errors(), true));
        }
    }

    /**
     * Gets collection of entities belongs to an entity set
     *
     * @param ResourceSet $resourceSet The entity set whose entities needs to be fetched
     *
     * @return array(Object)
     */
    public function getResourceSet(ResourceSet $resourceSet)
    {
        $resourceSetName =  $resourceSet->getName();
        if ($resourceSetName !== 'Customers' &&
        $resourceSetName !== 'Orders' &&
        $resourceSetName !== 'Order_Details' &&
        $resourceSetName !== 'Products' &&
        $resourceSetName !== 'Employees') {
            die('(NorthWindQueryProvider) Unknown resource set ' . $resourceSetName);
        }

        if ($resourceSetName === 'Order_Details') {
            $resourceSetName = 'Order Details';
        }

        $query = "SELECT * FROM [$resourceSetName]";
        $stmt = sqlsrv_query($this->_connectionHandle, $query);
        if( $stmt === false) {
             die( print_r( sqlsrv_errors(), true));
        }

        $returnResult = array();
        switch ($resourceSetName) {
            case 'Customers':
                $returnResult = $this->_serializeCustomers($stmt);
                break;
            case 'Orders':
                $returnResult = $this->_serializeOrders($stmt);
                break;
            case 'Order Details':
                $returnResult = $this->_serializeOrder_Details($stmt);
                break;
            /**case 'Products':
                $returnResult = $this->_serializeProducts($stmt);
                break;*/
            case 'Employees':
                $returnResult = $this->_serializeEmployees($stmt);
                break;
        }

        sqlsrv_free_stmt($stmt);
        return $returnResult;
    }

    /**
     * Gets an entity instance from an entity set identifed by a key
     *
     * @param ResourceSet $resourceSet     The entity set from which an entity needs to be fetched
     * @param KeyDescriptor $keyDescriptor The key to identify the entity to be fetched
     *
     * @return Object/NULL Returns entity instance if found else null
     */
    public function getResourceFromResourceSet(ResourceSet $resourceSet, KeyDescriptor $keyDescriptor)
    {
        $resourceSetName =  $resourceSet->getName();
        if ($resourceSetName !== 'Customers' &&
        $resourceSetName !== 'Orders' &&
        $resourceSetName !== 'Order_Details' &&
        $resourceSetName !== 'Products' &&
        $resourceSetName !== 'Employees') {
            die('(NorthWindQueryProvider) Unknown resource set ' . $resourceSetName);
        }

        if ($resourceSetName === 'Order_Details') {
            $resourceSetName = 'Order Details';
        }

        $namedKeyValues = $keyDescriptor->getValidatedNamedValues();
        $condition = null;
        foreach ($namedKeyValues as $key => $value) {
            $condition .= $key . ' = ' . $value[0] . ' and ';
        }

        $len = strlen($condition);
        $condition = substr($condition, 0, $len - 5);
        $query = "SELECT * FROM [$resourceSetName] WHERE $condition";
        $stmt = sqlsrv_query($this->_connectionHandle, $query);
        if( $stmt === false) {
             die( print_r( sqlsrv_errors(), true));
        }

        //If resource not found return null to the library
        if (!sqlsrv_has_rows($stmt)) {
            return null;
        }

        $result = null;
        while( $record = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
            switch ($resourceSetName) {
                case 'Customers':
                    $result = $this->_serializeCustomer($record);
                    break;
                case 'Orders':
                    $result = $this->_serializeOrder($record);
                    break;
                /**case 'Order Details':
                    $result = $this->_serializeOrder_Detail($record);
                    break;
                case 'Products':
                    $result = $this->_serializeProduct($record);
                    break;**/
                case 'Employees':
                    $result = $this->_serializeEmployee($record);
                    break;
            }
        }

        sqlsrv_free_stmt($stmt);
        return $result;
    }

    public function  getResourceFromRelatedResourceSet(ResourceSet $sourceResourceSet,
        $sourceEntityInstance,
        ResourceSet $targetResourceSet,
        ResourceProperty $targetProperty,
        KeyDescriptor $keyDescriptor
    ) {
        $result = array();
        /**$srcClass = get_class($sourceEntityInstance);
        $navigationPropName = $targetProperty->getName();
        $key = null;
        foreach ($keyDescriptor->getValidatedNamedValues() as $keyName => $valueDescription) {
            $key = $key . $keyName . '=' . $valueDescription[0] . ' and ';
        }

        $key = rtrim($key, ' and ');
        if ($srcClass === 'Customer') {
            if ($navigationPropName === 'Orders') {
                $query = "SELECT * FROM Orders WHERE CustomerID = '$sourceEntityInstance->CustomerID' and $key";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeOrders($stmt);
            } else {
                die('Customer does not have navigation porperty with name: ' . $navigationPropName);
            }
        } else if ($srcClass === 'Order') {
             if ($navigationPropName === 'Order_Details') {
                $query = "SELECT * FROM [Order Details] WHERE OrderID = $sourceEntityInstance->OrderID";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeOrder_Details($stmt);
            } else {
                die('Order does not have navigation porperty with name: ' . $navigationPropName);
            }
        } else if ($srcClass === 'Product') {
             if ($navigationPropName === 'Order_Details') {
                $query = "SELECT * FROM [Order Details] WHERE ProductID = $sourceEntityInstance->ProductID  and $key";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeOrder_Details($stmt);
            } else {
                die('Order does not have navigation porperty with name: ' . $navigationPropName);
            }
        } else if ($srcClass === 'Employee') {
             if ($navigationPropName === 'Subordinates') {
                $query = "SELECT * FROM Employees WHERE ReportsTo = $sourceEntityInstance->EmployeeID  and $key";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeEmployees($stmt);
            } else {
                die('Order does not have navigation porperty with name: ' . $navigationPropName);
            }
        }**/

        return empty($result) ? null : $result[0];

    }

    /**
     * TODO
     *
     * @return array(Objects)/array() Array of related resource if exists, if no related resources found returns empty array
     */
    public function  getRelatedResourceSet(ResourceSet $sourceResourceSet,
        $sourceEntityInstance,
        ResourceSet $targetResourceSet,
        ResourceProperty $targetProperty
    ){
        $result = array();
        $srcClass = get_class($sourceEntityInstance);
        $navigationPropName = $targetProperty->getName();
        if ($srcClass === 'Customer') {
            if ($navigationPropName === 'Orders') {
                $query = "SELECT * FROM Orders WHERE CustomerID = '$sourceEntityInstance->CustomerID'";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeOrders($stmt);
            } else {
                die('Customer does not have navigation porperty with name: ' . $navigationPropName);
            }
        } else if ($srcClass === 'Order') {
             if ($navigationPropName === 'Order_Details') {
                $query = "SELECT * FROM [Order Details] WHERE OrderID = $sourceEntityInstance->OrderID";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeOrder_Details($stmt);
            } else {
                die('Order does not have navigation porperty with name: ' . $navigationPropName);
            }
        } /**else if ($srcClass === 'Product') {
             if ($navigationPropName === 'Order_Details') {
                $query = "SELECT * FROM [Order Details] WHERE ProductID = $sourceEntityInstance->ProductID";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeOrder_Details($stmt);
            } else {
                die('Order does not have navigation porperty with name: ' . $navigationPropName);
            }
        } else if ($srcClass === 'Employee') {
             if ($navigationPropName === 'Subordinates') {
                $query = "SELECT * FROM Employees WHERE ReportsTo = $sourceEntityInstance->EmployeeID";
                $stmt = sqlsrv_query($this->_connectionHandle, $query);
                if( $stmt === false) {
                     die( print_r( sqlsrv_errors(), true));
                }

                $result = $this->_serializeEmployees($stmt);
            } else {
                die('Order does not have navigation porperty with name: ' . $navigationPropName);
            }
        }**/

        return $result;
    }

    /**
     * TODO
     *
     * @return Object/null
     */
    public function getRelatedResourceReference(ResourceSet $sourceResourceSet,
        $sourceEntityInstance,
        ResourceSet $targetResourceSet,
        ResourceProperty $targetProperty
    )
    {
        $result = null;
        $srcClass = get_class($sourceEntityInstance);
        $navigationPropName = $targetProperty->getName();
        if ($srcClass === 'Order') {
            if ($navigationPropName === 'Customer') {
                if (empty($sourceEntityInstance->CustomerID)) {
                    $result = null;
                } else {
                    $query = "SELECT * FROM Customers WHERE CustomerID = '$sourceEntityInstance->CustomerID'";
                    $stmt = sqlsrv_query($this->_connectionHandle, $query);
                    if( $stmt === false) {
                         die( print_r( sqlsrv_errors(), true));
                    }

                    if (!sqlsrv_has_rows($stmt)) {
                        $result =  null;
                    }

                    $result = $this->_serializeCustomer(sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC));
                }
            } else {
                die('Customer does not have navigation porperty with name: ' . $navigationPropName);
            }
        } /**else if ($srcClass === 'Order_Details') {
             if ($navigationPropName === 'Order') {
                if (empty($sourceEntityInstance->OrderID)) {
                    $result = null;
                } else {
                    $query = "SELECT * FROM Orders WHERE OrderID = $sourceEntityInstance->OrderID";
                    $stmt = sqlsrv_query($this->_connectionHandle, $query);
                    if( $stmt === false) {
                         die( print_r( sqlsrv_errors(), true));
                    }

                    if (!sqlsrv_has_rows($stmt)) {
                        $result =  null;
                    }

                    $result = $this->_serializeOrder(sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC));
                }
            } else if ($navigationPropName === 'Product') {
                if (empty($sourceEntityInstance->ProductID)) {
                    $result =  null;
                } else {
                    $query = "SELECT * FROM Products WHERE ProductID = $sourceEntityInstance->ProductID";
                    $stmt = sqlsrv_query($this->_connectionHandle, $query);
                    if( $stmt === false) {
                         die( print_r( sqlsrv_errors(), true));
                    }

                    if (!sqlsrv_has_rows($stmt)) {
                        $result =  null;
                    }

                    $result = $this->_serializeProduct(sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC));
                }
            } else {
                die('Order_Details does not have navigation porperty with name: ' . $navigationPropName);
            }
        } else if ($srcClass === 'Employee') {
             if ($navigationPropName === 'Manager') {
                if (empty($sourceEntityInstance->ReportsTo)) {
                    $result =  null;
                } else {
                    $query = "SELECT * FROM Employees WHERE EmployeeID = $sourceEntityInstance->ReportsTo";
                    $stmt = sqlsrv_query($this->_connectionHandle, $query);
                    if( $stmt === false) {
                         die( print_r( sqlsrv_errors(), true));
                    }

                   if (!sqlsrv_has_rows($stmt)) {
                        $result =  null;
                    }

                    $result = $this->_serializeEmployee(sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC));
                }
            } else {
                die('Order does not have navigation porperty with name: ' . $navigationPropName);
            }
        }**/

        return $result;
    }

    /**
     * Serialize the sql result array into Customer objects
     *
     * @param array(array) $result
     *
     * @return array(Object)
     */
    private function _serializeCustomers($result)
    {
        $customers = array();
        while( $record = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
        {
             $customers[] = $this->_serializeCustomer($record);
        }

        return $customers;
    }

    /**
     * Serialize the sql row into Customer object
     *
     * @param array $record
     *
     * @return Object
     */
    private function _serializeCustomer($record)
    {
        $customer = new Customer();
        $customer->CustomerID = $record['CustomerID'];
        $customer->CompanyName = $record['CompanyName'];
        $customer->ContactName = $record['ContactName'];
        $customer->ContactTitle = $record['ContactTitle'];
        $customer->Phone = $record['Phone'];
        $customer->Fax = $record['Fax'];
        $customer->Address = new Address();
        $customer->Address->StreetName = ($record['Address']);
        $customer->Address->City = $record['City'];
        $customer->Address->Region = $record['Region'];
        $customer->Address->PostalCode = $record['PostalCode'];
        $customer->Address->Country = $record['Country'];
        //Set alternate address
        $customer->Address->AltAddress = new Address();
        $customer->Address->AltAddress->StreetName = 'ALT_' . $customer->Address->StreetName;
        $customer->Address->AltAddress->City = 'ALT_' . $customer->Address->City;
        $customer->Address->AltAddress->Region = 'ALT_' . $customer->Address->Region;
        $customer->Address->AltAddress->PostalCode = 'ALT_' . $customer->Address->PostalCode;
        $customer->Address->AltAddress->Country = 'ALT_' . $customer->Address->Country;
        $customer->EmailAddresses = array();
        for ($i = 1; $i < 4; $i++) {
            $customer->EmailAddresses[] = $customer->CustomerID . $i . '@live.com';
        }

        $customer->OtherAddresses = array();
        for ($i = 0; $i < 2; $i++) {
            $customer->OtherAddresses[$i] = new Address();
            $this->copyAddress($customer->Address, $customer->OtherAddresses[$i], $i + 1);
        }

        //TODO Start Temp Code for testing
        /**$query = "SELECT * FROM Orders WHERE CustomerID = '$customer->CustomerID'";
		$stmt = sqlsrv_query($this->_connectionHandle, $query);
		if( $stmt === false) {
			die( print_r( sqlsrv_errors(), true));
		}

		$result = $this->_serializeOrders($stmt);
		$customer->Orders = $result;
		if (is_array($customer->Orders)) {
			foreach ($customer->Orders as &$orders) {
				$orders->Customer = unserialize(serialize($customer));
				$orders->Customer->Orders = null;
			}
		}**/
		//TODO End Temp Code for testing

        return $customer;
    }

    private function copyAddress(&$src, &$target, $tag)
    {
        $target->StreetName = $src->StreetName . $tag;
        $target->City = $src->City . $tag;
        $target->Region = $src->Region . $tag;
        $target->PostalCode = $src->PostalCode . $tag;
        $target->Country = $src->Country . $tag;

        $target->AltAddress = new Address();
        $target->AltAddress->StreetName = $target->AltAddress->StreetName . $tag;
        $target->AltAddress->City = $target->AltAddress->City . $tag;
        $target->AltAddress->Region = $target->AltAddress->Region . $tag;
        $target->AltAddress->PostalCode = $target->AltAddress->PostalCode . $tag;
        $target->AltAddress->Country = $target->AltAddress->Country . $tag;
    }

    /**
     * Serialize the sql result array into Order objects
     *
     * @param array(array) $result
     *
     * @return array(Object)
     */
    private function _serializeOrders($result)
    {
        $orders = array();
        while( $record = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
        {
             $orders[] = $this->_serializeOrder($record);
        }

        return $orders;
    }

    /**
     * Serialize the sql row into Order object
     *
     * @param array $record
     *
     * @return Object
     */
    private function _serializeOrder($record)
    {
        $order = new Order();
        $order->OrderID = $record['OrderID'];
		$order->CustomerID = $record['CustomerID'];
		$order->EmployeeID = $record['EmployeeID'];
		$order->OrderDate = !is_null($record['OrderDate']) ? $record['OrderDate']->format('Y-m-d H:i:s'): null;
		$order->RequiredDate = !is_null($record['RequiredDate']) ? $record['RequiredDate']->format('Y-m-d H:i:s'): null;
		$order->ShippedDate = !is_null($record['ShippedDate']) ? $record['ShippedDate']->format('Y-m-d H:i:s'): null;
		$order->ShipVia = $record['ShipVia'];
		$order->Freight = $record['Freight'];
		$order->ShipName = $record['ShipName'];
		$order->ShipAddress = $record['ShipAddress'];
		$order->ShipCity = $record['ShipCity'];
		$order->ShipRegion = $record['ShipRegion'];
		$order->ShipPostalCode = $record['ShipPostalCode'];
		$order->ShipCountry = $record['ShipCountry'];
        return $order;
    }

    /**
     * Serialize the sql result array into Employee objects
     *
     * @param array(array) $result
     *
     * @return array(Object)
     */
    private function _serializeEmployees($result)
    {
        $employees = array();
        while( $record = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
        {
             $employees[] = $this->_serializeEmployee($record);
        }

        return $employees;
    }

    /**
     * Serialize the sql row into Employee object
     *
     * @param array $record
     *
     * @return Object
     */
    private function _serializeEmployee($record)
    {
        $employee = new Employee();
        $employee->EmployeeID = $record['EmployeeID'];
        $employee->FirstName = $record['FirstName'];
        $employee->LastName = $record['LastName'];
        $employee->Title = $record['Title'];
        $employee->TitleOfCourtesy = $record['TitleOfCourtesy'];
        $employee->BirthDate = !is_null($record['BirthDate']) ? $record['BirthDate']->format('Y-m-d H:i:s'): null;
        $employee->HireDate = !is_null($record['HireDate']) ? $record['HireDate']->format('Y-m-d H:i:s'): null;
        $employee->Address = $record['Address'];
        $employee->City = $record['City'];
        $employee->Region = $record['Region'];
        $employee->PostalCode = $record['PostalCode'];
        $employee->Country = $record['Country'];
        $employee->HomePhone = $record['HomePhone'];
        $employee->Extension = $record['Extension'];
        $employee->Notes = $record['Notes'];
        $employee->ReportsTo = $record['ReportsTo'];
       // $employee->Photo = $record['Photo'];
        $employee->Emails = array ($employee->FirstName . '@hotmail.com', $employee->FirstName . '@live.com');
        return $employee;
    }

    /**
     * Serialize the sql result array into Order_Details objects
     *
     * @param array(array) $result
     *
     * @return array(Object)
     */
   private function _serializeOrder_Details($result)
    {
        $order_details = array();
        while( $record = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
        {
            $order_details[] = $this->_serializeOrder_Detail($record);
        }

        return $order_details;
    }

    /**
     * Serialize the sql row into Order_Details object
     *
     * @param array $record
     *
     * @return Object
     */
    private function _serializeOrder_Detail($record)
    {
        $order_details = new Order_Details();
        $order_details->Discount = $record['Discount'];
        $order_details->OrderID = $record['OrderID'];
        $order_details->ProductID = $record['ProductID'];
        $order_details->Quantity = $record['Quantity'];
        $order_details->UnitPrice = $record['UnitPrice'];
        return $order_details;
    }

    /**
     * Serialize the sql result array into Product objects
     *
     * @param array(array) $result
     *
     * @return array(Object)
     */
    /**private function _serializeProducts($result)
    {
        $products = array();
        while( $record = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
        {
             $products[] = $this->_serializeProduct($record);
        }

        return $products;
    }**/

    /**
     * Serialize the sql row into Product object
     *
     * @param array $record
     *
     * @return Object
     */
    /**private function _serializeProduct($record)
    {
        $product = new Product();
        $product->ProductID = $record['ProductID'];
        $product->ProductName = $record['ProductName'];
        $product->UnitPrice =  $record['UnitPrice'];
        $product->UnitsInStock = $record['UnitsInStock'];
        $product->UnitsOnOrder = $record['UnitsOnOrder'];
        return $product;
    }**/

    /**
     * The destructor
     */
    public function __destruct()
    {
        if ($this->_connectionHandle) {
			sqlsrv_close($this->_connectionHandle);
        }
    }
}
?>


text:
LaunchFile::LaunchFile(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::LaunchFile)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::WindowMinimizeButtonHint|Qt::CustomizeWindowHint);
}

LaunchFile::~LaunchFile()
{
    delete ui;
}

void LaunchFile::on_pushButton_add_button_clicked()
{
    QString filename = QFileDialog::getOpenFileName(this,"Open the file","/home");
    ui->listWidget->addItem(filename);

}

void LaunchFile::on_pushButton_delete_button_clicked()
{

}

void LaunchFile::on_pushButton_close_button_clicked()
{
    this->close();
}


text:
package com.amazonaws.services.applicationautoscaling.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ServiceNamespace {

    Ecs("ecs"),
    Elasticmapreduce("elasticmapreduce"),
    Ec2("ec2"),
    Appstream("appstream");

    private String value;

    private ServiceNamespace(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ServiceNamespace corresponding to the value
     */
    public static ServiceNamespace fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ServiceNamespace enumEntry : ServiceNamespace.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
class cHorse :
	public cPassiveMonster
{
	typedef cPassiveMonster super;

public:
	cHorse(int Type, int Color, int Style, int TameTimes);

	CLASS_PROTODEF(cHorse)

	virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = nullptr) override;
	virtual void Tick(std::chrono::milliseconds a_Dt, cChunk & a_Chunk) override;
	virtual void OnRightClicked(cPlayer & a_Player) override;

	bool IsSaddled      (void) const  {return m_bIsSaddled; }
	bool IsChested      (void) const  {return m_bHasChest; }
	bool IsEating       (void) const  {return m_bIsEating; }
	bool IsRearing      (void) const  {return m_bIsRearing; }
	bool IsMthOpen      (void) const  {return m_bIsMouthOpen; }
	bool IsTame         (void) const  {return m_bIsTame; }
	int  GetHorseType   (void) const  {return m_Type; }
	int  GetHorseColor  (void) const  {return m_Color; }
	int  GetHorseStyle  (void) const  {return m_Style; }
	int  GetHorseArmour (void) const  {return m_Armour;}

private:

	bool m_bHasChest, m_bIsEating, m_bIsRearing, m_bIsMouthOpen, m_bIsTame, m_bIsSaddled;
	int m_Type, m_Color, m_Style, m_Armour, m_TimesToTame, m_TameAttemptTimes, m_RearTickCount;

} ;


text:
package edu.umass.cs.iesl.author_coref.data_structures

import cc.factorie.util.Cubbie
import edu.umass.cs.iesl.author_coref._

trait HTMLFormatting {

  def toHTMLFormattedString: String
}

trait CubbieWithHTMLFormatting extends Cubbie with HTMLFormatting {
  /**
   * Creates an HTML formatted string *
   * @return
   */
  def toHTMLFormattedString: String = {
    val sb = new StringBuilder(1000)
    sb.append("\n
")
    sb.append(s"${this.getClass.ordinaryName}
")
    sb.append(HTMLFormatMap(this._map))
    sb.append("\n
")
    sb.toString()
  }

  /**
   * Helper method to generate the HTML strings
   * @param map
   * @return
   */
  protected def HTMLFormatMap(map: scala.collection.Map[String,Any]): String = {
    val sb = new StringBuilder(1000)
    sb.append(s"\n
")
    map.foreach{
      case (key, value) =>
        value match {
          case innerMap: scala.collection.Map[String,Any] =>
            sb.append(s"\n
$key:
")
            sb.append(HTMLFormatMap(innerMap))
          case iterable: Iterable[Any] =>
            iterable.foreach{_ match {
              case anotherMap: scala.collection.Map[String,Any] =>
                sb.append(s"\n
$key:
")
                sb.append(HTMLFormatMap(anotherMap))
              case _ => {}
            }}
            sb.append(s"\n
$key:")
            iterable.foreach{_ match {
              case anotherMap: scala.collection.Map[String,Any] => {}
              case a: Any => sb.append(s"$a | ")
            }}
          case _ =>
            sb.append(s"\n
$key: ${value.toString}
")
        }
    }
    sb.append("\n
")
    sb.toString()
  }

}


text:
package org.apache.tez.runtime.library.conf;

import javax.annotation.Nullable;

import java.util.Map;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.tez.dag.api.UserPayload;

@InterfaceAudience.Private
abstract class HadoopKeyValuesBasedBaseEdgeConfig {

  /**
   * Get the payload for the configured Output
   * @return output configuration as a byte array
   */
  public abstract UserPayload getOutputPayload();

  /**
   * Get the output class name
   * @return the output class name
   */
  public abstract String getOutputClassName();

  /**
   * Get the payload for the configured Input
   * @return input configuration as a byte array
   */
  public abstract UserPayload getInputPayload();

  /**
   * Get the history text for the configured Output
   * @return output configuration as a string in json format
   */
  public abstract String getOutputHistoryText();

  /**
   * Get the history text for the configured Input
   * @return input configuration as a string in json format
   */
  public abstract String getInputHistoryText();

  /**
   * Get the input class name
   * @return the input class name
   */
  public abstract String getInputClassName();

  public abstract static class Builder<T extends Builder<T>> implements BaseConfigBuilder<T> {

    /**
     * Enable compression for the specific Input / Output / Edge
     *
     * @param enabled          whether to enable compression or not
     * @param compressionCodec the codec to be used if compression is enabled. null implies using
     *                         the default
     * @param codecConf        the codec configuration. This can be null, and is a {@link
     *                         java.util.Map} of key-value pairs. The keys should be limited to
     *                         the ones required by the comparator.
     * @return instance of the current builder
     */
    public abstract T setCompression(boolean enabled, @Nullable String compressionCodec,
                            @Nullable Map<String, String> codecConf);

  }

}


text:
/**
*============================================================================
*  The Ohio State University Research Foundation, The University of Chicago -
*  Argonne National Laboratory, Emory University, SemanticBits LLC,
*  and Ekagra Software Technologies Ltd.
*
*  Distributed under the OSI-approved BSD 3-Clause License.
*  See http://ncip.github.com/cagrid-portal/LICENSE.txt for details.
*============================================================================
**/
/**
 *
 */
package gov.nih.nci.cagrid.portal.portlet.query.results;

import gov.nih.nci.cagrid.portal.dao.QueryResultTableDao;
import gov.nih.nci.cagrid.portal.domain.dataservice.QueryInstance;
import gov.nih.nci.cagrid.portal.domain.table.QueryResultTable;
import gov.nih.nci.cagrid.portal.portlet.UserModel;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Joshua Phillips
 * @author Manav Kher
 */
public class ExportJSONResultsMetadataController extends AbstractController {

    private UserModel userModel;
    private QueryResultTableDao queryResultTableDao;
    private QueryResultTableToDataTableMetadataBuilder queryResultTableToDataTableMetadataBuilder;

    /**
     *
     */
    public ExportJSONResultsMetadataController() {

    }

    /*
      * (non-Javadoc)
      *
      * @see
      * org.springframework.web.servlet.mvc.AbstractController#handleRequestInternal
      * (javax.servlet.http.HttpServletRequest,
      * javax.servlet.http.HttpServletResponse)
      */
    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest req,
                                                 HttpServletResponse res) throws Exception {

        QueryInstance instance = getUserModel().getCurrentQueryInstance();
        QueryResultTable table = getQueryResultTableDao().getByQueryInstanceId(
                instance.getId());
        JSONObject meta = queryResultTableToDataTableMetadataBuilder
                .build(table);
        res.setContentType("application/json");
        res.getWriter().write(meta.toString());

        return null;
    }

    public UserModel getUserModel() {
        return userModel;
    }

    public void setUserModel(UserModel userModel) {
        this.userModel = userModel;
    }

    public QueryResultTableDao getQueryResultTableDao() {
        return queryResultTableDao;
    }

    public void setQueryResultTableDao(QueryResultTableDao queryResultTableDao) {
        this.queryResultTableDao = queryResultTableDao;
    }

    public QueryResultTableToDataTableMetadataBuilder getQueryResultTableToDataTableMetadataBuilder() {
        return queryResultTableToDataTableMetadataBuilder;
    }

    public void setQueryResultTableToDataTableMetadataBuilder(QueryResultTableToDataTableMetadataBuilder queryResultTableToDataTableMetadataBuilder) {
        this.queryResultTableToDataTableMetadataBuilder = queryResultTableToDataTableMetadataBuilder;
    }
}


text:
from cStringIO import StringIO

from libpepper.buildsteps.lexbuildstep import LexBuildStep
from libpepper.buildsteps.parsebuildstep import ParseBuildStep
from libpepper.buildsteps.renderbuildstep import RenderBuildStep

from libpepper.cpp.cpprenderer import PepCppRenderer
from libpepper.environment import PepEnvironment
from libpepper import builtins

def eval_program( prog ):
    env = PepEnvironment( PepCppRenderer() )
    builtins.add_builtins( env )

    res = None
    for ln in prog:
        res = env.render_value( ln.evaluate( env ) )

    return res

def run_snippet( code ):
    return (
        eval_program(
            ParseBuildStep().process(
                LexBuildStep().process(
                    StringIO( code )
                )
            )
        )
    )


text:
package nl.tudelft.pds.granula.modeller.giraph.operation;

import nl.tudelft.pds.granula.archiver.entity.info.Source;
import nl.tudelft.pds.granula.archiver.entity.info.SummaryInfo;
import nl.tudelft.pds.granula.archiver.entity.operation.Operation;
import nl.tudelft.pds.granula.modeller.model.operation.ConcreteOperationModel;
import nl.tudelft.pds.granula.modeller.rule.derivation.BasicSummaryDerivation;
import nl.tudelft.pds.granula.modeller.rule.derivation.FilialLongAggregationDerivation;
import nl.tudelft.pds.granula.modeller.rule.visual.MainInfoTableVisualization;
import nl.tudelft.pds.granula.modeller.rule.derivation.ColorDerivation;
import nl.tudelft.pds.granula.modeller.rule.linking.UniqueParentLinking;
import nl.tudelft.pds.granula.modeller.giraph.GiraphType;

import java.util.ArrayList;

public class GlobalCoordintorGlobalDataload extends ConcreteOperationModel {

    public GlobalCoordintorGlobalDataload() {
        super(GiraphType.GlobalCoordinator, GiraphType.GlobalDataload);
    }

    public void loadRules() {
        super.loadRules();

        addLinkingRule(new UniqueParentLinking(GiraphType.BspMaster, GiraphType.BspSetup));

        addInfoDerivation(new FilialLongAggregationDerivation(2, GiraphType.DataLoad, "LoadedDataVolume", "LoadedDataVolume"));
        addInfoDerivation(new FilialLongAggregationDerivation(2, GiraphType.DataLoad, "LoadedEdgeCount", "LoadedEdgeCount"));
        addInfoDerivation(new FilialLongAggregationDerivation(2, GiraphType.DataLoad, "LoadedVertexCount", "LoadedVertexCount"));
        addInfoDerivation(new ColorDerivation(1, GiraphType.ColorGrey));
        addInfoDerivation(new SummaryDerivation(10));
        addVisualDerivation(new MainInfoTableVisualization(1,
                new ArrayList<String>() {{

                    add("LoadedEdgeCount");
                    add("LoadedVertexCount");
                    add("LoadedDataVolume");
                }}));
    }

    protected class SummaryDerivation extends BasicSummaryDerivation {

        public SummaryDerivation(int level) { super(level); }

        @Override
        public boolean execute() {
            Operation operation = (Operation) entity;
            String summary = String.format("The [%s] operation loads the initial graph data from Distributed File System to BspWorkers. " +
                    "These data are then converted into Giraph format and redistributed among BspWorkers by some partitioining technique. " +
                    "The detail mechanism requires more investigation. " +
                    "This operation occur within GlobalSuperstep -1 (InputSuperstep), " +
                    "and contains a set of DataLoad operations for each BspWorker.", operation.getName());
            summary += getBasicSummary(operation);

            SummaryInfo summaryInfo = new SummaryInfo("Summary");
            summaryInfo.setValue("A Summary");
            summaryInfo.addSummary(summary, new ArrayList<Source>());
            operation.addInfo(summaryInfo);
            return  true;
        }
    }

}


text:
[![](https://github.com/keras-team/keras-tuner/workflows/Tests/badge.svg?branch=master)](https://github.com/keras-team/keras-tuner/actions?query=workflow%3ATests+branch%3Amaster)
[![codecov](https://codecov.io/gh/keras-team/keras-tuner/branch/master/graph/badge.svg)](https://codecov.io/gh/keras-team/keras-tuner)
[![PyPI version](https://badge.fury.io/py/keras-tuner.svg)](https://badge.fury.io/py/keras-tuner)

KerasTuner is an easy-to-use, scalable hyperparameter optimization framework
that solves the pain points of hyperparameter search. Easily configure your
search space with a define-by-run syntax, then leverage one of the available
search algorithms to find the best hyperparameter values for your models.
KerasTuner comes with Bayesian Optimization, Hyperband, and Random Search algorithms
built-in, and is also designed to be easy for researchers to extend in order to
experiment with new search algorithms.

Official Website: [https://keras.io/keras_tuner/](https://keras.io/keras_tuner/)

---
## Quick links

* [Getting started with KerasTuner](https://keras.io/guides/keras_tuner/getting_started)
* [KerasTuner developer guides](https://keras.io/guides/keras_tuner/)
* [KerasTuner API reference](https://keras.io/api/keras_tuner/)

---
## Installation

KerasTuner requires **Python 3.6+** and **TensorFlow 2.0+**.

Install the latest release:

```
pip install keras-tuner --upgrade
```

You can also check out other versions in our
[GitHub repository](https://github.com/keras-team/keras-tuner).

---
## Quick introduction

Import KerasTuner and TensorFlow:

```python
import keras_tuner
from tensorflow import keras
```

Write a function that creates and returns a Keras model.
Use the `hp` argument to define the hyperparameters during model creation.

```python
def build_model(hp):
  model = keras.Sequential()
  model.add(keras.layers.Dense(
      hp.Choice('units', [8, 16, 32]),
      activation='relu'))
  model.add(keras.layers.Dense(1, activation='relu'))
  model.compile(loss='mse')
  return model
```

Initialize a tuner (here, `RandomSearch`).
We use `objective` to specify the objective to select the best models,
and we use `max_trials` to specify the number of different models to try.

```python
tuner = keras_tuner.RandomSearch(
    build_model,
    objective='val_loss',
    max_trials=5)
```

Start the search and get the best model:

```python
tuner.search(x_train, y_train, epochs=5, validation_data=(x_val, y_val))
best_model = tuner.get_best_models()[0]
```

To learn more about KerasTuner, check out [this starter guide](https://keras.io/guides/keras_tuner/getting_started/).

---
## Contributing Guide

Please refer to the [CONTRIBUTING.md](https://github.com/keras-team/keras-tuner/blob/master/CONTRIBUTING.md) for the contributing guide.

---
## Community

Please use the [Keras Slack workspace](https://kerasteam.slack.com/), the `#keras-tuner` channel for communication.

Use [this link](https://keras-slack-autojoin.herokuapp.com/) to request an invitation to the channel.

---
## Citing KerasTuner

If KerasTuner helps your research, we appreciate your citations.
Here is the BibTeX entry:

```bibtex
@misc{omalley2019kerastuner,
	title        = {KerasTuner},
	author       = {O'Malley, Tom and Bursztein, Elie and Long, James and Chollet, Fran\c{c}ois and Jin, Haifeng and Invernizzi, Luca and others},
	year         = 2019,
	howpublished = {\url{https://github.com/keras-team/keras-tuner}}
}
```


text:
<link rel="stylesheet" href="/css/site.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

#ifdef DEBUG
    //use weex-devtool to start debug server and paste debug url here
    //[WXDevTool launchDevToolDebugWithUrl:@"ws://127.0.0.1:8088/debugProxy/native"];
#endif
    [WXAppConfiguration setAppName:@"hello-weex-ios"];
    [WXSDKEngine initSDKEnvironment];

    NSURL *url = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"js"]];
    UIViewController *vc = [[WeexViewController alloc] initWithSourceURL:url];
    self.window.rootViewController = vc;

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
By default minikube assumes all images are to be pulled from publically accessible Docker repositories or remote
repositories that the minikube VM can access with some pre-saved credentials (like Google container registery)
But, you can give following command and then any future docker commands you give on your host will be executed
inside the minikube VM. Which means if you build any docker images after that, they will be availble inside minikube.

`eval $(minikube docker-env)`


text:
import unittest

from ..book import OrderBook
from ..orders import LimitBuyOrder, LimitSellOrder
from ..asset import make_symbol

class OrderBookTest(unittest.TestCase):

    def setUp(self):
        self.trades = []
        self.book = OrderBook(lambda trade: self.trades.append(trade))

    def tearDown(self):
        self.book = None
        self.trades = None

    def numOrdersExecuted(self):
        return len(self.trades)

    def testMatchBuyExact(self):
        sell = LimitSellOrder(100, make_symbol('BTC', 'USD'), 1, 'gavin')
        buy = LimitBuyOrder(100, make_symbol('BTC', 'USD'), 1, 'satoshi')

        # Execute Buy Order First
        self.book.execute(buy)
        self.book.execute(sell)
        self.assertEquals(1, self.numOrdersExecuted(),
                          'One trade should have been executed')
        [trade] = self.trades
        self.assertEquals(sell.symbol, trade.symbol,
                          'The trade\'s symbol should be that of the sell order\'s symbol')
        self.assertEquals(buy.symbol, trade.symbol,
                          'The trade\'s symbol should be that of the buy order\'s symbol')
        self.assertEquals(sell.trader_id, trade.seller_id,
                          'The sell order\'s trader_id should be the seller_id of the trade')
        self.assertEquals(buy.trader_id, trade.buyer_id,
                          'The buy order\'s trader_id should be the buyer_id of the trade')
        self.assertEquals(sell.quantity, trade.quantity)
        self.assertEquals(buy.quantity, trade.quantity)
        self.assertEquals(sell.price, trade.price)
        self.assertEquals(buy.price, trade.price)

        # make sure all the orders were cleared out
        self.assertFalse(self.book.has_bids(), 'The book should be empty')
        self.assertFalse(self.book.has_asks(), 'The book should be empty')

    def testMatchSellExact(self):
        sell = LimitSellOrder(100, 'BTC/USD', 1, 'gavin')
        buy = LimitBuyOrder(100, 'BTC/USD', 1, 'satoshi')

        # Execute Sell Order First
        self.book.execute(sell)
        self.book.execute(buy)
        self.assertEquals(1, self.numOrdersExecuted(),
                          'One trade should have been executed')
        [trade] = self.trades
        self.assertEquals(sell.symbol, trade.symbol,
                          'The trade\'s symbol should be that of the sell order\'s symbol')
        self.assertEquals(buy.symbol, trade.symbol,
                          'The trade\'s symbol should be that of the buy order\'s symbol')
        self.assertEquals(sell.trader_id, trade.seller_id,
                          'The sell order\'s trader_id should be the seller_id of the trade')
        self.assertEquals(buy.trader_id, trade.buyer_id,
                          'The buy order\'s trader_id should be the buyer_id of the trade')
        self.assertEquals(sell.quantity, trade.quantity)
        self.assertEquals(buy.quantity, trade.quantity)
        self.assertEquals(sell.price, trade.price)
        self.assertEquals(buy.price, trade.price)

        # make sure all the orders were cleared out
        self.assertFalse(self.book.has_bids(), 'The book should be empty')
        self.assertFalse(self.book.has_asks(), 'The book should be empty')

    def testMatchPartial(self):
        # One seller, multiple buyers. All orders should be matched.
        sell = LimitSellOrder(100, make_symbol('BTC', 'USD'), 1, 'gavin')
        buy1 = LimitBuyOrder(100, make_symbol('BTC', 'USD'), 0.5, 'satoshi')
        buy2 = LimitBuyOrder(100, make_symbol('BTC', 'USD'), 0.25, 'gmaxwell')
        buy3 = LimitBuyOrder(100, make_symbol('BTC', 'USD'), 0.25, 'mhearn')

        # since all orders are for the same price, they should be matched in FIFO Order
        self.book.execute(buy1)
        self.book.execute(buy2)
        self.book.execute(buy3)
        self.book.execute(sell)

        self.assertEquals(3, self.numOrdersExecuted())
        [trade1, trade2, trade3] = self.trades
        self.assertEquals(buy1.quantity, trade1.quantity)
        self.assertEquals(buy1.trader_id, trade1.buyer_id)
        self.assertEquals(buy2.quantity, trade2.quantity)
        self.assertEquals(buy2.trader_id, trade2.buyer_id)
        self.assertEquals(buy3.quantity, trade3.quantity)
        self.assertEquals(buy3.trader_id, trade3.buyer_id)

        # make sure all the orders were cleared out
        self.assertFalse(self.book.has_bids(), 'The book should be empty')
        self.assertFalse(self.book.has_asks(), 'The book should be empty')

    def testMatchBuyPartialUnfilled(self):
        # One seller, one buyer. Buyer should be filled, seller should be partially filled
        # price should be the sellers since it was on the book first

        sell = LimitSellOrder(100, make_symbol('BTC', 'USD'), 1, 'gavin')
        buy = LimitBuyOrder(150, make_symbol('BTC', 'USD'), 0.25, 'satoshi')

        self.book.execute(sell)
        self.book.execute(buy)

        self.assertEquals(1, self.numOrdersExecuted())
        [trade] = self.trades
        self.assertEquals(make_symbol('BTC', 'USD'), trade.symbol)
        self.assertEquals(buy.quantity, trade.quantity)
        self.assertEquals(buy.trader_id, trade.buyer_id)
        self.assertEquals(sell.trader_id, trade.seller_id)
        # Order should be filled at the sellers price since it was on the book first
        self.assertEquals(sell.price, trade.price)

        self.assertTrue(self.book.has_asks(), 'There should still be an ask on the book')

        self.assertFalse(self.book.has_bids(), 'There should be no bids')

    def testMatchLimitSellPriceOrder(self):
        # when matching a limit order, the trade executes at the price of the order
        # that was on the book, not the new order

        # See: http://money.stackexchange.com/questions/15156/how-do-exchanges-match-limit-orders

        # gavin posts an order to buy 5 BTC @ 100 USD each
        self.book.execute(LimitBuyOrder(100, make_symbol('BTC', 'USD'), 5, 'gavin'))
        # satoshi posts an order to buy 10 BTC @ 99 USD each
        self.book.execute(LimitBuyOrder(99, make_symbol('BTC', 'USD'), 10, 'satoshi'))
        # mhearn posts an order to buy 20 BTC @ 50 USD each
        self.book.execute(LimitBuyOrder(50, make_symbol('BTC', 'USD'), 20, 'mhearn'))

        # finally, we execute a limit order to sell 100BTC at 0.01 USD
        self.book.execute(LimitSellOrder(0.01, make_symbol('BTC', 'USD'), 100, 'fool'))

        # all 3 buys should have been filled
        self.assertEquals(3, self.numOrdersExecuted())
        [gavin_trade, satoshi_trade, hearn_trade] = self.trades

        # gavin's order should have been filled first at a price of 100
        self.assertEquals('gavin', gavin_trade.buyer_id)
        self.assertEquals(100, gavin_trade.price)

        # satoshi's order should have been filled second at a price of 99
        self.assertEquals('satoshi', satoshi_trade.buyer_id)
        self.assertEquals(99, satoshi_trade.price)

        # mhearns order should have been filled last at a price of 50
        self.assertEquals('mhearn', hearn_trade.buyer_id)
        self.assertEquals(50, hearn_trade.price)

        # All the bids should have been filled
        self.assertFalse(self.book.has_bids())
        # Partial order should still be on the book
        self.assertTrue(self.book.has_asks())

    def testMatchLimitBuyPriceOrder(self):
        # same as above, but for the opposite situation

        # gavin posts an order to sell 5 BTC @ 100 USD each
        self.book.execute(LimitSellOrder(100, make_symbol('BTC', 'USD'), 5, 'gavin'))
        # satoshi posts an order to sell 10 BTC @ 99 USD each
        self.book.execute(LimitSellOrder(99, make_symbol('BTC', 'USD'), 10, 'satoshi'))
        # mhearn posts an order to sell 20 BTC @ 50 USD each
        self.book.execute(LimitSellOrder(50, make_symbol('BTC', 'USD'), 20, 'mhearn'))

        # finally, we execute a limit order to buy 100BTC at 1000 USD
        self.book.execute(LimitBuyOrder(1000, make_symbol('BTC', 'USD'), 100, 'fool'))

        # all 3 buys should have been filled
        self.assertEquals(3, self.numOrdersExecuted())
        [hearn_trade, satoshi_trade, gavin_trade] = self.trades

        # mhearns order should have been filled first at a price of 50
        self.assertEquals('mhearn', hearn_trade.seller_id)
        self.assertEquals(50, hearn_trade.price)

        # satoshi's order should have been filled second at a price of 99
        self.assertEquals('satoshi', satoshi_trade.seller_id)
        self.assertEquals(99, satoshi_trade.price)

        # gavin's order should have been filled last at a price of 100
        self.assertEquals('gavin', gavin_trade.seller_id)
        self.assertEquals(100, gavin_trade.price)

        # All the asks should have been filled
        self.assertFalse(self.book.has_asks())
        # Partial buy order should still be on the book
        self.assertTrue(self.book.has_bids())


text:
namespace enterprise_connectors {

namespace {

absl::optional<KeyRotationCommandFactory*>& GetTestInstanceStorage() {
  static absl::optional<KeyRotationCommandFactory*> storage;
  return storage;
}

}  // namespace

KeyRotationCommandFactory::~KeyRotationCommandFactory() = default;

// static
KeyRotationCommandFactory* KeyRotationCommandFactory::GetInstance() {
  auto test_instance = GetTestInstanceStorage();
  if (test_instance.has_value() && test_instance.value()) {
    return test_instance.value();
  }
  return base::Singleton<KeyRotationCommandFactory>::get();
}

std::unique_ptr<KeyRotationCommand> KeyRotationCommandFactory::CreateCommand(
    scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory) {
#if BUILDFLAG(IS_WIN)
  return std::make_unique<WinKeyRotationCommand>();
#elif BUILDFLAG(IS_LINUX)
  return std::make_unique<LinuxKeyRotationCommand>(
      std::move(url_loader_factory));
#else
  return nullptr;
#endif  // BUILDFLAG(IS_WIN)
}

// static
void KeyRotationCommandFactory::SetFactoryInstanceForTesting(
    KeyRotationCommandFactory* factory) {
  DCHECK(factory);
  GetTestInstanceStorage().emplace(factory);
}

// static
void KeyRotationCommandFactory::ClearFactoryInstanceForTesting() {
  GetTestInstanceStorage().reset();
}

}  // namespace enterprise_connectors


text:
<?php

namespace Elerium\Doctrine\Forms;

use Elerium;
use Nette;
use Nette\Forms\IControl;

class Rules extends Nette\Object
{

	/**
	 * @param \Nette\Forms\IControl $control
	 * @return bool
	 */
	public static function validateUnique(IControl $control)
	{
		$container = $control->getParent();
		if($container->getDefaultValue($control->name) == $control->getValue())
		{
			return TRUE;
		}

		return !(bool) $container->getEntityManager()->getRepository($container->getClassMetadata()->getName())->findOneBy(array($control->name => $control->value));
	}
}