text:
package org.apache.phoenix.mapreduce.index;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.DefaultParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.util.FSUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.NullOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.mapreduce.CsvBulkImportUtil;
import org.apache.phoenix.mapreduce.util.ConnectionUtil;
import org.apache.phoenix.mapreduce.util.PhoenixConfigurationUtil;
import org.apache.phoenix.mapreduce.util.PhoenixMapReduceUtil;
import org.apache.phoenix.parse.HintNode.Hint;
import org.apache.phoenix.schema.PTable;
import org.apache.phoenix.util.EnvironmentEdgeManager;
import org.apache.phoenix.util.PhoenixRuntime;
import org.apache.phoenix.util.QueryUtil;
import org.apache.phoenix.util.SchemaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

/**
 * An MR job to verify that the index table is in sync with the data table.
 *
 */
public class IndexScrutinyTool extends Configured implements Tool {

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

    private static final Option SCHEMA_NAME_OPTION =
            new Option("s", "schema", true, "Phoenix schema name (optional)");
    private static final Option DATA_TABLE_OPTION =
            new Option("dt", "data-table", true, "Data table name (mandatory)");
    private static final Option INDEX_TABLE_OPTION =
            new Option("it", "index-table", true,
                    "Index table name (mandatory).");
    private static final Option TIMESTAMP =
            new Option("t", "time", true,
                    "Timestamp in millis used to compare the index and data tables.  Defaults to current time minus 60 seconds");

    private static final Option RUN_FOREGROUND_OPTION =
            new Option("runfg", "run-foreground", false, "Applicable on top of -direct option."
                    + "If specified, runs index scrutiny in Foreground. Default - Runs the build in background.");

    private static final Option SNAPSHOT_OPTION = //TODO check if this works
            new Option("snap", "snapshot", false,
                    "If specified, uses Snapshots for async index building (optional)");

    public static final Option BATCH_SIZE_OPTION =
            new Option("b", "batch-size", true, "Number of rows to compare at a time");
    public static final Option SOURCE_TABLE_OPTION =
            new Option("src", "source", true,
                    "Table to use as the source table, whose rows are iterated over and compared to the other table."
                            + " Options are DATA_TABLE_SOURCE, INDEX_TABLE_SOURCE, BOTH."
                            + "  Defaults to BOTH, which does two separate jobs to iterate over both tables");

    private static final Option HELP_OPTION = new Option("h", "help", false, "Help");

    private static final Option OUTPUT_INVALID_ROWS_OPTION =
            new Option("o", "output", false, "Whether to output invalid rows");
    private static final Option OUTPUT_FORMAT_OPTION =
            new Option("of", "output-format", true,
                    "Format in which to output invalid rows.  Options are FILE, TABLE.  Defaults to TABLE");
    private static final Option OUTPUT_PATH_OPTION =
            new Option("op", "output-path", true, "Output path where the files are written");
    private static final Option OUTPUT_MAX = new Option("om", "output-max", true, "Max number of invalid rows to output per mapper.  Defaults to 1M");
    public static final String INDEX_JOB_NAME_TEMPLATE = "PHOENIX_SCRUTINY_[%s]_[%s]";

    /**
     * Which table to use as the source table
     */
    public static enum SourceTable {
        DATA_TABLE_SOURCE, INDEX_TABLE_SOURCE,
        /**
         * Runs two separate jobs to iterate over both tables
         */
        BOTH;
    }

    public static enum OutputFormat {
        FILE, TABLE
    }

    private List<Job> jobs = Lists.newArrayList();

    private Options getOptions() {
        final Options options = new Options();
        options.addOption(SCHEMA_NAME_OPTION);
        options.addOption(DATA_TABLE_OPTION);
        options.addOption(INDEX_TABLE_OPTION);
        options.addOption(RUN_FOREGROUND_OPTION);
        options.addOption(OUTPUT_INVALID_ROWS_OPTION);
        options.addOption(OUTPUT_FORMAT_OPTION);
        options.addOption(OUTPUT_PATH_OPTION);
        options.addOption(OUTPUT_MAX);
        options.addOption(SNAPSHOT_OPTION);
        options.addOption(HELP_OPTION);
        options.addOption(TIMESTAMP);
        options.addOption(BATCH_SIZE_OPTION);
        options.addOption(SOURCE_TABLE_OPTION);
        return options;
    }

    /**
     * Parses the commandline arguments, throws IllegalStateException if mandatory arguments are
     * missing.
     * @param args supplied command line arguments
     * @return the parsed command line
     */
    private CommandLine parseOptions(String[] args) {
        final Options options = getOptions();

        CommandLineParser parser = new DefaultParser();
        CommandLine cmdLine = null;
        try {
            cmdLine = parser.parse(options, args);
        } catch (ParseException e) {
            printHelpAndExit("Error parsing command line options: " + e.getMessage(), options);
        }

        if (cmdLine.hasOption(HELP_OPTION.getOpt())) {
            printHelpAndExit(options, 0);
        }

        requireOption(cmdLine, DATA_TABLE_OPTION);
        requireOption(cmdLine, INDEX_TABLE_OPTION);

        return cmdLine;
    }

    private void requireOption(CommandLine cmdLine, Option option) {
        if (!cmdLine.hasOption(option.getOpt())) {
            throw new IllegalStateException(option.getLongOpt() + " is a mandatory parameter");
        }
    }

    private void printHelpAndExit(String errorMessage, Options options) {
        System.err.println(errorMessage);
        printHelpAndExit(options, 1);
    }

