/*
(non-Javadoc)
@see org.fcrepo.server.security.xacml.pep.PEPClient#evaluateBatch(java.lang.String[])
979518
@Override
    public String evaluateBatch(List<String> request) throws PEPException {
        if (request == null) {
            throw new NullPointerException("evaluateBatch(request=null)");
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Resolving request batch ({} requests)", request.size());
        }

        String response = null;
        try {
            response = this.client.evaluateBatch(request.toArray(STRING_TYPE));
        } catch (Exception e) {
            logger.error("Error evaluating request.", e);
            throw new PEPException("Error evaluating request", e);
        }

        return response;
    }
1273658
@Override
    public int executeBatch()
    {
        Object connection = getConnection();
        // Create a hashset and populate data into it
        Pipeline pipeLine = null;
        if (isBoundTransaction())
        {
            pipeLine = ((Jedis) connection).pipelined();
        }
        try
        {
            for (Node node : nodes)
            {
                if (node.isDirty())
                {
                    node.handlePreEvent();
                    // delete can not be executed in batch
                    if (node.isInState(RemovedState.class))
                    {
                        onDelete(node.getData(), node.getEntityId(), pipeLine != null ? pipeLine : connection);
                    }
                    else
                    {

                        List<RelationHolder> relationHolders = getRelationHolders(node);
                        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                                node.getDataClass());

                        onPersist(metadata, node.getData(), node.getEntityId(), relationHolders,
                                pipeLine != null ? pipeLine : connection);
                    }
                    node.handlePostEvent();
                }
            }
        }
        finally
        {
            //
            if (pipeLine != null)
            {
                pipeLine.sync(); // send I/O.. as persist call. so no need to
                                 // read
                // response?
            }
            onCleanup(connection);
        }

        return nodes.size();
    }
552040
private static <E> List<E> getBatchList(Integer index, int batchSize, Collection<E> collection) {
        List<E> list = null;
        if (collection instanceof List) {
            list = (List<E>) collection;
        } else {
            list = new ArrayList<E>(collection);
        }

        if (index == list.size() / batchSize) {
            return list.subList(index * batchSize, list.size());
        } else {
            return list.subList(index * batchSize, (index + 1) * batchSize);
        }
    }
168561
public void evaluate(ObjectStream<DocSample> samples, int nFolds)
      throws IOException {

    CrossValidationPartitioner<DocSample> partitioner = new CrossValidationPartitioner<>(
        samples, nFolds);

    while (partitioner.hasNext()) {

      CrossValidationPartitioner.TrainingSampleStream<DocSample> trainingSampleStream = partitioner
          .next();

      DocumentClassifierModel model = DocumentClassifierME.train(languageCode,
          trainingSampleStream, params, factory);

      DocumentClassifierEvaluator evaluator = new DocumentClassifierEvaluator(
          new DocumentClassifierME(model), listeners);

      evaluator.evaluate(trainingSampleStream.getTestSampleStream());

      documentAccuracy.add(evaluator.getAccuracy(),
          evaluator.getDocumentCount());

    }
  }
570331
public static int[] executeBatch(Connection conn, String sql, Iterable<Object[]> paramsBatch) throws SQLException {
		PreparedStatement ps = null;
		try {
			ps = StatementUtil.prepareStatementForBatch(conn, sql, paramsBatch);
			return ps.executeBatch();
		} finally {
			DbUtil.close(ps);
		}
	}
1193075
@WithBridgeMethods(value = SQLDeleteClause.class, castRequired =  true)
    public C addBatch() {
        batches.add(metadata);
        metadata = new DefaultQueryMetadata();
        metadata.addJoin(JoinType.DEFAULT, entity);
        metadata.setValidatingVisitor(validatingVisitor);
        return (C) this;
    }
1332916
@WithBridgeMethods(value = SQLInsertClause.class, castRequired = true)
    public C addBatch() {
        if (subQueryBuilder != null) {
            subQuery = subQueryBuilder.select(values.toArray(new Expression[values.size()])).clone();
            values.clear();
        }
        batches.add(new SQLInsertBatch(columns, values, subQuery));
        columns.clear();
        values.clear();
        subQuery = null;
        return (C) this;
    }
1037366
public void generateMethodExecuteBatch(String daoFactory) {
		// create interface
		String transationExecutorName = "Batch";
		// @formatter:off
		// ParameterizedTypeName parameterizedTypeName =
		// ParameterizedTypeName.get(className(AbstractExecutable.class),
		// className(daoFactory));
		classBuilder.addType(TypeSpec.interfaceBuilder(transationExecutorName).addModifiers(Modifier.PUBLIC)
				.addTypeVariable(TypeVariableName.get("T"))
				// .addSuperinterface(parameterizedTypeName)
				.addJavadoc("Rapresents batch operation.\n")
				.addMethod(MethodSpec.methodBuilder("onExecute").addJavadoc("Execute batch operations.")
						.addJavadoc("\n\n@param daoFactory\n@throws Throwable\n")
						.addParameter(className(daoFactory), "daoFactory")
						.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).returns(TypeVariableName.get("T")).build())
				.build());
		// @formatter:on

		// @formatter:on
		{
			// execute read/write mode
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("executeBatch")
					// generate javadoc
					.addTypeVariable(TypeVariableName.get("T"))
					.addJavadoc(
							"<p>Executes a batch opening a read only connection. This method <strong>is thread safe</strong> to avoid concurrent problems.</p>\n\n")
					.addJavadoc("@param commands\n\tbatch to execute\n").addModifiers(Modifier.PUBLIC)
					.addParameter(
							ParameterizedTypeName.get(className(transationExecutorName), TypeVariableName.get("T")),
							"commands")
					.returns(TypeVariableName.get("T"));

			executeMethod.addStatement("return executeBatch(commands, false)");
			classBuilder.addMethod(executeMethod.build());
		}

		{
			// execute read/write mode
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("executeBatch")
					// generate javadoc
					.addJavadoc(
							"<p>Executes a batch. This method <strong>is thread safe</strong> to avoid concurrent problems. The "
									+ "drawback is only one transaction at time can be executed. if <code>writeMode</code> is set to false, multiple batch operations is allowed.</p>\n")
					.addTypeVariable(TypeVariableName.get("T")).addJavadoc("\n")
					.addJavadoc("@param commands\n\tbatch to execute\n")
					.addJavadoc(
							"@param writeMode\n\ttrue to open connection in write mode, false to open connection in read only mode\n")
					.addModifiers(Modifier.PUBLIC)
					.addParameter(
							ParameterizedTypeName.get(className(transationExecutorName), TypeVariableName.get("T")),
							"commands")
					.addParameter(Boolean.TYPE, "writeMode").returns(TypeVariableName.get("T"));

			executeMethod.addStatement("boolean needToOpened=writeMode?!this.isOpenInWriteMode(): !this.isOpen()");
			executeMethod.addCode(
					"if (needToOpened) { if (writeMode) { openWritableDatabase(); } else { openReadOnlyDatabase(); }}\n",
					SQLiteDatabase.class);

			// support for live data
			executeMethod.addStatement("$L currentDaoFactory=new DataSourceSingleThread()",
					DATA_SOURCE_SINGLE_THREAD_NAME);
			executeMethod.addStatement("currentDaoFactory.onSessionOpened()");

			executeMethod.beginControlFlow("try");
			executeMethod.beginControlFlow("if (commands!=null)");
			executeMethod.addStatement("return commands.onExecute(currentDaoFactory)");

			executeMethod.endControlFlow();

			executeMethod.nextControlFlow("catch($T e)", Throwable.class);

			executeMethod.addStatement("$T.error(e.getMessage())", Logger.class);
			executeMethod.addStatement("e.printStackTrace()");
			executeMethod.addStatement("throw(e)");

			executeMethod.nextControlFlow("finally");
			executeMethod.addCode("if (needToOpened) { close(); }\n");
			// support for live data
			executeMethod.addStatement("currentDaoFactory.onSessionClosed()");
			executeMethod.endControlFlow();
			executeMethod.addStatement("return null");

			classBuilder.addMethod(executeMethod.build());
		}
	}
1061334
private int[] convertBatch(int[] batch) {
        int[] conv = new int[batch.length];
        for (int i=0; i<batch.length; i++) {
            conv[i] = sample[batch[i]];
        }
        return conv;
    }
877816
public void executeBatchIfNecessary() throws OJBBatchUpdateException
    {
        if (batchCon != null)
        {
            try
            {
                batchCon.executeBatchIfNecessary();
            }
            catch (Throwable th)
            {
                throw new OJBBatchUpdateException(th);
            }
        }
    }
1142935
public int[] executeBatchPreparedStatement(String statement, Collection inParamsBatch) throws SQLException {
		return executeBatchPreparedStatement(statement, inParamsBatch, true);
	}
368113
public static int[] executeBatch(Connection conn, String... sqls) throws SQLException {
		return executeBatch(conn, new ArrayIter<String>(sqls));
	}
46050
protected static <P extends ParaObject> void batchGet(Map<String, KeysAndAttributes> kna, Map<String, P> results) {
		if (kna == null || kna.isEmpty() || results == null) {
			return;
		}
		try {
			BatchGetItemResult result = getClient().batchGetItem(new BatchGetItemRequest().
					withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL).withRequestItems(kna));
			if (result == null) {
				return;
			}

			List<Map<String, AttributeValue>> res = result.getResponses().get(kna.keySet().iterator().next());

			for (Map<String, AttributeValue> item : res) {
				P obj = fromRow(item);
				if (obj != null) {
					results.put(obj.getId(), obj);
				}
			}
			logger.debug("batchGet(): total {}, cc {}", res.size(), result.getConsumedCapacity());

			if (result.getUnprocessedKeys() != null && !result.getUnprocessedKeys().isEmpty()) {
				Thread.sleep(1000);
				logger.warn("{} UNPROCESSED read requests!", result.getUnprocessedKeys().size());
				batchGet(result.getUnprocessedKeys(), results);
			}
		} catch (Exception e) {
			logger.error(null, e);
		}
	}
444118
private static BatchExecutor getSetBatchExecutor(BeanMappingParam param, BeanMappingObject config) {
        BatchExecutor executor = config.getSetBatchExecutor();
        if (executor != null) { // 如果已经生成，则直接返回
            return executor;
        }

        if (canBatch(config.getBehavior()) == false) {
            config.setBatch(false);
            return null;
        }

        // 处理target操作数据搜集
        List<String> targetFields = new ArrayList<String>();
        List<Class> targetArgs = new ArrayList<Class>();
        Class locatorClass = param.getTargetRef().getClass(); // 检查一下locatorClass
        for (BeanMappingField beanField : config.getBeanFields()) {
            String targetField = beanField.getTargetField().getName();
            Class targetArg = beanField.getTargetField().getClazz();
            if (StringUtils.isEmpty(targetField) || targetArg == null) {
                return null; // 直接不予处理
            }

            Class selfLocatorClass = beanField.getTargetField().getLocatorClass();
            if (selfLocatorClass != null && selfLocatorClass != locatorClass) {
                config.setBatch(false);// 直接改写为false，发现locatorClass存在于不同的class
                return null;
            }

            if (canBatch(beanField.getBehavior()) == false) {
                config.setBatch(false);
                return null;
            }

            SetExecutor set = beanField.getSetExecutor();// 只针对property进行batch优化
            if (set != null && (set instanceof FastPropertySetExecutor || set instanceof PropertySetExecutor) == false) {
                config.setBatch(false);
                return null;
            }

            // 搜集信息
            targetFields.add(targetField);
            targetArgs.add(targetArg);
        }
        // 生成下target批量处理器
        executor = Uberspector.getInstance().getBatchExecutor(locatorClass,
                                                              targetFields.toArray(new String[targetFields.size()]),
                                                              targetArgs.toArray(new Class[targetArgs.size()]));
        if (config.getBehavior().isDebug() && logger.isDebugEnabled()) {
            logger.debug("TargetClass[" + param.getTargetRef().getClass() + "]SetBatchExecutor is init");
        }
        config.setSetBatchExecutor(executor);
        return executor;
    }
1076370
public QuadBatch pushBatch (QuadBatch newBatch) {
    if (newBatch == null) return null;
    QuadBatch oldBatch = batch;
    batch.end();
    batch = beginBatch(newBatch);
    return oldBatch;
  }
1227114
public final void evaluate() throws IllegalAccessException, InvocationTargetException {
		if (simple) tr.startCollection();
		fTestMethod.invoke(fTarget, params);
		if (simple) tr.stopCollection();
	}
220008
public void evaluate(final ObjectStream<SequenceLabelSample> samples,
      final int nFolds) throws IOException {

    // Note: The name samples need to be grouped on a document basis.

    final CrossValidationPartitioner<DocumentSample> partitioner = new CrossValidationPartitioner<DocumentSample>(
        new NameToDocumentSampleStream(samples), nFolds);

    while (partitioner.hasNext()) {

      final CrossValidationPartitioner.TrainingSampleStream<DocumentSample> trainingSampleStream = partitioner
          .next();

      SequenceLabelerModel model = null;
      if (this.factory != null) {
        model = SequenceLabelerME.train(this.languageCode,
            new DocumentToNameSampleStream(trainingSampleStream), this.params,
            this.factory);
      } else {
        System.err.println("You need to implement a SequenceLabelerFactory!");
        System.exit(1);
      }
      
      String corpusFormat = Flags.getCorpusFormat(this.params);
      // do testing
      final SequenceLabelerEvaluator evaluator = new SequenceLabelerEvaluator(corpusFormat,
          new SequenceLabelerME(model), this.listeners);

      evaluator.evaluate(new DocumentToNameSampleStream(
          trainingSampleStream.getTestSampleStream()));

      this.fmeasure.mergeInto(evaluator.getFMeasure());
    }
  }