/* (non-Javadoc)
@see org.apache.hadoop.mapred.Reducer#reduce(java.lang.Object, java.util.Iterator, org.apache.hadoop.mapred.OutputCollector, org.apache.hadoop.mapred.Reporter)
556172
public void reduce(Shard key, Iterator<IntermediateForm> values,
      OutputCollector<Shard, IntermediateForm> output, Reporter reporter)
      throws IOException {

    LOG.info("Construct a form writer for " + key);
    IntermediateForm form = new IntermediateForm();
    form.configure(iconf);
    while (values.hasNext()) {
      IntermediateForm singleDocForm = values.next();
      form.process(singleDocForm);
    }
    form.closeWriter();
    LOG.info("Closed the form writer for " + key + ", form = " + form);

    output.collect(key, form);
  }
1230148
@NotNull
    public static <Key extends Serializable, ValueIn, MapOutput extends Serializable, ReducerResult extends Serializable> ReducerResult compute(@NotNull AnalyticsContext analyticsContext,
                                                                                                                                                @NotNull MapReduceTask<Key, ValueIn, MapOutput, ReducerResult> mapReduceTask) {

        Timer timer = MetricsFactory.getMetrics().getTimer("analytics.compute");

        ClusterGroup clusterGroup = analyticsContext.getIgnite()
                                                    .cluster()
                                                    .forServers();


        ReducerResult execute = analyticsContext.getIgnite()
                                                .compute(clusterGroup)
                                                .execute(mapReduceTask, null);

        timer.stop();

        LOGGER.debug("Complete compute operation in {}", timer);

        return execute;
    }
231643
public BigRational reduce() {
		BigInteger n = numerator.toBigInteger();
		BigInteger d = denominator.toBigInteger();

		BigInteger gcd = n.gcd(d);
		n = n.divide(gcd);
		d = d.divide(gcd);

		return valueOf(n, d);
	}
435592
private void writeObject(ObjectOutputStream out) throws IOException {
		super.write(out);
		out.writeUTF(this.mapreduceOutputFormat.getClass().getName());
		this.configuration.write(out);
	}
559359
def _perform_reduce(self, map_results, factory, group=False,
                        group_level=None):
        '''
        
        '''

        def get_group_key(key, group, group_level):
            if group:
                return key
            return key[0:group_level]

        if not group and group_level is None:
            keys = map(operator.itemgetter(0), map_results)
            values = map(operator.itemgetter(1), map_results)
            return self._reduce_values(factory, None, keys, values)
        else:
            groups = dict()
            for row in map_results:
                key, value = row[:2]
                group_key = get_group_key(key, group, group_level)
                if group_key not in groups:
                    groups[group_key] = list()
                groups[group_key].append((key, value))
            resp = list()
            for group_key, results in groups.iteritems():
                keys = map(operator.itemgetter(0), results)
                values = map(operator.itemgetter(1), results)
                resp.extend(
                    self._reduce_values(factory, group_key, keys, values))
            return resp
815257
private void writeObject(ObjectOutputStream out) throws IOException {
		out.writeUTF(hadoopOutputFormatName);
		jobConf.write(out);
		out.writeObject(converter);
		out.writeObject(fileOutputCommitterWrapper);
	}
939712
public void reduce(K2 key, Iterator<V2> values, 
                     OutputCollector<K3, V3> output, Reporter reporter
                     ) throws IOException {
    isOk = false;
    startApplication(output, reporter);
    downlink.reduceKey(key);
    while (values.hasNext()) {
      downlink.reduceValue(values.next());
    }
    if(skipping) {
      //flush the streams on every record input if running in skip mode
      //so that we don't buffer other records surrounding a bad record.
      downlink.flush();
    }
    isOk = true;
  }
3515
function reportReducer (linter, summary, filePath) {
  const fileContents = fs.readFileSync(filePath, {encoding: 'utf8'})
  const file = linter.process(fileContents)

  if (file.messages.length !== 0) {
    this.printFilePath(filePath)

    file.messages.forEach((message) => {
      const severity = message.fatal ? 'error' : 'warning'
      this.printLintItem(message.line, message.column, severity, message.message, message.ruleId)

      if (message.fatal) {
        summary.errors += 1
      } else {
        summary.warnings += 1
      }
    })

    console.log('') // logging empty line
  }

  return summary
}
742979
function reduceit(v, i) {
    if (i >= this.rmin) {
      return undefined;
    }
    this.accumulater[i] += (v / this.scale[i]);
    return this.accumulater[i];
  }
333122
@Override
  public void reduce(DeepWaterTask2 drt) {
    if (_res == null) _res = drt._res;
    else {
//      _res._chunk_node_count += drt._res._chunk_node_count;
      _res.model_info().add(drt._res.model_info()); //add models, but don't average yet
    }
    assert(_res.model_info().get_params()._replicate_training_data);
  }
424751
@SuppressWarnings("unchecked")
    private void reduce(AnalyzerJob analyzerJob, Collection<AnalyzerResult> slaveResults,
            Map<ComponentJob, AnalyzerResult> resultMap, List<AnalysisResultReductionException> reductionErrors) {

        if (slaveResults.size() == 1) {
            // special case where these was only 1 slave job
            final AnalyzerResult firstResult = slaveResults.iterator().next();
            resultMap.put(analyzerJob, firstResult);
            _analysisListener.analyzerSuccess(_masterJob, analyzerJob, firstResult);
            return;
        }

        final Class<? extends AnalyzerResultReducer<?>> reducerClass = analyzerJob.getDescriptor()
                .getResultReducerClass();

        final ComponentDescriptor<? extends AnalyzerResultReducer<?>> reducerDescriptor = Descriptors
                .ofComponent(reducerClass);

        AnalyzerResultReducer<AnalyzerResult> reducer = null;
        boolean success = false;
        try {
            reducer = (AnalyzerResultReducer<AnalyzerResult>) reducerDescriptor.newInstance();

            _lifeCycleHelper.assignProvidedProperties(reducerDescriptor, reducer);
            _lifeCycleHelper.initialize(reducerDescriptor, reducer);

            final AnalyzerResult reducedResult = reducer.reduce(slaveResults);
            resultMap.put(analyzerJob, reducedResult);
            
            success = true;
            _analysisListener.analyzerSuccess(_masterJob, analyzerJob, reducedResult);

        } catch (Exception e) {
            AnalysisResultReductionException reductionError = new AnalysisResultReductionException(analyzerJob,
                    slaveResults, e);
            reductionErrors.add(reductionError);

            _analysisListener.errorInComponent(_masterJob, analyzerJob, null, e);
        } finally {
            if (reducer != null) {
                _lifeCycleHelper.close(reducerDescriptor, reducer, success);
            }
        }
    }
17232
def reducer_output(self, metro, values):
        
        records = []
        # build up list of data for each metro area and submit as one network
        # call instead of individually 
        for value in values:
            total, poi = value
            records.append(dict(
                metro_area=metro,
                poi=poi,
                count=total
            ))
            output = "{0}\t{1}\t{2}"
            output = output.format(metro.encode('utf-8'), total, poi.encode('utf-8'))
            yield None, output
        if self.mongo:
            self.mongo.insert_many(records)
338913
private void reduce() {
        Long[] keys = counter.asMap().keySet().toArray(ArrayUtils.EMPTY_LONG_OBJECT_ARRAY);
        Arrays.sort(keys);
        for (int i = 0, n = keys.length - maxNumBlocks + BUFFER_NUM_BLOCKS; i < n; i++) {
            counter.remove(keys[i]);
        }
    }
529964
@Override
    public List<QueryRow> reducedQuery(QueryOptions options) throws CouchbaseLiteException {
        Predicate<QueryRow> postFilter = options.getPostFilter();

        int groupLevel = options.getGroupLevel();
        boolean group = options.isGroup() || (groupLevel > 0);
        Reducer reduce = delegate.getReduce();
        if (options.isReduceSpecified()) {
            if (options.isReduce() && reduce == null) {
                Log.w(TAG, "Cannot use reduce option in view %s which has no reduce block defined",
                        name);
                throw new CouchbaseLiteException(new Status(Status.BAD_PARAM));
            }
        }

        final List<Object> keysToReduce = new ArrayList<Object>(REDUCE_BATCH_SIZE);
        final List<Object> valuesToReduce = new ArrayList<Object>(REDUCE_BATCH_SIZE);
        final Object[] lastKeys = new Object[1];
        lastKeys[0] = null;
        final ForestDBViewStore that = this;
        final List<QueryRow> rows = new ArrayList<QueryRow>();

        try {
            openIndex();
        } catch (ForestException e) {
            throw new CouchbaseLiteException(e.code);
        }

        QueryIterator itr;
        try {
            itr = forestQuery(options);

            while (itr.next()) {
                byte[] bKey = itr.keyJSON();
                byte[] bValue = itr.valueJSON();
                Object keyObject = fromJSON(bKey, Object.class);
                Object valueObject = fromJSON(bValue, Object.class);
                if (group && !groupTogether(keyObject, lastKeys[0], groupLevel)) {
                    if (lastKeys[0] != null) {
                        // This pair starts a new group, so reduce & record the last one:
                        Object key = groupKey(lastKeys[0], groupLevel);
                        Object reduced = (reduce != null) ?
                                reduce.reduce(keysToReduce, valuesToReduce, false) : null;
                        QueryRow row = new QueryRow(null, 0, key, reduced, null);
                        if (postFilter == null || postFilter.apply(row))
                            rows.add(row);
                        keysToReduce.clear();
                        valuesToReduce.clear();
                    }
                    lastKeys[0] = keyObject;
                }

                keysToReduce.add(keyObject);
                valuesToReduce.add(valueObject);
            }

        } catch (ForestException e) {
            Log.e(TAG, "Error in reducedQuery()", e);
        } catch (IOException e) {
            Log.e(TAG, "Error in reducedQuery()", e);
            throw new CouchbaseLiteException(Status.UNKNOWN);
        }

        if (keysToReduce != null && keysToReduce.size() > 0) {
            // Finish the last group (or the entire list, if no grouping):
            Object key = group ? groupKey(lastKeys[0], groupLevel) : null;
            Object reduced = (reduce != null) ?
                    reduce.reduce(keysToReduce, valuesToReduce, false) : null;
            Log.v(TAG, String.format(Locale.ENGLISH, "Query %s: Reduced to key=%s, value=%s", name, key, reduced));
            QueryRow row = new QueryRow(null, 0, key, reduced, null);
            if (postFilter == null || postFilter.apply(row))
                rows.add(row);
        }
        return rows;
    }
1025331
@Override
    public Double reduce(List<Double> values) {
        double min = Double.MAX_VALUE;
        double max = Double.MIN_VALUE;

        for (Double value : values) {
            if (value == null) {
                value = 0.0;
            }

            double candidate = (value);

            if (candidate < min) {
                min = candidate;
            }
            if (candidate > max) {
                max = candidate;
            }
        }
        return max - min;
    }
417152
@SuppressWarnings("unchecked")
	public PythonSingleOutputStreamOperator reduce(ReduceFunction<PyObject> fun) throws IOException {
		return new PythonSingleOutputStreamOperator(stream.reduce(new PythonReduceFunction(fun)));
	}
1265206
private void writeObject(ObjectOutputStream out) throws IOException {
		out.writeUTF(hadoopInputFormatName);
		jobConf.write(out);
		out.writeObject(converter);
	}