    private void printHelpAndExit(Options options, int exitCode) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("help", options);
        System.exit(exitCode);
    }

    class JobFactory {
        Connection connection;
        Configuration configuration;
        private boolean useSnapshot;
        private long ts;
        private boolean outputInvalidRows;
        private OutputFormat outputFormat;
        private String basePath;
        private long scrutinyExecuteTime;
        private long outputMaxRows; // per mapper

        public JobFactory(Connection connection, Configuration configuration, long batchSize,
                boolean useSnapshot, long ts, boolean outputInvalidRows, OutputFormat outputFormat,
                String basePath, long outputMaxRows) {
            this.outputInvalidRows = outputInvalidRows;
            this.outputFormat = outputFormat;
            this.basePath = basePath;
            this.outputMaxRows = outputMaxRows;
            PhoenixConfigurationUtil.setScrutinyBatchSize(configuration, batchSize);
            this.connection = connection;
            this.configuration = configuration;
            this.useSnapshot = useSnapshot;
            this.ts = ts; // CURRENT_SCN to set
            scrutinyExecuteTime = EnvironmentEdgeManager.currentTimeMillis(); // time at which scrutiny was run.
                                                              // Same for
            // all jobs created from this factory
            PhoenixConfigurationUtil.setScrutinyExecuteTimestamp(configuration,
                scrutinyExecuteTime);
        }

        public Job createSubmittableJob(String schemaName, String indexTable, String dataTable,
                SourceTable sourceTable) throws Exception {
            Preconditions.checkArgument(SourceTable.DATA_TABLE_SOURCE.equals(sourceTable)
                    || SourceTable.INDEX_TABLE_SOURCE.equals(sourceTable));

            final String qDataTable = SchemaUtil.getQualifiedTableName(schemaName, dataTable);
            final String qIndexTable;
            if (schemaName != null && !schemaName.isEmpty()) {
                qIndexTable = SchemaUtil.getQualifiedTableName(schemaName, indexTable);
            } else {
                qIndexTable = indexTable;
            }
            PhoenixConfigurationUtil.setScrutinyDataTable(configuration, qDataTable);
            PhoenixConfigurationUtil.setScrutinyIndexTable(configuration, qIndexTable);
            PhoenixConfigurationUtil.setScrutinySourceTable(configuration, sourceTable);
            PhoenixConfigurationUtil.setScrutinyOutputInvalidRows(configuration, outputInvalidRows);
            PhoenixConfigurationUtil.setScrutinyOutputMax(configuration, outputMaxRows);

            final PTable pdataTable = PhoenixRuntime.getTable(connection, qDataTable);
            final PTable pindexTable = PhoenixRuntime.getTable(connection, qIndexTable);

            // set CURRENT_SCN for our scan so that incoming writes don't throw off scrutiny
            configuration.set(PhoenixConfigurationUtil.CURRENT_SCN_VALUE, Long.toString(ts));

            // set the source table to either data or index table
            SourceTargetColumnNames columnNames =
                    SourceTable.DATA_TABLE_SOURCE.equals(sourceTable)
                            ? new SourceTargetColumnNames.DataSourceColNames(pdataTable,
                                    pindexTable)
                            : new SourceTargetColumnNames.IndexSourceColNames(pdataTable,
                                    pindexTable);
            String qSourceTable = columnNames.getQualifiedSourceTableName();
            List<String> sourceColumnNames = columnNames.getSourceColNames();
            List<String> sourceDynamicCols = columnNames.getSourceDynamicCols();
            List<String> targetDynamicCols = columnNames.getTargetDynamicCols();

            // Setup the select query against source - we either select the index columns from the
            // index table,
            // or select the data table equivalents of the index columns from the data table
            final String selectQuery =
                    QueryUtil.constructSelectStatement(qSourceTable, sourceColumnNames, null,
                        Hint.NO_INDEX, true);
            LOG.info("Query used on source table to feed the mapper: " + selectQuery);

            PhoenixConfigurationUtil.setScrutinyOutputFormat(configuration, outputFormat);
            // if outputting to table, setup the upsert to the output table
            if (outputInvalidRows && OutputFormat.TABLE.equals(outputFormat)) {
                String upsertStmt =
                        IndexScrutinyTableOutput.constructOutputTableUpsert(sourceDynamicCols,
                            targetDynamicCols, connection);
                PhoenixConfigurationUtil.setUpsertStatement(configuration, upsertStmt);
                LOG.info("Upsert statement used for output table: " + upsertStmt);
            }

            final String jobName =
                    String.format(INDEX_JOB_NAME_TEMPLATE, qSourceTable,
                        columnNames.getQualifiedTargetTableName());
            final Job job = Job.getInstance(configuration, jobName);

            if (!useSnapshot) {
                PhoenixMapReduceUtil.setInput(job, PhoenixIndexDBWritable.class, qDataTable,
                    selectQuery);
            } else { // TODO check if using a snapshot works
                Admin admin = null;
                String snapshotName;
                try {
                    final PhoenixConnection pConnection =
                            connection.unwrap(PhoenixConnection.class);
                    admin = pConnection.getQueryServices().getAdmin();
                    String pdataTableName = pdataTable.getName().getString();
                    snapshotName = new StringBuilder(pdataTableName).append("-Snapshot").toString();
                    admin.snapshot(snapshotName, TableName.valueOf(pdataTableName));
                } finally {
                    if (admin != null) {
                        admin.close();
                    }
                }
                // root dir not a subdirectory of hbase dir
                Path rootDir = new Path("hdfs:///index-snapshot-dir");
                FSUtils.setRootDir(configuration, rootDir);

                // set input for map reduce job using hbase snapshots
                //PhoenixMapReduceUtil.setInput(job, PhoenixIndexDBWritable.class, snapshotName,
                //    qDataTable, restoreDir, selectQuery);
            }
            TableMapReduceUtil.initCredentials(job);
            Path outputPath =
                    getOutputPath(configuration, basePath,
                        SourceTable.DATA_TABLE_SOURCE.equals(sourceTable) ? pdataTable
                                : pindexTable);

            return configureSubmittableJob(job, outputPath);
        }

        private Job configureSubmittableJob(Job job, Path outputPath) throws Exception {
            Configuration conf = job.getConfiguration();
            conf.setBoolean("mapreduce.job.user.classpath.first", true);
            HBaseConfiguration.merge(conf, HBaseConfiguration.create(conf));
            job.setJarByClass(IndexScrutinyTool.class);
            job.setOutputFormatClass(NullOutputFormat.class);
            if (outputInvalidRows && OutputFormat.FILE.equals(outputFormat)) {
                job.setOutputFormatClass(TextOutputFormat.class);
                FileOutputFormat.setOutputPath(job, outputPath);
            }
            job.setMapperClass(IndexScrutinyMapper.class);
            job.setNumReduceTasks(0);
            // Set the Output classes
            job.setMapOutputKeyClass(Text.class);
            job.setMapOutputValueClass(Text.class);
            TableMapReduceUtil.addDependencyJars(job);
            return job;
        }

        Path getOutputPath(final Configuration configuration, String basePath, PTable table)
                throws IOException {
            Path outputPath = null;
            FileSystem fs;
            if (basePath != null) {
                outputPath =
                        CsvBulkImportUtil.getOutputPath(new Path(basePath),
                            table.getPhysicalName().getString());
                fs = outputPath.getFileSystem(configuration);
                fs.delete(outputPath, true);
            }
            return outputPath;
        }
    }

    @Override
    public int run(String[] args) throws Exception {
        Connection connection = null;
        try {
            /** start - parse command line configs **/
            CommandLine cmdLine = null;
            try {
                cmdLine = parseOptions(args);
            } catch (IllegalStateException e) {
                printHelpAndExit(e.getMessage(), getOptions());
            }
            final Configuration configuration = HBaseConfiguration.addHbaseResources(getConf());
            connection = ConnectionUtil.getInputConnection(configuration);
            final String schemaName = cmdLine.getOptionValue(SCHEMA_NAME_OPTION.getOpt());
            final String dataTable = cmdLine.getOptionValue(DATA_TABLE_OPTION.getOpt());
            final String indexTable = cmdLine.getOptionValue(INDEX_TABLE_OPTION.getOpt());
            final String qDataTable = SchemaUtil.getQualifiedTableName(schemaName, dataTable);
            String basePath = cmdLine.getOptionValue(OUTPUT_PATH_OPTION.getOpt());
            boolean isForeground = cmdLine.hasOption(RUN_FOREGROUND_OPTION.getOpt());
            boolean useSnapshot = cmdLine.hasOption(SNAPSHOT_OPTION.getOpt());
            boolean outputInvalidRows = cmdLine.hasOption(OUTPUT_INVALID_ROWS_OPTION.getOpt());
            SourceTable sourceTable =
                    cmdLine.hasOption(SOURCE_TABLE_OPTION.getOpt())
                            ? SourceTable
                                    .valueOf(cmdLine.getOptionValue(SOURCE_TABLE_OPTION.getOpt()))
                            : SourceTable.BOTH;

            long batchSize =
                    cmdLine.hasOption(BATCH_SIZE_OPTION.getOpt())
                            ? Long.parseLong(cmdLine.getOptionValue(BATCH_SIZE_OPTION.getOpt()))
                            : PhoenixConfigurationUtil.DEFAULT_SCRUTINY_BATCH_SIZE;

            long ts =
                    cmdLine.hasOption(TIMESTAMP.getOpt())
                            ? Long.parseLong(cmdLine.getOptionValue(TIMESTAMP.getOpt()))
                            : EnvironmentEdgeManager.currentTimeMillis() - 60000;

            if (indexTable != null) {
                if (!isValidIndexTable(connection, qDataTable, indexTable)) {
                    throw new IllegalArgumentException(String
                            .format(" %s is not an index table for %s ", indexTable, qDataTable));
                }
            }

            String outputFormatOption = cmdLine.getOptionValue(OUTPUT_FORMAT_OPTION.getOpt());
            OutputFormat outputFormat =
                    outputFormatOption != null
                            ? OutputFormat.valueOf(outputFormatOption.toUpperCase())
                            : OutputFormat.TABLE;
            long outputMaxRows =
                    cmdLine.hasOption(OUTPUT_MAX.getOpt())
                            ? Long.parseLong(cmdLine.getOptionValue(OUTPUT_MAX.getOpt()))
                            : 1000000L;
            /** end - parse command line configs **/

            if (outputInvalidRows && OutputFormat.TABLE.equals(outputFormat)) {
                // create the output table if it doesn't exist
                try (Connection outputConn = ConnectionUtil.getOutputConnection(configuration)) {
                    outputConn.createStatement().execute(IndexScrutinyTableOutput.OUTPUT_TABLE_DDL);
                    outputConn.createStatement()
                            .execute(IndexScrutinyTableOutput.OUTPUT_METADATA_DDL);
                }
            }

            LOG.info(String.format(
                "Running scrutiny [schemaName=%s, dataTable=%s, indexTable=%s, useSnapshot=%s, timestamp=%s, batchSize=%s, outputBasePath=%s, outputFormat=%s, outputMaxRows=%s]",
                schemaName, dataTable, indexTable, useSnapshot, ts, batchSize, basePath,
                outputFormat, outputMaxRows));
            JobFactory jobFactory =
                    new JobFactory(connection, configuration, batchSize, useSnapshot, ts,
                            outputInvalidRows, outputFormat, basePath, outputMaxRows);
            // If we are running the scrutiny with both tables as the source, run two separate jobs,
            // one for each direction
            if (SourceTable.BOTH.equals(sourceTable)) {
                jobs.add(jobFactory.createSubmittableJob(schemaName, indexTable, dataTable,
                    SourceTable.DATA_TABLE_SOURCE));
                jobs.add(jobFactory.createSubmittableJob(schemaName, indexTable, dataTable,
                    SourceTable.INDEX_TABLE_SOURCE));
            } else {
                jobs.add(jobFactory.createSubmittableJob(schemaName, indexTable, dataTable,
                    sourceTable));
            }

            if (!isForeground) {
                LOG.info("Running Index Scrutiny in Background - Submit async and exit");
                for (Job job : jobs) {
                    job.submit();
                }
                return 0;
            }
            LOG.info(
                "Running Index Scrutiny in Foreground. Waits for the build to complete. This may take a long time!.");
            boolean result = true;
            for (Job job : jobs) {
                result = result && job.waitForCompletion(true);
            }

            // write the results to the output metadata table
            if (outputInvalidRows && OutputFormat.TABLE.equals(outputFormat)) {
                LOG.info("Writing results of jobs to output table "
                        + IndexScrutinyTableOutput.OUTPUT_METADATA_TABLE_NAME);
                IndexScrutinyTableOutput.writeJobResults(connection, args, jobs);
            }

            if (result) {
                return 0;
            } else {
                LOG.error("IndexScrutinyTool job failed! Check logs for errors..");
                return -1;
            }
        } catch (Exception ex) {
            LOG.error("An exception occurred while performing the indexing job: "
                    + ExceptionUtils.getMessage(ex) + " at:\n" + ExceptionUtils.getStackTrace(ex));
            return -1;
        } finally {
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException sqle) {
                LOG.error("Failed to close connection ", sqle.getMessage());
                throw new RuntimeException("Failed to close connection");
            }
        }
    }

    @VisibleForTesting
    public List<Job> getJobs() {
        return jobs;
    }

    /**
     * Checks for the validity of the index table passed to the job.
     * @param connection
     * @param masterTable
     * @param indexTable
     * @return
     * @throws SQLException
     */
    private boolean isValidIndexTable(final Connection connection, final String masterTable,
            final String indexTable) throws SQLException {
        final DatabaseMetaData dbMetaData = connection.getMetaData();
        final String schemaName = SchemaUtil.getSchemaNameFromFullName(masterTable);
        final String tableName =
                SchemaUtil.normalizeIdentifier(SchemaUtil.getTableNameFromFullName(masterTable));

        ResultSet rs = null;
        try {
            rs = dbMetaData.getIndexInfo("", schemaName, tableName, false, false);
            while (rs.next()) {
                final String indexName = rs.getString(6);
                if (indexTable.equalsIgnoreCase(indexName)) {
                    return true;
                }
            }
        } finally {
            if (rs != null) {
                rs.close();
            }
        }
        return false;
    }

    public static void main(final String[] args) throws Exception {
        int result = ToolRunner.run(new IndexScrutinyTool(), args);
        System.exit(result);
    }

}


text:
package com.hitzd.his.casehistory.beans;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.hitzd.his.casehistory.beans.exam.ExamMaster;
import com.hitzd.his.casehistory.beans.germtest.GermTest;
import com.hitzd.his.casehistory.beans.germtest.GermTestResult;
import com.hitzd.his.casehistory.beans.labtest.LabTestMaster;
import com.hitzd.his.casehistory.beans.operation.Operation;
import com.hitzd.his.casehistory.beans.operation.OperationMaster;
import com.hitzd.his.casehistory.beans.operation.OperationName;

/**
 * PatVisit generated by MyEclipse Persistence Tools
 */

public class PatVisit implements java.io.Serializable {

	// Fields

	/**
	 *
	 */
	private static final long serialVersionUID = -4890409247745862978L;

	private String patientId;

	private Long visitId;

	private String deptAdmissionTo;

	private Date admissionDateTime;

	private String deptDischargeFrom;

	private Date dischargeDateTime;

	private String occupation;

	private String maritalStatus;

	private String identity;

	private String armedServices;

	private String duty;

	private String unitInContract;

	private String chargeType;

	private Long workingStatus;

	private String insuranceType;

	private String insuranceNo;

	private String serviceAgency;

	private String mailingAddress;

	private String zipCode;

	private String nextOfKin;

	private String relationship;

	private String nextOfKinAddr;

	private String nextOfKinZipcode;

	private String nextOfKinPhone;

	private String patientClass;

	private String admissionCause;

	private Date consultingDate;

	private String patAdmCondition;

	private String consultingDoctor;

	private String admittedBy;

	private Long emerTreatTimes;

	private Long escEmerTimes;

	private Long seriousCondDays;

	private Long criticalCondDays;

	private Long icuDays;

	private Long ccuDays;

	private Long specLevelNursDays;

	private Long firstLevelNursDays;

	private Long secondLevelNursDays;

	private Long autopsyIndicator;

	private String bloodType;

	private String bloodTypeRh;

	private Long bloodTranTimes;

	private Long bloodTranVol;

	private Long bloodTranReactTimes;

	private Long decubitalUlcerTimes;

	private String alergyDrugs;

	private String adverseReactionDrugs;

	private String mrValue;

	private String mrQuality;

	private Long followIndicator;

	private Long followInterval;

	private String followIntervalUnits;

	private String director;

	private String attendingDoctor;

	private String doctorInCharge;

	private String dischargeDisposition;

	private Double totalCosts;

	private Double totalPayments;

	private Date catalogDate;

	private String cataloger;

	private String catalogWriter;

	private Long infusionReactTimes;

	private String topUnit;

	private Long serviceSystemIndicator;

	private String healthLevel;

	private String mrInfectReport;

	private Long infectIndicator;

	private Double bodyWeight;

	private Double bodyHeight;

	private String internalNo;

	private String identityClass;

	private Long hbsagIndicator;

	private Long hcvAbIndicator;

	private Long hivAbIndicator;

	private String chiefDoctor;

	private String advancedStudiesDoctor;

	private String practiceDoctorOfGraduate;

	private String practiceDoctor;

	private String doctorOfControlQuality;

	private String nurseOfControlQuality;

	private Date dateOfControlQuality;

	private Long firstCaseIndicator;

	private Long thirdLevelNursDays;

	private String XExamNo;

	private String medicalPayWay;

	private Long firstAidIndicator;

	private Long trainingInjuryIndicator;

	private String inDeptName;

	private Long inClinicAttr;

	private Long inOutpOrInp;

	private Long inInternalOrSergery;

	private String outDeptName;

	private Long outClinicAttr;

	private Long outOutpOrInp;

	private Long outInternalOrSergery;

	private Long settleIndi;

	private Date linkDate;

	// 诊断列表
	private List<Diagnosis> diagnosis = new ArrayList<Diagnosis>();
	public int getDiagnosisCount()
	{
		return diagnosis.size();
	}
	public Diagnosis getDiagnosisByIndex(int index)
	{
		return diagnosis.get(index);
	}
	public void addDiagnosis(Diagnosis value)
	{
		diagnosis.add(value);
	}
	public void removeDiagnosisByIndex(int index)
	{
		diagnosis.remove(index);
	}

	// 摆药记录
	private List<DrugDispenseRec> drugDispenseRecs = new ArrayList<DrugDispenseRec>();
	public int getDrugDispenseRecCount()
	{
		return drugDispenseRecs.size();
	}
	public DrugDispenseRec getDrugDispenseRecByIndex(int index)
	{
		return drugDispenseRecs.get(index);
	}
	public void addDrugDispenseRec(DrugDispenseRec value)
	{
		drugDispenseRecs.add(value);
	}
	public void removeDrugDispenseRecByIndex(int index)
	{
		drugDispenseRecs.remove(index);
	}
	// 住院费用明细
	private List<InpBillDetail> inpBillDetails = new ArrayList<InpBillDetail>();
	public int getInpBillDetailCount()
	{
		return inpBillDetails.size();
	}
	public InpBillDetail getInpBillDetailByIndex(int index)
	{
		return inpBillDetails.get(index);
	}
	public void addInpBillDetail(InpBillDetail value)
	{
		inpBillDetails.add(value);
	}
	public void removeInpBillDetailByIndex(int index)
	{
		inpBillDetails.remove(index);
	}
	// 手术记录
	private List<Operation> operations = new ArrayList<Operation>();
	public int getOperationCount()
	{
		return operations.size();
	}
	public Operation getOperationByIndex(int index)
	{
		return operations.get(index);
	}
	public void addOperation(Operation value)
	{
		operations.add(value);
	}
	public void removeOperationByIndex(int index)
	{
		operations.remove(index);
	}
	// 手术主记录
	private List<OperationMaster> operationMasters = new ArrayList<OperationMaster>();
	public int getOperationMasterCount()
	{
		return operationMasters.size();
	}
	public OperationMaster getOperationMasterByIndex(int index)
	{
		return operationMasters.get(index);
	}
	public void addDiagnosis(OperationMaster value)
	{
		operationMasters.add(value);
	}
	public void removeOperationMasterByIndex(int index)
	{
		operationMasters.remove(index);
	}
	// 手术名称
	private List<OperationName> operationNames = new ArrayList<OperationName>();
	public int getOperationNameCount()
	{
		return operationNames.size();
	}
	public OperationName getOperationNameByIndex(int index)
	{
		return operationNames.get(index);
	}
	public void addOperationName(OperationName value)
	{
		operationNames.add(value);
	}
	public void removeOperationNameByIndex(int index)
	{
		operationNames.remove(index);
	}
	// 医嘱记录
	private List<Orders> orders = new ArrayList<Orders>();
	public int getOrdersCount()
	{
		return orders.size();
	}
	public Orders getOrdersByIndex(int index)
	{
		return orders.get(index);
	}
	public void addOrders(Orders value)
	{
		orders.add(value);
	}
	public void removeOrdersByIndex(int index)
	{
		orders.remove(index);
	}
	// 体征记录
	private List<VitalSignsRec> vitalSignsRecs = new ArrayList<VitalSignsRec>();
	public int getVitalSignsRecCount()
	{
		return vitalSignsRecs.size();
	}
	public VitalSignsRec getVitalSignsRecByIndex(int index)
	{
		return vitalSignsRecs.get(index);
	}
	public void addVitalSignsRec(VitalSignsRec value)
	{
		vitalSignsRecs.add(value);
	}
	public void removeVitalSignsRecByIndex(int index)
	{
		vitalSignsRecs.remove(index);
	}
	// 检查记录
	private List<ExamMaster> examMasters = new ArrayList<ExamMaster>();
	public int getExamMasterCount()
	{
		return examMasters.size();
	}
	public ExamMaster getExamMasterByIndex(int index)
	{
		return examMasters.get(index);
	}
	public void addExamMaster(ExamMaster value)
	{
		examMasters.add(value);
	}
	public void removeExamMasterByIndex(int index)
	{
		examMasters.remove(index);
	}
	// 微生物检验记录
	private List<GermTest> germTests = new ArrayList<GermTest>();
	public int getGermTestCount()
	{
		return germTests.size();
	}
	public GermTest getGermTestByIndex(int index)
	{
		return germTests.get(index);
	}
	public void addGermTest(GermTest value)
	{
		germTests.add(value);
	}
	public void removeGermTestByIndex(int index)
	{
		germTests.remove(index);
	}
	// 检测记录
	private List<LabTestMaster> labTestMaster = new ArrayList<LabTestMaster>();
	public int getLabTestMasterCount()
	{
		return labTestMaster.size();
	}
	public LabTestMaster getLabTestMasterByIndex(int index)
	{
		return labTestMaster.get(index);
	}
	public void addLabTestMaster(LabTestMaster value)
	{
		labTestMaster.add(value);
	}
	public void removeLabTestMasterByIndex(int index)
	{
		labTestMaster.remove(index);
	}
	//
	private List<GermTestResult> germTestResults = new ArrayList<GermTestResult>();
	public int getGermTestResultCount()
	{
		return germTestResults.size();
	}
	public GermTestResult getGermTestResultByIndex(int index)
	{
		return germTestResults.get(index);
	}
	public void addGermTestResult(GermTestResult value)
	{
		germTestResults.add(value);
	}
	public void removeGermTestResultByIndex(int index)
	{
		germTestResults.remove(index);
	}

	public String getAdmission_Cause() {
		return admissionCause;
	}

	public void setAdmission_Cause(String admissionCause) {
		this.admissionCause = admissionCause;
	}

	public Date getAdmission_Date_Time() {
		return admissionDateTime;
	}

	public void setAdmission_Date_Time(Date admissionDateTime) {
		this.admissionDateTime = admissionDateTime;
	}

	public String getAdmitted_By() {
		return admittedBy;
	}

	public void setAdmitted_By(String admittedBy) {
		this.admittedBy = admittedBy;
	}

	public String getAdvanced_Studies_Doctor() {
		return advancedStudiesDoctor;
	}

	public void setAdvanced_Studies_Doctor(String advancedStudiesDoctor) {
		this.advancedStudiesDoctor = advancedStudiesDoctor;
	}

	public String getAdverse_Reaction_Drugs() {
		return adverseReactionDrugs;
	}

	public void setAdverse_Reaction_Drugs(String adverseReactionDrugs) {
		this.adverseReactionDrugs = adverseReactionDrugs;
	}

	public String getAlergy_Drugs() {
		return alergyDrugs;
	}

	public void setAlergy_Drugs(String alergyDrugs) {
		this.alergyDrugs = alergyDrugs;
	}

	public String getArmed_Services() {
		return armedServices;
	}

	public void setArmed_Services(String armedServices) {
		this.armedServices = armedServices;
	}

	public String getAttending_Doctor() {
		return attendingDoctor;
	}

	public void setAttending_Doctor(String attendingDoctor) {
		this.attendingDoctor = attendingDoctor;
	}

	public Long getAutopsy_Indicator() {
		return autopsyIndicator;
	}

	public void setAutopsy_Indicator(Long autopsyIndicator) {
		this.autopsyIndicator = autopsyIndicator;
	}

	public Long getBlood_TranReact_Times() {
		return bloodTranReactTimes;
	}

	public void setBlood_TranReact_Times(Long bloodTranReactTimes) {
		this.bloodTranReactTimes = bloodTranReactTimes;
	}

	public Long getBlood_Tran_Times() {
		return bloodTranTimes;
	}

	public void setBlood_Tran_Times(Long bloodTranTimes) {
		this.bloodTranTimes = bloodTranTimes;
	}

	public Long getBlood_Tran_Vol() {
		return bloodTranVol;
	}

	public void setBlood_Tran_Vol(Long bloodTranVol) {
		this.bloodTranVol = bloodTranVol;
	}

	public String getBlood_Type() {
		return bloodType;
	}

	public void setBlood_Type(String bloodType) {
		this.bloodType = bloodType;
	}

	public String getBlood_Type_Rh() {
		return bloodTypeRh;
	}

	public void setBlood_Type_Rh(String bloodTypeRh) {
		this.bloodTypeRh = bloodTypeRh;
	}

	public Double getBody_Height() {
		return bodyHeight;
	}

	public void setBody_Height(Double bodyHeight) {
		this.bodyHeight = bodyHeight;
	}

	public Double getBody_Weight() {
		return bodyWeight;
	}

	public void setBody_Weight(Double bodyWeight) {
		this.bodyWeight = bodyWeight;
	}

	public Date getCatalog_Date() {
		return catalogDate;
	}

	public void setCatalog_Date(Date catalogDate) {
		this.catalogDate = catalogDate;
	}

	public String getCataloger() {
		return cataloger;
	}

	public void setCataloger(String cataloger) {
		this.cataloger = cataloger;
	}

	public String getCatalog_Writer() {
		return catalogWriter;
	}

	public void setCatalog_Writer(String catalogWriter) {
		this.catalogWriter = catalogWriter;
	}

	public Long getCcu_Days() {
		return ccuDays;
	}

	public void setCcu_Days(Long ccuDays) {
		this.ccuDays = ccuDays;
	}

	public String getCharge_Type() {
		return chargeType;
	}

	public void setCharge_Type(String chargeType) {
		this.chargeType = chargeType;
	}

	public String getChief_Doctor() {
		return chiefDoctor;
	}

	public void setChief_Doctor(String chiefDoctor) {
		this.chiefDoctor = chiefDoctor;
	}

	public Date getConsulting_Date() {
		return consultingDate;
	}

	public void setConsulting_Date(Date consultingDate) {
		this.consultingDate = consultingDate;
	}

	public String getConsulting_Doctor() {
		return consultingDoctor;
	}

	public void setConsulting_Doctor(String consultingDoctor) {
		this.consultingDoctor = consultingDoctor;
	}

	public Long getCritical_Cond_Days() {
		return criticalCondDays;
	}

	public void setCritical_Cond_Days(Long criticalCondDays) {
		this.criticalCondDays = criticalCondDays;
	}

	public Date getDate_Of_Control_Quality() {
		return dateOfControlQuality;
	}

	public void setDate_Of_Control_Quality(Date dateOfControlQuality) {
		this.dateOfControlQuality = dateOfControlQuality;
	}

	public Long getDecubital_Ulcer_Times() {
		return decubitalUlcerTimes;
	}

	public void setDecubital_Ulcer_Times(Long decubitalUlcerTimes) {
		this.decubitalUlcerTimes = decubitalUlcerTimes;
	}

	public String getDept_Admission_To() {
		return deptAdmissionTo;
	}

	public void setDept_Admission_To(String deptAdmissionTo) {
		this.deptAdmissionTo = deptAdmissionTo;
	}

	public String getDept_Discharge_From() {
		return deptDischargeFrom;
	}

	public void setDept_Discharge_From(String deptDischargeFrom) {
		this.deptDischargeFrom = deptDischargeFrom;
	}

	public String getDirector() {
		return director;
	}

	public void setDirector(String director) {
		this.director = director;
	}

	public Date getDischarge_Date_Time() {
		return dischargeDateTime;
	}

	public void setDischarge_Date_Time(Date dischargeDateTime) {
		this.dischargeDateTime = dischargeDateTime;
	}

	public String getDischarge_Disposition() {
		return dischargeDisposition;
	}

	public void setDischarge_Disposition(String dischargeDisposition) {
		this.dischargeDisposition = dischargeDisposition;
	}

	public String getDoctor_In_Charge() {
		return doctorInCharge;
	}

	public void setDoctor_In_Charge(String doctorInCharge) {
		this.doctorInCharge = doctorInCharge;
	}

	public String getDoctor_Of_Control_Quality() {
		return doctorOfControlQuality;
	}

	public void setDoctor_Of_Control_Quality(String doctorOfControlQuality) {
		this.doctorOfControlQuality = doctorOfControlQuality;
	}

	public String getDuty() {
		return duty;
	}

	public void setDuty(String duty) {
		this.duty = duty;
	}

	public Long getEmer_Treat_Times() {
		return emerTreatTimes;
	}

	public void setEmer_Treat_Times(Long emerTreatTimes) {
		this.emerTreatTimes = emerTreatTimes;
	}

	public Long getEsc_Emer_Times() {
		return escEmerTimes;
	}

	public void setEsc_Emer_Times(Long escEmerTimes) {
		this.escEmerTimes = escEmerTimes;
	}

	public Long getFirst_Aid_Indicator() {
		return firstAidIndicator;
	}

	public void setFirst_Aid_Indicator(Long firstAidIndicator) {
		this.firstAidIndicator = firstAidIndicator;
	}

	public Long getFirst_Case_Indicator() {
		return firstCaseIndicator;
	}

	public void setFirst_Case_Indicator(Long firstCaseIndicator) {
		this.firstCaseIndicator = firstCaseIndicator;
	}

	public Long getFirst_Level_Nurs_Days() {
		return firstLevelNursDays;
	}

	public void setFirst_Level_Nurs_Days(Long firstLevelNursDays) {
		this.firstLevelNursDays = firstLevelNursDays;
	}

	public Long getFollow_Indicator() {
		return followIndicator;
	}

	public void setFollow_Indicator(Long followIndicator) {
		this.followIndicator = followIndicator;
	}

	public Long getFollow_Interval() {
		return followInterval;
	}

	public void setFollow_Interval(Long followInterval) {
		this.followInterval = followInterval;
	}

	public String getFollow_Interval_Units() {
		return followIntervalUnits;
	}

	public void setFollow_Interval_Units(String followIntervalUnits) {
		this.followIntervalUnits = followIntervalUnits;
	}

	public Long getHbsag_Indicator() {
		return hbsagIndicator;
	}

	public void setHbsag_Indicator(Long hbsagIndicator) {
		this.hbsagIndicator = hbsagIndicator;
	}

	public Long getHcv_Ab_Indicator() {
		return hcvAbIndicator;
	}

	public void setHcv_Ab_Indicator(Long hcvAbIndicator) {
		this.hcvAbIndicator = hcvAbIndicator;
	}

	public String getHealth_Level() {
		return healthLevel;
	}

	public void setHealth_Level(String healthLevel) {
		this.healthLevel = healthLevel;
	}

	public Long getHiv_Ab_Indicator() {
		return hivAbIndicator;
	}

	public void setHiv_Ab_Indicator(Long hivAbIndicator) {
		this.hivAbIndicator = hivAbIndicator;
	}

	public Long getIcu_Days() {
		return icuDays;
	}

	public void setIcu_Days(Long icuDays) {
		this.icuDays = icuDays;
	}

	public String getIdentity() {
		return identity;
	}

	public void setIdentity(String identity) {
		this.identity = identity;
	}

	public String getIdentity_Class() {
		return identityClass;
	}

	public void setIdentity_Class(String identityClass) {
		this.identityClass = identityClass;
	}

	public Long getIn_Clinic_Attr() {
		return inClinicAttr;
	}

	public void setIn_Clinic_Attr(Long inClinicAttr) {
		this.inClinicAttr = inClinicAttr;
	}

	public String getIn_Dept_Name() {
		return inDeptName;
	}

	public void setIn_Dept_Name(String inDeptName) {
		this.inDeptName = inDeptName;
	}

	public Long getInfect_Indicator() {
		return infectIndicator;
	}

	public void setInfect_Indicator(Long infectIndicator) {
		this.infectIndicator = infectIndicator;
	}

	public Long getInfusion_React_Times() {
		return infusionReactTimes;
	}

	public void setInfusion_React_Times(Long infusionReactTimes) {
		this.infusionReactTimes = infusionReactTimes;
	}

	public Long getIn_Internal_Or_Sergery() {
		return inInternalOrSergery;
	}

	public void setIn_Internal_Or_Sergery(Long inInternalOrSergery) {
		this.inInternalOrSergery = inInternalOrSergery;
	}

	public Long getIn_Outp_Or_Inp() {
		return inOutpOrInp;
	}

	public void setIn_Outp_Or_Inp(Long inOutpOrInp) {
		this.inOutpOrInp = inOutpOrInp;
	}

	public String getInsurance_No() {
		return insuranceNo;
	}

	public void setInsurance_No(String insuranceNo) {
		this.insuranceNo = insuranceNo;
	}

	public String getInsurance_Type() {
		return insuranceType;
	}

	public void setInsurance_Type(String insuranceType) {
		this.insuranceType = insuranceType;
	}

	public String getInternal_No() {
		return internalNo;
	}

	public void setInternal_No(String internalNo) {
		this.internalNo = internalNo;
	}

	public Date getLink_Date() {
		return linkDate;
	}

	public void setLink_Date(Date linkDate) {
		this.linkDate = linkDate;
	}

	public String getMailing_Address() {
		return mailingAddress;
	}

	public void setMailing_Address(String mailingAddress) {
		this.mailingAddress = mailingAddress;
	}

	public String getMarital_Status() {
		return maritalStatus;
	}

	public void setMarital_Status(String maritalStatus) {
		this.maritalStatus = maritalStatus;
	}

	public String getMedical_Pay_Way() {
		return medicalPayWay;
	}

	public void setMedical_Pay_Way(String medicalPayWay) {
		this.medicalPayWay = medicalPayWay;
	}

	public String getMr_Infect_Report() {
		return mrInfectReport;
	}

	public void setMr_Infect_Report(String mrInfectReport) {
		this.mrInfectReport = mrInfectReport;
	}

	public String getMr_Quality() {
		return mrQuality;
	}

	public void setMr_Quality(String mrQuality) {
		this.mrQuality = mrQuality;
	}

	public String getMr_Value() {
		return mrValue;
	}

	public void setMr_Value(String mrValue) {
		this.mrValue = mrValue;
	}

	public String getNext_Of_Kin() {
		return nextOfKin;
	}

	public void setNext_Of_Kin(String nextOfKin) {
		this.nextOfKin = nextOfKin;
	}

	public String getNext_Of_Kin_Addr() {
		return nextOfKinAddr;
	}

	public void setNext_Of_Kin_Addr(String nextOfKinAddr) {
		this.nextOfKinAddr = nextOfKinAddr;
	}

	public String getNext_Of_Kin_Phone() {
		return nextOfKinPhone;
	}

	public void setNext_Of_Kin_Phone(String nextOfKinPhone) {
		this.nextOfKinPhone = nextOfKinPhone;
	}

	public String getNext_Of_Kin_Zipcode() {
		return nextOfKinZipcode;
	}

	public void setNext_Of_Kin_Zipcode(String nextOfKinZipcode) {
		this.nextOfKinZipcode = nextOfKinZipcode;
	}

	public String getNurse_Of_Control_Quality() {
		return nurseOfControlQuality;
	}

	public void setNurse_Of_Control_Quality(String nurseOfControlQuality) {
		this.nurseOfControlQuality = nurseOfControlQuality;
	}

	public String getOccupation() {
		return occupation;
	}

	public void setOccupation(String occupation) {
		this.occupation = occupation;
	}

	public Long getOut_Clinic_Attr() {
		return outClinicAttr;
	}

	public void setOut_Clinic_Attr(Long outClinicAttr) {
		this.outClinicAttr = outClinicAttr;
	}

	public String getOut_Dept_Name() {
		return outDeptName;
	}

	public void setOut_Dept_Name(String outDeptName) {
		this.outDeptName = outDeptName;
	}

	public Long getOut_Internal_Or_Sergery() {
		return outInternalOrSergery;
	}

	public void setOut_Internal_Or_Sergery(Long outInternalOrSergery) {
		this.outInternalOrSergery = outInternalOrSergery;
	}

	public Long getOut_Outp_Or_Inp() {
		return outOutpOrInp;
	}

	public void setOut_Outp_Or_Inp(Long outOutpOrInp) {
		this.outOutpOrInp = outOutpOrInp;
	}

	public String getPat_Adm_Condition() {
		return patAdmCondition;
	}

	public void setPat_Adm_Condition(String patAdmCondition) {
		this.patAdmCondition = patAdmCondition;
	}

	public String getPatient_Class() {
		return patientClass;
	}

	public void setPatient_Class(String patientClass) {
		this.patientClass = patientClass;
	}

	public String getPatient_Id() {
		return patientId;
	}

	public void setPatient_Id(String patientId) {
		this.patientId = patientId;
	}

	public String getPractice_Doctor() {
		return practiceDoctor;
	}

	public void setPractice_Doctor(String practiceDoctor) {
		this.practiceDoctor = practiceDoctor;
	}

	public String getPractice_Doctor_Of_Graduate() {
		return practiceDoctorOfGraduate;
	}

	public void setPractice_Doctor_Of_Graduate(String practiceDoctorOfGraduate) {
		this.practiceDoctorOfGraduate = practiceDoctorOfGraduate;
	}

	public String getRelationship() {
		return relationship;
	}

	public void setRelationship(String relationship) {
		this.relationship = relationship;
	}

	public Long getSecond_Level_Nurs_Days() {
		return secondLevelNursDays;
	}

	public void setSecond_Level_Nurs_Days(Long secondLevelNursDays) {
		this.secondLevelNursDays = secondLevelNursDays;
	}

	public Long getSerious_Cond_Days() {
		return seriousCondDays;
	}

	public void setSerious_Cond_Days(Long seriousCondDays) {
		this.seriousCondDays = seriousCondDays;
	}

	public String getService_Agency() {
		return serviceAgency;
	}

	public void setService_Agency(String serviceAgency) {
		this.serviceAgency = serviceAgency;
	}

	public Long getService_System_Indicator() {
		return serviceSystemIndicator;
	}

	public void setService_System_Indicator(Long serviceSystemIndicator) {
		this.serviceSystemIndicator = serviceSystemIndicator;
	}

	public Long getSettle_Indi() {
		return settleIndi;
	}

	public void setSettle_Indi(Long settleIndi) {
		this.settleIndi = settleIndi;
	}

	public Long getSpec_Level_Nurs_Days() {
		return specLevelNursDays;
	}

	public void setSpec_Level_Nurs_Days(Long specLevelNursDays) {
		this.specLevelNursDays = specLevelNursDays;
	}

	public Long getThird_Level_Nurs_Days() {
		return thirdLevelNursDays;
	}

	public void setThird_Level_Nurs_Days(Long thirdLevelNursDays) {
		this.thirdLevelNursDays = thirdLevelNursDays;
	}

	public String getTop_Unit() {
		return topUnit;
	}

	public void setTop_Unit(String topUnit) {
		this.topUnit = topUnit;
	}

	public Double getTotal_Costs() {
		return totalCosts;
	}

	public void setTotal_Costs(Double totalCosts) {
		this.totalCosts = totalCosts;
	}

	public Double getTotal_Payments() {
		return totalPayments;
	}

	public void setTotal_Payments(Double totalPayments) {
		this.totalPayments = totalPayments;
	}

	public Long getTraining_Injury_Indicator() {
		return trainingInjuryIndicator;
	}

	public void setTraining_Injury_Indicator(Long trainingInjuryIndicator) {
		this.trainingInjuryIndicator = trainingInjuryIndicator;
	}

	public String getUnit_In_Contract() {
		return unitInContract;
	}

	public void setUnit_In_Contract(String unitInContract) {
		this.unitInContract = unitInContract;
	}

	public Long getVisit_Id() {
		return visitId;
	}

	public void setVisit_Id(Long visitId) {
		this.visitId = visitId;
	}

	public Long getWorking_Status() {
		return workingStatus;
	}

	public void setWorking_Status(Long workingStatus) {
		this.workingStatus = workingStatus;
	}

	public String getXExam_No() {
		return XExamNo;
	}

	public void setXExam_No(String examNo) {
		XExamNo = examNo;
	}

	public String getZip_Code() {
		return zipCode;
	}

	public void setZip_Code(String zipCode) {
		this.zipCode = zipCode;
	}

}

redpajama_set_name: RedPajamaGithub


text:
module BillApi
  module Workflow
    class ApproveBill < Transition

      def perform
        @bill = Bill.find(@workflow.bill_id)
        @bill.comments.create(:body => @params["comment"], :base_contact => @workflow.initiator_email) unless @params["comment"].blank?
        @emails  = @params["recipient_emails"]
        @bill.events.create(:message =>"#{@workflow.initiator_email} переслал для визирования #{@emails.join(" , ")}")
        @emails.each do |e|
           permission = ApproverPermission.create(:bill_id => @bill.id , :base_contact => e )
           Notifier.deliver_approve_bill(:bill => @bill, :permission => permission , :comment => @params["comment"] )
        end
        @workflow.current_state = @params["to_state"]
      end

      def require_token?
        false
      end
    end
  end
end


text:
Q_Image
=======

```php
require_once '/path/to/Image/Autoloader.php';
Q_Image_Autoloader::register();
```

Rotate
------

```php
$image = new Q_Image('1.jpg');
$image->rotate(180);
$image->output(); // output image to browser
//$image->save('2.jpg'); // or save to file
```

Flip
----

```php
$image = new Q_Image('1.jpg');
$image->flip(true); // horizontal
//$image->flip(false, true); // or vertical
//$image->flip(true, true); // or horizontal and vertical
$image->output();
//$image->save('2.jpg');
```

Filter
------

```php
$image = new Q_Image('1.jpg');
$image->filter(IMG_FILTER_GRAYSCALE);
// or multiple filters
$image->filter(array(
    IMG_FILTER_GRAYSCALE,
    IMG_FILTER_EMBOSS
));
$image->output();
```

Resize
------

```php
$image = new Q_Image('1.jpg');
$image->resize(100, 100, Q_Image_Manipulation_Resize::NONE); // do not save proportion
//$image->resize(100, 100, Q_Image_Manipulation_Resize::LARGER_SIDE); // proportion save
//$image->resize(100, 100, Q_Image_Manipulation_Resize::SMALLER_SIDE); // proportion save
$image->output();
```

Crop
----

```php
$image = new Q_Image('1.jpg');
$image->crop(100, 100); // center center
//$image->crop(100, 100, Q_Image_Manipulation_Crop::CENTER, Q_Image_Manipulation_Crop::BOTTOM);
//$image->crop(100, 100, Q_Image_Manipulation_Crop::BOTTOM, Q_Image_Manipulation_Crop::CENTER);
//$image->crop(100, 100, Q_Image_Manipulation_Crop::BOTTOM, Q_Image_Manipulation_Crop::BOTTOM);
$image->output();
```


text:
import procgame
import procgame.config
import os
import sys
import yaml

def save_config():
	try:
		dirname = os.path.dirname(procgame.config.path)
		if not os.path.isdir(dirname):
			print("Creating directory: %s" % (dirname))
			os.makedirs(dirname)
		output = file(procgame.config.path, 'w')
		yaml.dump(procgame.config.values, output)
		del output
	except IOError:
		print("Error writing to configuration file at "+procgame.config.path)
		sys.exit(2)

def tool_populate_options(parser):
	parser.add_option('-k', '--key', action='store', help='The configuration key to be manipulated.')
	parser.add_option('-a', '--add', action='store', help='Add VALUE to list KEY.', metavar='VALUE')
	parser.add_option('-r', '--remove', action='store', help='Remove VALUE from list KEY.', metavar='VALUE')
	parser.add_option('-s', '--set', action='store', help='Assign the value of KEY to VALUE.', metavar='VALUE')
	parser.add_option('-c', '--clear', action='store_true', help='Removes KEY from the configuration.')

def tool_get_usage():
	return """[options]"""

def tool_run(options, args):
	no_values_loaded = (procgame.config.values == {})
	procgame.config.values = procgame.config.values or {}
	if options.key:
		if options.key not in procgame.config.values and not (options.add or options.set):
			print("Key does not exist.")
			sys.exit(3)

		if options.add or options.remove:
			if options.key in procgame.config.values and type(procgame.config.values[options.key]) != list:
				print("Cannot add or remove values from a key that does not have a list value.  Type is "+(type(procgame.config.values[options.key]).__name__))
				sys.exit(3)

			if options.add:
				if options.key not in procgame.config.values:
					procgame.config.values[options.key] = []
				procgame.config.values[options.key].append(options.add)
				save_config()
				return True
			if options.remove:
				procgame.config.values[options.key].remove(options.remove)
				save_config()
				return True

		if options.set:
			if options.key in procgame.config.values and type(procgame.config.values[options.key]) != str:
				print("Cannot assign a value to a key that is not a string.  Type is "+(type(procgame.config.values[options.key]).__name__))
				sys.exit(3)

			procgame.config.values[options.key] = options.set
			save_config()
			return True

		if options.clear:
			del procgame.config.values[options.key]
			save_config()
			return True

		print procgame.config.values[options.key]
		return True

	# If nothing else, show the file location and some diagnostic information:
	print("""Your configuration file is located at:""")
	print("")
	print("""  %s""" % (procgame.config.path))
	print("")

	if not os.path.exists(procgame.config.path):
		print 'Your configuration file does not exist.'
	elif no_values_loaded:
		print 'Your configuration file contains one or more errors and was not parsed successfully.'

	return True


text:
package org.apereo.cas.web.flow.actions;

import org.apereo.cas.services.RegisteredServiceMultifactorPolicyFailureModes;
import org.apereo.cas.web.flow.CasWebflowConstants;
import org.apereo.cas.web.support.WebUtils;

import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.context.ApplicationContext;
import org.springframework.webflow.action.EventFactorySupport;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
 * Action executed to determine how a MFA provider should fail if unavailable.
 *
 * @author Travis Schmidt
 * @since 5.3.4
 */
@Slf4j
public class MultifactorAuthenticationFailureAction extends AbstractMultifactorAuthenticationAction {
    public MultifactorAuthenticationFailureAction(final ApplicationContext applicationContext) {
        super(applicationContext);
    }

    @Override
    protected Event doExecute(final RequestContext requestContext) {
        val service = WebUtils.getRegisteredService(requestContext);
        val failureMode = provider.getFailureModeEvaluator().evaluate(service, provider);

        LOGGER.debug("Final failure mode has been determined to be [{}]", failureMode);

        if (failureMode == RegisteredServiceMultifactorPolicyFailureModes.OPEN) {
            return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_BYPASS);
        }

        return new EventFactorySupport().event(this, CasWebflowConstants.TRANSITION_ID_UNAVAILABLE);
    }

}


text:
#region Apache License Version 2.0

#endregion Apache License Version 2.0

using SF.Sys.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace SF.Auth.IdentityServices.DataModels
{
	public class DataUserRole: DataUserRole<DataUser, DataUserCredential, DataUserClaimValue, DataUserRole>
	{

	}
	[Table("UserRole")]
	public class DataUserRole<TUser, TUserCredential, TUserClaimValue, TUserRole>
		where TUser : DataUser<TUser, TUserCredential, TUserClaimValue, TUserRole>
		where TUserCredential : DataUserCredential<TUser, TUserCredential, TUserClaimValue, TUserRole>
		where TUserClaimValue : DataUserClaimValue<TUser, TUserCredential, TUserClaimValue, TUserRole>
		where TUserRole : DataUserRole<TUser, TUserCredential, TUserClaimValue, TUserRole>
	{
		[Key]
		[Column(Order =1)]
		public long UserId { get; set; }

		[ForeignKey(nameof(UserId))]
		public TUser User { get; set; }

		/// <summary>
		/// 角色
		/// </summary>
		[Key]
		[Column(Order = 1)]
		[Index]
		public string RoleId { get; set; }

		[ForeignKey(nameof(RoleId))]
		public DataRole Role { get; set; }
	}
}


text:
<?php

declare(strict_types=1);

namespace Ixocreate\ServiceManager;

interface InitializerInterface
{
    /**
     * @param ServiceManagerInterface $container
     * @param $instance
     * @return void
     */
    public function __invoke(ServiceManagerInterface $container, $instance): void;
}


text:
class VotesController < ApplicationController

  # First, figure out our nested scope. User or Voteable?
  before_filter :find_votes_for_my_scope, :only => [:index]

  before_filter :login_required, :only => [:new, :edit, :destroy, :create, :update]
  before_filter :must_own_vote,  :only => [:edit, :destroy, :update]
  before_filter :not_allowed,    :only => [:edit, :update, :new]

  # GET /users/:user_id/votes/
  # GET /users/:user_id/votes.xml
  # GET /users/:user_id/voteables/:voteable_id/votes/
  # GET /users/:user_id/voteables/:voteable_id/votes.xml
  def index
    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @votes }
    end
  end

  # GET /users/:user_id/votes/1
  # GET /users/:user_id/votes/1.xml
  # GET /users/:user_id/voteables/:voteable_id/votes/1
  # GET /users/:user_id/voteables/:voteable_id/1.xml
  def show
    @voteable = Vote.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @vote }
    end
  end

  # GET /users/:id/votes/new
  # GET /users/:id/votes/new.xml
  # GET /users/:id/votes/new
  # GET /users/:id/votes/new.xml
  def new
    # Not generally used. Most people want to vote via AJAX calls.
  end

  # GET /users/:id/votes/1/edit
  def edit
    # Not generally used. Most people don't want to allow editing of votes.
  end

  # POST /users/:user_id/voteables/:voteable_id/votes
  # POST /users/:user_id/voteables/:voteable_id/votes.xml
  def create
    @voteable = Voteable.find(params[:quote_id])

    respond_to do |format|
      if current_user.vote(@voteable, params[:vote])
        format.rjs  { render :action => "create", :vote => @vote }
        format.html { redirect_to([@voteable.user, @voteable]) }
        format.xml  { render :xml => @voteable, :status => :created, :location => @voteable }
      else
        format.rjs  { render :action => "error" }
        format.html { render :action => "new" }
        format.xml  { render :xml => @vote.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /users/:id/votes/1
  # PUT /users/:id/votes/1.xml
  def update
    # Not generally used
  end

  # DELETE /users/:id/votes/1
  # DELETE /users/:id/votes/1.xml
  def destroy
    @vote = Vote.find(params[:id])
    @vote.destroy

    respond_to do |format|
      format.html { redirect_to(user_votes_url) }
      format.xml  { head :ok }
    end
  end

  private
  def find_votes_for_my_scope
    if params[:voteable_id]
      @votes = Vote.for_voteable(Voteable.find(params[:voteable_id])).descending
    elsif params[:user_id]
      @votes = Vote.for_voter(User.find(params[:user_id])).descending
    else
      @votes = []
    end
  end

  def must_own_vote
    @vote ||= Vote.find(params[:id])
    @vote.user == current_user || ownership_violation
  end

  def ownership_violation
    respond_to do |format|
      flash[:notice] = 'You cannot edit or delete votes that you do not own!'
      format.html do
        redirect_to user_path(current_user)
      end
    end
  end

end


text:
#ifndef _DATAFILEREADERPFIELD_H_
#define _DATAFILEREADERPFIELD_H_

#include <PField.h>
#include <DataFile.h>

class Oonepole;

class DataFileReaderPField : public RTNumberPField {
public:
	DataFileReaderPField(
		const char   *fileName,
		const double lag,
		const int    controlRate,
		const double skipTime = 0.0,     // time to skip (pre-scale) before read
		const double timeFactor = 1.0,   // scale stream duration
		// Use the following if the data file has no header.
		const int    defaultFileRate = -1,
		const int    defaultFormat = kDataFormatFloat,
		const bool   defaultSwap = false);

	virtual double doubleValue(double) const;

protected:
	virtual ~DataFileReaderPField();

private:
	DataFile *_datafile;
	Oonepole *_filter;
};

#endif // _DATAFILEREADERPFIELD_H_


text:
import netaddr
import sqlalchemy as sa
from sqlalchemy import orm
from sqlalchemy import sql

from neutron.api.rpc.agentnotifiers import metering_rpc_agent_api
from neutron.common import constants
from neutron.db import common_db_mixin as base_db
from neutron.db import l3_db
from neutron.db import model_base
from neutron.db import models_v2
from neutron.extensions import metering
from neutron.openstack.common import log as logging
from neutron.openstack.common import uuidutils

LOG = logging.getLogger(__name__)

class MeteringLabelRule(model_base.BASEV2, models_v2.HasId):
    direction = sa.Column(sa.Enum('ingress', 'egress',
                                  name='meteringlabels_direction'))
    remote_ip_prefix = sa.Column(sa.String(64))
    metering_label_id = sa.Column(sa.String(36),
                                  sa.ForeignKey("meteringlabels.id",
                                                ondelete="CASCADE"),
                                  nullable=False)
    excluded = sa.Column(sa.Boolean, default=False, server_default=sql.false())

class MeteringLabel(model_base.BASEV2, models_v2.HasId, models_v2.HasTenant):
    name = sa.Column(sa.String(255))
    description = sa.Column(sa.String(1024))
    rules = orm.relationship(MeteringLabelRule, backref="label",
                             cascade="delete", lazy="joined")
    routers = orm.relationship(
        l3_db.Router,
        primaryjoin="MeteringLabel.tenant_id==Router.tenant_id",
        foreign_keys='MeteringLabel.tenant_id',
        uselist=True)
    shared = sa.Column(sa.Boolean, default=False, server_default=sql.false())

class MeteringDbMixin(metering.MeteringPluginBase,
                      base_db.CommonDbMixin):

    def __init__(self):
        self.meter_rpc = metering_rpc_agent_api.MeteringAgentNotifyAPI()

    def _make_metering_label_dict(self, metering_label, fields=None):
        res = {'id': metering_label['id'],
               'name': metering_label['name'],
               'description': metering_label['description'],
               'shared': metering_label['shared'],
               'tenant_id': metering_label['tenant_id']}
        return self._fields(res, fields)

    def create_metering_label(self, context, metering_label):
        m = metering_label['metering_label']
        tenant_id = self._get_tenant_id_for_create(context, m)

        with context.session.begin(subtransactions=True):
            metering_db = MeteringLabel(id=uuidutils.generate_uuid(),
                                        description=m['description'],
                                        tenant_id=tenant_id,
                                        name=m['name'],
                                        shared=m['shared'])
            context.session.add(metering_db)

        return self._make_metering_label_dict(metering_db)

    def delete_metering_label(self, context, label_id):
        with context.session.begin(subtransactions=True):
            try:
                label = self._get_by_id(context, MeteringLabel, label_id)
            except orm.exc.NoResultFound:
                raise metering.MeteringLabelNotFound(label_id=label_id)

            context.session.delete(label)

    def get_metering_label(self, context, label_id, fields=None):
        try:
            metering_label = self._get_by_id(context, MeteringLabel, label_id)
        except orm.exc.NoResultFound:
            raise metering.MeteringLabelNotFound(label_id=label_id)

        return self._make_metering_label_dict(metering_label, fields)

    def get_metering_labels(self, context, filters=None, fields=None,
                            sorts=None, limit=None, marker=None,
                            page_reverse=False):
        marker_obj = self._get_marker_obj(context, 'metering_labels', limit,
                                          marker)
        return self._get_collection(context, MeteringLabel,
                                    self._make_metering_label_dict,
                                    filters=filters, fields=fields,
                                    sorts=sorts,
                                    limit=limit,
                                    marker_obj=marker_obj,
                                    page_reverse=page_reverse)

    def _make_metering_label_rule_dict(self, metering_label_rule, fields=None):
        res = {'id': metering_label_rule['id'],
               'metering_label_id': metering_label_rule['metering_label_id'],
               'direction': metering_label_rule['direction'],
               'remote_ip_prefix': metering_label_rule['remote_ip_prefix'],
               'excluded': metering_label_rule['excluded']}
        return self._fields(res, fields)

    def get_metering_label_rules(self, context, filters=None, fields=None,
                                 sorts=None, limit=None, marker=None,
                                 page_reverse=False):
        marker_obj = self._get_marker_obj(context, 'metering_label_rules',
                                          limit, marker)

        return self._get_collection(context, MeteringLabelRule,
                                    self._make_metering_label_rule_dict,
                                    filters=filters, fields=fields,
                                    sorts=sorts,
                                    limit=limit,
                                    marker_obj=marker_obj,
                                    page_reverse=page_reverse)

    def get_metering_label_rule(self, context, rule_id, fields=None):
        try:
            metering_label_rule = self._get_by_id(context,
                                                  MeteringLabelRule, rule_id)
        except orm.exc.NoResultFound:
            raise metering.MeteringLabelRuleNotFound(rule_id=rule_id)

        return self._make_metering_label_rule_dict(metering_label_rule, fields)

    def _validate_cidr(self, context, label_id, remote_ip_prefix,
                       direction, excluded):
        r_ips = self.get_metering_label_rules(context,
                                              filters={'metering_label_id':
                                                       label_id,
                                                       'direction':
                                                       [direction],
                                                       'excluded':
                                                       [excluded]},
                                              fields=['remote_ip_prefix'])

        cidrs = [r['remote_ip_prefix'] for r in r_ips]
        new_cidr_ipset = netaddr.IPSet([remote_ip_prefix])
        if (netaddr.IPSet(cidrs) & new_cidr_ipset):
            raise metering.MeteringLabelRuleOverlaps(
                remote_ip_prefix=remote_ip_prefix)

    def create_metering_label_rule(self, context, metering_label_rule):
        m = metering_label_rule['metering_label_rule']
        with context.session.begin(subtransactions=True):
            label_id = m['metering_label_id']
            ip_prefix = m['remote_ip_prefix']
            direction = m['direction']
            excluded = m['excluded']

            self._validate_cidr(context, label_id, ip_prefix, direction,
                                excluded)
            metering_db = MeteringLabelRule(id=uuidutils.generate_uuid(),
                                            metering_label_id=label_id,
                                            direction=direction,
                                            excluded=m['excluded'],
                                            remote_ip_prefix=ip_prefix)
            context.session.add(metering_db)

        return self._make_metering_label_rule_dict(metering_db)

    def delete_metering_label_rule(self, context, rule_id):
        with context.session.begin(subtransactions=True):
            try:
                rule = self._get_by_id(context, MeteringLabelRule, rule_id)
            except orm.exc.NoResultFound:
                raise metering.MeteringLabelRuleNotFound(rule_id=rule_id)

            context.session.delete(rule)

    def _get_metering_rules_dict(self, metering_label):
        rules = []
        for rule in metering_label.rules:
            rule_dict = self._make_metering_label_rule_dict(rule)
            rules.append(rule_dict)

        return rules

    def _make_router_dict(self, router):
        res = {'id': router['id'],
               'name': router['name'],
               'tenant_id': router['tenant_id'],
               'admin_state_up': router['admin_state_up'],
               'status': router['status'],
               'gw_port_id': router['gw_port_id'],
               constants.METERING_LABEL_KEY: []}

        return res

    def _process_sync_metering_data(self, context, labels):
        all_routers = None

        routers_dict = {}
        for label in labels:
            if label.shared:
                if not all_routers:
                    all_routers = self._get_collection_query(context,
                                                             l3_db.Router)
                routers = all_routers
            else:
                routers = label.routers

            for router in routers:
                router_dict = routers_dict.get(
                    router['id'],
                    self._make_router_dict(router))

                rules = self._get_metering_rules_dict(label)

                data = {'id': label['id'], 'rules': rules}
                router_dict[constants.METERING_LABEL_KEY].append(data)

                routers_dict[router['id']] = router_dict

        return routers_dict.values()

    def get_sync_data_metering(self, context, label_id=None, router_ids=None):
        labels = context.session.query(MeteringLabel)

        if label_id:
            labels = labels.filter(MeteringLabel.id == label_id)
        elif router_ids:
            labels = (labels.join(MeteringLabel.routers).
                      filter(l3_db.Router.id.in_(router_ids)))

        return self._process_sync_metering_data(context, labels)


text:
using System;
using System.Threading.Tasks;
using Apollo.CommandSystem;
using Apollo.Data;
using Apollo.Services;

namespace Apollo.Commands.Metrics
{
    public class AddMetric : AuthenticatedCommand
    {
        private readonly IMetricsDataService metricsDataService;

        public string category { get; set; }
        public string name { get; set; }
        public decimal value { get; set; }

        public AddMetric(
            ILoginService loginService,
            IMetricsDataService metricsDataService
        ) : base(loginService)
        {
            Logger.Trace("Created AddMetric Instance");
            this.metricsDataService = metricsDataService;
            this.value = default(decimal);
        }

        public override async Task<CommandResult> Execute()
        {
            Logger.Trace("Began Executing AddMetric");
            var newMetric = await this.metricsDataService.InsertMetric(category, name, value);
            Logger.Trace("Left Data Service");
            return CommandResult.CreateSuccessResult(newMetric);
        }

        public override Task<bool> IsValid()
        {
            if (string.IsNullOrWhiteSpace(category) ||
                string.IsNullOrWhiteSpace(name))
                return Task.FromResult(false);
            return Task.FromResult(true);
        }

        public override object ExamplePayload()
        {
            return new { category, name, value};
        }
    }
}


text:
// Dependencies
const assetCache = require('../index');
const chai = require('chai');
const gutil = require('gulp-util');
const fs = require('fs');

const expect = chai.expect;

// Utility Functions
const throwErr = function (err) {
  if (err) throw err;
};

describe('gulp-asset-cache', function () {
  const testFoo = 'test/fixtures/foo.jpg';
  const testBar = 'test/fixtures/bar.jpg';
  const testBaz = 'test/fixtures/baz.jpg';
  const fileFoo = new gutil.File({ path: `./${testFoo}`, contents: Buffer.from('Foo'), stat: { size: 100 } });
  const fileBar = new gutil.File({ path: `./${testBar}`, contents: Buffer.from('Bar'), stat: { size: 100 } });
  const fileBaz = new gutil.File({ path: `./${testBaz}`, contents: Buffer.from('Baz'), stat: { size: 100 } });

  describe('without a cache file', function () {
    beforeEach(function () {
      // Reset Cache stored in mem
      assetCache.currentCache = {};
    });

    /**
     * Test 1 - Default cache file should be created with the keys of foo.jpg and bar.jpg
     * @results Test confirms that the default file is being written with new files being added
     */
    it('Default file should be created with Foo and Bar', function (done) {
      const stream = assetCache.filter();
      stream.pipe(assetCache.cache());

      stream.on('finish', function () {
        // Add a dealy to make sure the file is finished writing before reading
        setTimeout(function run() {
          fs.readFile('./.asset-cache', 'utf8', function (err, data) {
            throwErr(err);
            expect(JSON.parse(data)).to.have.keys([testFoo, testBar]);
            done();
          });
        }, 500);
      });

      stream.write(fileFoo);
      stream.write(fileBar);
      stream.end();
    });

    /**
     * Test 2 - Cache file should be created with the keys of foo.jpg, bar.jpg, and baz.jpg
     * @results Test confirms that file is being written with new files being added
     */
    it('Foo, Bar, and Baz should show as uncached and be added to a specified cache file', function (done) {
      const stream = assetCache.filter('./test/.test-new-cache');
      stream.pipe(assetCache.cache());

      stream.on('finish', function () {
        // Add a delay to make sure the file is finished writing before reading
        setTimeout(function () {
          fs.readFile('./test/.test-new-cache', 'utf8', function (err, data) {
            throwErr(err);
            expect(JSON.parse(data)).to.have.keys([testFoo, testBar, testBaz]);
            done();
          });
        }, 500);
      });

      stream.write(fileFoo);
      stream.write(fileBar);
      stream.write(fileBaz);
      stream.end();
    });

    // After - Clean up test directory
    after(function () {
      fs.unlink('./test/.test-new-cache', throwErr);
      fs.unlink('./.asset-cache', throwErr);
    });
  });

  describe('with an existing cache', function () {
    // Before - Set up Existing Cache Files for testing
    before(function () {
      fs.writeFile('./test/.test-update-cache', JSON.stringify({
        'test/fixtures/foo.jpg': '9a00e3f54e6a23ee446348a075ddcfb1'
      }, null, 4), 'utf8', throwErr);
      fs.writeFile('./test/.test-stored-cache', JSON.stringify({
        'test/fixtures/foo.jpg': 'b432aa22f80486078aa53e6e5c64ddb3',
        'test/fixtures/bar.jpg': '976c38a5095dc3dd31c85e2ca1fbbc50'
      }, null, 4), 'utf8', throwErr);
    });

    // Reset Cache in mem
    beforeEach(function () {
      assetCache.currentCache = {};
    });

    /**
     * Test 2 - foo.jpg should be removed from the cache, and bar.jpg and baz.jpg should be added
     * @results Test confirms that files are both being added and removed from the cache
     */
    it('Bar and Baz should be added to a stored cache file, Foo should be removed.', function (done) {
      const stream = assetCache.filter('./test/.test-update-cache');
      stream.pipe(assetCache.cache());

      stream.on('finish', function () {
        // Add a delay to make sure the file is finished writing before reading
        setTimeout(function () {
          fs.readFile('./test/.test-update-cache', 'utf8', function (err, data) {
            throwErr(err);
            const cacheObj = JSON.parse(data);
            expect(cacheObj).to.have.keys([testBar, testBaz]);
            expect(cacheObj).to.not.have.keys([testFoo]);
            done();
          });
        }, 500);
      });

      stream.write(fileBar);
      stream.write(fileBaz);
      stream.end();
    });

    /**
     * Test 3 - foo.jpg and bar.jpg should be recognized as cached while baz.jpg should be uncached
     * @results Test confirms that files are being recognized properly when cached
     */
    it('Foo and Bar should show as cached while Baz is uncached and added to the cache file.', function (done) {
      const stream = assetCache.filter('./test/.test-stored-cache');
      stream.pipe(assetCache.cache());

      stream.on('finish', function () {
        // Add a delay to make sure the file is finished writing before reading
        setTimeout(function () {
          fs.readFile('./test/.test-stored-cache', 'utf8', function (err, data) {
            throwErr(err);
            expect(JSON.parse(data)).to.have.keys([testFoo, testBar, testBaz]);
            done();
          });
        }, 500);
      });

      stream.write(fileFoo);
      stream.write(fileBar);
      stream.write(fileBaz);
      stream.end();
    });

    // After - Clean up test directory
    after(function () {
      fs.unlink('./test/.test-update-cache', throwErr);
      fs.unlink('./test/.test-stored-cache', throwErr);
    });
  });
});


text:
windows_sharepoint

This is the windows_sharepoint module.

##Module Description

This module allow you to manage user and group in SharePoint 2013. Allow you to install and configure SharePoint 2013
You can found this module on the forge [jriviere/windows_sharepoint](https://forge.puppetlabs.com/jriviere/windows_sharepoint) or on [GitHub](https://github.com/insentia/windows_sharepoint)

This module use the [AutoSPInstaller Project](http://autospinstaller.codeplex.com/) to install and configure SharePoint. v3.96 (6 July 2014). This version have been modified to run with puppet.

All password will be automatically fill if you use Windows AD module and his XML file. The windows_ad module can be found in forge [jriviere/windows_ad](https://forge.puppetlabs.com/jriviere/windows_ad) or on [GitHub](https://github.com/insentia/windows_ad)

The account used for installing SharePoint must be Admin local at least on each server, and SQL sysdbo or at least have SQL DB Creator and security admin rights
Tested with :
	SharePoint Foundation 2013 SP1
	SharePoint Standard 2013 SP1
	SharePoint EnterPrise 2013 SP1

This module is only compatible with SharePoint 2013.
Only tested with puppet agent 3.6.2, Windows Server 2012 R2

##Last Fix/Update
V 0.0.7 :
 - Add -ea option on powershell command
 - Update the way to execute SharePoint installation

###Setup Requirements
Depends on the following modules:
	- ['puppetlabs/powershell', '>=1.0.2'](https://forge.puppetlabs.com/puppetlabs/powershell),
	- ['puppetlabs/stdlib', '>= 4.2.1'](https://forge.puppetlabs.com/puppetlabs/stdlib)

##Usage

##SharePointInstall
Class windows_sharepoint :
Permit installation of SharePoint

	class{'windows_sharepoint':
	  languagepackspath     => "C:\\source\\LanguagePacks",   # path where we are going to take the updates and put them in the correct folder for autospinstaller (not yet implemented)
	  updatespath    		=> "C:\\source\\Updates",         # path where we are going to take the extracted languagepacks and put them in the correct folder for autospinstaller. (Works)
	  sppath             	=> "C:\\source\\sharepoint.exe",  # path where we will find the exe file of sharepoint Foundation
	  dbserver           	=> "SQL_ALIAS",                   # the alias created by autospinstaller
	  dbaliasinstance 		=> "COMPUTERNAME",
	  setupaccountpassword  => "P@ssw0rd",
	  spfarmaccount         => "spfarm",
	  spapppoolaccount      => "spapppool",
	  spservicesaccount     => "spservices",
	  spsearchaccount       => "spsearch",
	  spcrawlaccount        => "spcrawl",
	  spsuperreaderaccount  => "spsuperreader",
	  spsuperuseraccount    => "spsuperuser",
	  spsyncaccount         => "spsyncaccount",                  # Mandatory with Standard and enterprise
	  spusrprfpassword      => "spusrprfaccount",                # Mandatory with Standard and enterprise
	  spexcelaccount        => "spexcelaccount",                 # Mandatory with enterprise
	  key                   => "SYOUR-PRODU-CTKEY-OFSPS-2012S",
	  passphrase            => "P@ssPhrase@2014",               #SharePoint Farm PassPhrase.Must be at least 8 charaters with upper character, lower character, numbers, specialcharacter (3 of this 4 categories)
	  webappurl             => "https://localhost",
	  applicationPool       => "Default AppPool",
	  webappname            => "WebApp",
	  webappport            => 443,
	  webappdatabasename    => "Default_ContentDB",
	  siteurl   		    => "https://localhost",
	  sitecolname  		    => "Home",
	  sitecollcid			=> "1033",
	  sitecollocale 		=> "en-us",
	  sitecolowner  		=> "spfarm",
	}

Parameters:
```
	$removedefaultwebapp         # If set to true this will delete the default created webapp
```
##webapplication
Ressource windows_sharepoint::webapplication :
Permit installation of SharePoint

	windows_sharepoint::webapplication{"default - $webappname":
	  url                    => "http://localhost",
	  applicationpoolname    => "AppPool_TestPuppet",
	  webappname             => "Test Puppet",
	  databasename           => "SP2013_Content_TestPuppet",
	  applicationpoolaccount => "s-spapppool",
	  ensure                 => present,
	  usessl                 => false,
	  webappport             => 6789,
	}

##user
Resource: windows_sharepoint::user

	windows_sharepoit{'SQLServer':
	  username   => "Jerome",
	  login      => 'jre',
	  group      => "SharePoint Owners",
	  weburl     => 'https://sharepoint/sites/jre',
	  admin      => true,
	}

Parameters:
```
	$username         # Fullname of the user
	$login            # SamAccountName
	$weburl           # URL of the site where we want to add user
	$group            # Group name where we want put the user
	$admin            # Is SiteColAdmin ? Default : false
```

##SP Group
Resource: windows_sharepoint::group

````
	windows_sharepoit{'SharePoint Owners':
	  group           => "SharePoint Owners",
	  weburl          => 'https://sharepoint/sites/jre',
	  permissionlevel => 'Full Control',
	  ownername       => 'jre',
	}
````
Parameters:
```
	$weburl           # URL of the site where we want to add user
	$group            # Group name where we want put the user
	$permissionlevel  # Permissions for the group Full Control|Edit|Contribute|Read|Design
	$ownername        # Owner of the group
	$description      # group description
```

##webapplication
Ressource windows_sharepoint::services::reporting :
Allow installation and configuration of SharePoint reporting service integrated mode
```
	windows_sharepoint::services::reporting{"Reporting":
	  databasename    => "ReportingServicesDB",
	  databaseserver  => "SQL_ALIAS",
	  serviceaccount  => "spservices",
	}
```
Parameters:
```
	$defaultsrvgrp    # Add the service to the default service app group. Default True
	$apppoolname      # App Pool name . The app pool will be created.
	$servicename      # Service Name. Default : SQL Server Reporting Service Application
	$proxyname        # Proxy Name. Default : SQL Server Reporting Service Application Proxy
```
## Known issues
Please don't add a '/' after the WebApp URL and site url, if you do so AutoSpInstaller will throw an error and will not create the WebApp and site Coll.

The User profile Service Application will be installed but the synchronisation will not work. You have to remove the UPA Service and create another one manually. (Puppet can't get back the control with infinite powershell start-process instance :(, so I have to disable this steps. ). (Don't forget to give Replicate Right to the sync user.)

License
-------
Apache License, Version 2.0

Contact
-------
[Jerome RIVIERE](https://github.com/ninja-2)

Support
-------
Please log tickets and issues at [Github site](https://github.com/insentia/windows_sharepoint/issues)


text:
package org.apache.metamodel.jdbc.dialects;

import java.sql.Types;

import org.apache.metamodel.jdbc.JdbcDataContext;
import org.apache.metamodel.query.AggregateFunction;
import org.apache.metamodel.query.FilterItem;
import org.apache.metamodel.query.FromItem;
import org.apache.metamodel.query.Query;
import org.apache.metamodel.query.ScalarFunction;
import org.apache.metamodel.schema.ColumnType;

/**
 * A query rewriter can be used for rewriting (part of) a query's string
 * representation. This is usefull for databases that deviate from the SQL 99
 * compliant syntax which is delievered by the query and it's query item's
 * toString() methods.
 *
 * @see AbstractQueryRewriter
 * @see JdbcDataContext
 */
public interface IQueryRewriter {

    public String rewriteFromItem(FromItem item);

    public String rewriteQuery(Query query);

    public String rewriteFilterItem(FilterItem whereItem);

    /**
     * Gets whether this query rewriter is able to write the "Max rows" query
     * property to the query string.
     *
     * @return whether this query rewriter is able to write the "Max rows" query
     *         property to the query string.
     */
    public boolean isMaxRowsSupported();

    /**
     * Gets whether this query rewriter is able to write the "First row" query
     * property to the query string.
     *
     * @return whether this query rewriter is able to write the "First row"
     *         query property to the query string.
     */
    public boolean isFirstRowSupported();

    /**
     * Determines whether a specific scalar function is supported by the
     * database or not.
     *
     * If the function is not supported then MetaModel will handle the function
     * on the client side.
     *
     * @param function
     * @return
     */
    public boolean isScalarFunctionSupported(ScalarFunction function);

    /**
     * Determines whether a specific aggregate function is supported by the
     * database or not.
     *
     * If the function is not supported then MetaModel will handle the function
     * on the client side.
     *
     * @param function
     * @return
     */
    public boolean isAggregateFunctionSupported(AggregateFunction function);

    /**
     * Escapes the quotes within a String literal of a query item.
     *
     * @return String item with quotes escaped.
     */
    public String escapeQuotes(String item);

    /**
     * Rewrites the name of a column type, as it is written in CREATE TABLE
     * statements. Some databases dont support all column types, or have
     * different names for them. The implementation of this method will do that
     * conversion.
     *
     * @param columnType
     *            the (non-null) {@link ColumnType} to rewrite
     * @param columnSize
     *            the (possibly null) column size that may or may not have been
     *            specified
     * @return
     */
    public String rewriteColumnType(ColumnType columnType, Integer columnSize);

    /**
     * Gets the column type for a specific JDBC type (as defined in
     * {@link Types}), native type name and column size.
     *
     * @param jdbcType
     * @param nativeType
     * @param columnSize
     * @return
     */
    public ColumnType getColumnType(int jdbcType, String nativeType, Integer columnSize);

    /**
     * Determines if the JDBC data source supports transactions or not. Usually
     * this is the case since JDBC is designed for ACID compliant databases, but
     * in some cases the JDBC interface is used also to facilitate connectivity
     * to non-transactional data source such as Apache Hive and others.
     *
     * @return
     */
    public boolean isTransactional();
}


text:
from unittest import TestCase

class TestSchema(TestCase):

    def is_valid(self, content):
        from ..schema import get_schema
        from lxml import etree
        schema = get_schema()
        doc = etree.XML(content)
        return schema.validate(doc)

    def test_valid(self):
        content = '

Valid

'
        self.assertTrue(self.is_valid(content))


text:
class Activity < Audit
   #Audit lives in vendor/plugins/acts_as_audited/lib/audit.rb

  def uname
    if username.to_s == "--- :false\n"
      uname = nil
    else
      uname = username
    end
    uname
  end
 def activity_action
   action.gsub(/\W/, "").titleize

 end
   def summary
      summ  = ""
      if changes && auditable_type == "Map"
         if changes["status"] && changes["status"] != "status"
            map_action  =  Map::STATUS[changes["status"]]
            case map_action
            when :unloaded
               summ = "Map was unloaded"
            when :loading
               summ = "Map started loading from library"
            when :available
               summ = "Map became available"
            when :warping
               summ = "Map started rectification process"
            when :warped
               summ = "Map successfully rectified"
            else
               summ =""
            end

         end #status

         if changes["mask_status"] && changes["status"] != "mask_status"
            mask_action = Map::MASK_STATUS[changes["mask_status"]]
            case mask_action
            when :unmasked
               summ = "Map was unmasked"
            when :masking
               summ = "Map started masking process"
            when :masked
               summ = "Map successfully masked"
            else
               summ = ""
            end

         end # mask_status

      end #Map

      summ
   end

end


text:
define({
  "_themeLabel": "Katlanabilir Tema",
  "_layout_default": "Varsayılan düzen",
  "_layout_layout1": "Düzen 1"
});


text:
import os
import re
from getpass import getpass
import yaml
from pytz import timezone
import feedparser
import saschapath

def run():
    profile = {}

    print("Welcome to the profile populator. If, at any step, you'd prefer " +
          "not to enter the requested information, just hit 'Enter' with a " +
          "blank field to continue.")

    def simple_request(var, cleanVar, cleanInput=None):
        input = raw_input(cleanVar + ": ")
        if input:
            if cleanInput:
                input = cleanInput(input)
            profile[var] = input

    # name
    simple_request('first_name', 'First name')
    simple_request('last_name', 'Last name')

    # timezone
    print("\nPlease enter a timezone from the list located in the TZ* " +
          "column at http://en.wikipedia.org/wiki/" +
          "List_of_tz_database_time_zones, or none at all.")
    tz = raw_input("Timezone: ")
    while tz:
        try:
            timezone(tz)
            profile['timezone'] = tz
            break
        except:
            print("Not a valid timezone. Try again.")
            tz = raw_input("Timezone: ")

    response = raw_input("\nWould you prefer to have notifications sent by " +
                         "email (E) or text message (T)? ")
    while not response or (response != 'E' and response != 'T'):
        response = raw_input("Please choose email (E) or text message (T): ")
    profile['prefers_email'] = (response == 'E')

    stt_engines = {
        "sphinx": None,
        "google": "GOOGLE_SPEECH"
    }

    response = raw_input("\nIf you would like to choose a specific STT " +
                         "engine, please specify which.\nAvailable " +
                         "implementations: %s. (Press Enter to default " +
                         "to PocketSphinx): " % stt_engines.keys())
    if (response in stt_engines):
        profile["stt_engine"] = response
        api_key_name = stt_engines[response]
        if api_key_name:
            key = raw_input("\nPlease enter your API key: ")
            profile["keys"] = {api_key_name: key}
    else:
        print("Unrecognized STT engine. Available implementations: %s"
              % stt_engines.keys())
        profile["stt_engine"] = "sphinx"

    # write to profile
    print("Writing to profile...")
    if not os.path.exists(saschapath.CONFIG_PATH):
        os.makedirs(saschapath.CONFIG_PATH)
    outputFile = open(saschapath.config("profile.yml"), "w")
    yaml.dump(profile, outputFile, default_flow_style=False)
    print("Done.")

if __name__ == "__main__":
    run()


text:
"""End to end tests for GRR fingerprint-related flows."""

from grr_response_test.end_to_end_tests import test_base

class TestFingerprintFileOSLinux(test_base.EndToEndTest):
  """Tests if Fingerprinting works on Linux."""

  platforms = [
      test_base.EndToEndTest.Platform.LINUX,
  ]

  def runTest(self):
    args = self.grr_api.types.CreateFlowArgs("FingerprintFile")
    args.pathspec.path = "/bin/ls"
    args.pathspec.pathtype = args.pathspec.OS

    with self.WaitForFileRefresh("fs/os/bin/ls"):
      f = self.RunFlowAndWait("FingerprintFile", args=args)

    results = list(f.ListResults())
    self.assertNotEmpty(results)

    fingerprint_result = results[0].payload
    self.assertLen(fingerprint_result.hash_entry.md5, 16)
    self.assertLen(fingerprint_result.hash_entry.sha1, 20)
    self.assertLen(fingerprint_result.hash_entry.sha256, 32)

class TestFingerprintFileOSWindows(test_base.EndToEndTest):
  """Tests if Fingerprinting works on Windows."""

  platforms = [
      test_base.EndToEndTest.Platform.WINDOWS,
  ]

  def runTest(self):
    args = self.grr_api.types.CreateFlowArgs("FingerprintFile")
    args.pathspec.path = "C:\\Windows\\regedit.exe"
    args.pathspec.pathtype = args.pathspec.OS

    with self.WaitForFileRefresh("fs/os/C:/Windows/regedit.exe"):
      self.RunFlowAndWait("FingerprintFile", args=args)