/* (non-Javadoc)
@see org.kie.spi.Accumulator#accumulate(java.lang.Object, org.kie.spi.Tuple, org.kie.common.InternalFactHandle, org.kie.rule.Declaration[], org.kie.rule.Declaration[], org.kie.WorkingMemory)
8761
public void accumulate(Object workingMemoryContext,
                           Object context,
                           Tuple leftTuple,
                           InternalFactHandle handle,
                           Declaration[] declarations,
                           Declaration[] innerDeclarations,
                           WorkingMemory workingMemory) throws Exception {
        Object value = this.unwrapHandle ? ((LeftTuple) handle.getObject()).getFactHandle().getObject() : handle.getObject();
        ((CollectContext) context).result.add( value );
    }
705171
private static int aggregateDimValue(
      final int[] positions,
      final BufferAggregator[] theAggregators,
      final ByteBuffer resultsBuf,
      final int numBytesPerRecord,
      final int[] aggregatorOffsets,
      final int aggSize,
      final int aggExtra,
      final int dimIndex,
      int currentPosition
  )
  {
    if (SKIP_POSITION_VALUE == positions[dimIndex]) {
      return currentPosition;
    }
    if (INIT_POSITION_VALUE == positions[dimIndex]) {
      positions[dimIndex] = currentPosition * numBytesPerRecord;
      currentPosition++;
      final int pos = positions[dimIndex];
      for (int j = 0; j < aggSize; ++j) {
        theAggregators[j].init(resultsBuf, pos + aggregatorOffsets[j]);
      }
    }
    final int position = positions[dimIndex];

    switch (aggExtra) {
      case 7:
        theAggregators[6].aggregate(resultsBuf, position + aggregatorOffsets[6]);
        // fall through
      case 6:
        theAggregators[5].aggregate(resultsBuf, position + aggregatorOffsets[5]);
        // fall through
      case 5:
        theAggregators[4].aggregate(resultsBuf, position + aggregatorOffsets[4]);
        // fall through
      case 4:
        theAggregators[3].aggregate(resultsBuf, position + aggregatorOffsets[3]);
        // fall through
      case 3:
        theAggregators[2].aggregate(resultsBuf, position + aggregatorOffsets[2]);
        // fall through
      case 2:
        theAggregators[1].aggregate(resultsBuf, position + aggregatorOffsets[1]);
        // fall through
      case 1:
        theAggregators[0].aggregate(resultsBuf, position + aggregatorOffsets[0]);
    }
    for (int j = aggExtra; j < aggSize; j += AGG_UNROLL_COUNT) {
      theAggregators[j].aggregate(resultsBuf, position + aggregatorOffsets[j]);
      theAggregators[j + 1].aggregate(resultsBuf, position + aggregatorOffsets[j + 1]);
      theAggregators[j + 2].aggregate(resultsBuf, position + aggregatorOffsets[j + 2]);
      theAggregators[j + 3].aggregate(resultsBuf, position + aggregatorOffsets[j + 3]);
      theAggregators[j + 4].aggregate(resultsBuf, position + aggregatorOffsets[j + 4]);
      theAggregators[j + 5].aggregate(resultsBuf, position + aggregatorOffsets[j + 5]);
      theAggregators[j + 6].aggregate(resultsBuf, position + aggregatorOffsets[j + 6]);
      theAggregators[j + 7].aggregate(resultsBuf, position + aggregatorOffsets[j + 7]);
    }
    return currentPosition;
  }
1086063
@Override
    public void storeUpdate(INDArray array, int iterationNumber, int epochNumber) {
        /*
            Here we want to do 4 things:
            1) update accumulated values
            2) invoke extractor, that'll (optionally) pull all updates above threshold
            3) ???
            4) PROFIT!
         */

        try {
            // commit should happen in each individual thread
            Nd4j.getExecutioner().commit();
            firstOne.compareAndSet(-1L, Thread.currentThread().getId());

            // TODO: since we know number of elements in advance, we don't really need CopyOnWrite list here.
            candidates.add(array);
            barrier.await();

            if (firstOne.get() == Thread.currentThread().getId()) {
                // if accum is null, let's just create it here
                if (storage == null) {
                    // we don't want state array to be attached to any workspace
                    shape = array.shape();
                    ordering = array.ordering();

                    try (MemoryWorkspace workspace = Nd4j.getMemoryManager().scopeOutOfWorkspaces()) {
                        // TODO: if p2p isn't supported, this should become HOST-only allocation
                        storage = Nd4j.create(shape, ordering);
                    }
                }


                // accumulate our values, a
                //storage.addi(array);
                Nd4j.accumulate(storage, candidates);

                // we ensure storage was updated successfully
                Nd4j.getExecutioner().commit();

                // if there's something to send - send it. Skip otherwise!!!
                if (handler.broadcastUpdates(storage, iterationNumber, epochNumber)) {
                    ownCounter.getAndIncrement();
                }

                // reset "first one" :)
                firstOne.set(-1L);
                candidates.clear();
            }

            barrier.await();
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } catch (BrokenBarrierException e) {
            throw new RuntimeException(e);
        }
    }
996415
def _accumulate(sequence, func):
    
    iterator = iter(sequence)
    total = next(iterator)
    yield total
    for element in iterator:
        total = func(total, element)
        yield total
329651
public void init(Object workingMemoryContext,
                     Object context,
                     Tuple leftTuple,
                     Declaration[] declarations,
                     WorkingMemory workingMemory) throws Exception {
        ((CollectContext) context).result = this.collect.instantiateResultObject( (InternalWorkingMemory) workingMemory );
    }
692318
public void accumulate(AverageData data,
                           Object value) {
        if (value != null) {
            data.count++;
            data.total = data.total.add( (BigDecimal) value );
        }
    }
828584
public void sumUp() {
        int offset=0;
        int tmp=0;
        for (int i = 0; i < numChunks; i++) {
            int[] chunk = chunks[i];
            if (chunk==null) throw new IllegalStateException("Chunks are not continous, null fragement at offset "+i);
            for (int j = 0; j < chunkSize; j++) {
                tmp = chunk[j];
                chunk[j] = offset;
                offset += tmp;
            }
        }
    }
1081005
def accumulate(iterable, func=operator.add):
    
    it = iter(iterable)
    total = next(it)
    yield total
    for element in it:
        total = func(total, element)
        yield total
1098575
protected void visitAccInlineCustomCode(RuleContext context2, AccumulateDescr descr, MethodCallExpr accumulateDSL, PatternDescr basePattern, PatternDescr inputDescr, Set<String> externalDeclrs) {
        context.pushExprPointer(accumulateDSL::addArgument);

        String targetClassName = StringUtil.toId(context2.getRuleDescr().getName()) + "Accumulate" + descr.getLine();
        String code = ACCUMULATE_INLINE_FUNCTION.replaceAll("AccumulateInlineFunction", targetClassName);

        CompilationUnit templateCU = JavaParser.parse(code);
        ClassOrInterfaceDeclaration templateClass = templateCU.getClassByName(targetClassName).orElseThrow(() -> new RuntimeException("Template did not contain expected type definition."));
        ClassOrInterfaceDeclaration templateContextClass = templateClass.getMembers().stream().filter(m -> m instanceof ClassOrInterfaceDeclaration && ((ClassOrInterfaceDeclaration) m).getNameAsString().equals("ContextData")).map(ClassOrInterfaceDeclaration.class::cast).findFirst().orElseThrow(() -> new RuntimeException("Template did not contain expected type definition."));

        List<String> contextFieldNames = new ArrayList<>();
        MethodDeclaration initMethod = templateClass.getMethodsByName("init").get(0);
        BlockStmt initBlock = JavaParser.parseBlock("{" + descr.getInitCode() + "}");
        List<DeclarationSpec> accumulateDeclarations = new ArrayList<>();
        Set<String> usedExtDeclrs = parseInitBlock( context2, descr, basePattern, templateContextClass, contextFieldNames, initMethod, initBlock, accumulateDeclarations );

        boolean useLegacyAccumulate = false;
        Type singleAccumulateType = null;
        MethodDeclaration accumulateMethod = templateClass.getMethodsByName("accumulate").get(0);
        BlockStmt actionBlock = parseBlock(descr.getActionCode());
        Collection<String> allNamesInActionBlock = collectNamesInBlock(context2, actionBlock);
        if (allNamesInActionBlock.size() == 1) {
            String nameExpr = allNamesInActionBlock.iterator().next();
            accumulateMethod.getParameter(1).setName(nameExpr);
            singleAccumulateType = context2.getDeclarationById(nameExpr).get().getType();
        } else {
            allNamesInActionBlock.removeIf( name -> !externalDeclrs.contains( name ) );
            usedExtDeclrs.addAll( allNamesInActionBlock );
            useLegacyAccumulate = true;
        }

        Optional<MethodDeclaration> optReverseMethod = Optional.empty();
        if(descr.getReverseCode() != null) {
            BlockStmt reverseBlock = parseBlock(descr.getReverseCode());
            Collection<String> allNamesInReverseBlock = collectNamesInBlock(context2, reverseBlock);
            if (allNamesInReverseBlock.size() == 1) {
                MethodDeclaration reverseMethod = templateClass.getMethodsByName("reverse").get(0);
                reverseMethod.getParameter(1).setName(allNamesInReverseBlock.iterator().next());
                optReverseMethod = Optional.of(reverseMethod);
            } else {
                allNamesInActionBlock.removeIf( name -> !externalDeclrs.contains( name ) );
                usedExtDeclrs.addAll( allNamesInActionBlock );
                useLegacyAccumulate = true;
            }
        }

        if ( useLegacyAccumulate || !usedExtDeclrs.isEmpty() ) {
            new LegacyAccumulate(context, descr, basePattern, usedExtDeclrs).build();
            return;
        }

        for(DeclarationSpec d : accumulateDeclarations) {
            context2.addDeclaration(d);
        }

        writeAccumulateMethod(contextFieldNames, singleAccumulateType, accumulateMethod, actionBlock);

        // <result expression>: this is a semantic expression in the selected dialect that is executed after all source objects are iterated.
        MethodDeclaration resultMethod = templateClass.getMethodsByName("getResult").get(0);
        Type returnExpressionType = JavaParser.parseType("java.lang.Object");
        Expression returnExpression = JavaParser.parseExpression(descr.getResultCode());
        if (returnExpression instanceof NameExpr) {
            returnExpression = new EnclosedExpr(returnExpression);
        }
        rescopeNamesToNewScope(new NameExpr("data"), contextFieldNames, returnExpression);
        resultMethod.getBody().get().addStatement(new ReturnStmt(returnExpression));
        MethodDeclaration getResultTypeMethod = templateClass.getMethodsByName("getResultType").get(0);
        getResultTypeMethod.getBody().get().addStatement(new ReturnStmt(new ClassExpr(returnExpressionType)));

        if (optReverseMethod.isPresent()) {
            MethodDeclaration supportsReverseMethod = templateClass.getMethodsByName("supportsReverse").get(0);
            supportsReverseMethod.getBody().get().addStatement(JavaParser.parseStatement("return true;"));

            BlockStmt reverseBlock = parseBlock(descr.getReverseCode());
            writeAccumulateMethod(contextFieldNames, singleAccumulateType, optReverseMethod.get(), reverseBlock);
        } else {
            MethodDeclaration supportsReverseMethod = templateClass.getMethodsByName("supportsReverse").get(0);
            supportsReverseMethod.getBody().get().addStatement(JavaParser.parseStatement("return false;"));

            MethodDeclaration reverseMethod = templateClass.getMethodsByName("reverse").get(0);
            reverseMethod.getBody().get().addStatement(JavaParser.parseStatement("throw new UnsupportedOperationException(\"This function does not support reverse.\");"));
        }

        // add resulting accumulator class into the package model
        this.packageModel.addGeneratedPOJO(templateClass);

        final MethodCallExpr functionDSL = new MethodCallExpr(null, ACC_FUNCTION_CALL);
        functionDSL.addArgument(new ClassExpr(JavaParser.parseType(targetClassName)));
        functionDSL.addArgument(context.getVarExpr(inputDescr.getIdentifier()));

        final String bindingId = basePattern.getIdentifier();
        final MethodCallExpr asDSL = new MethodCallExpr(functionDSL, BIND_AS_CALL);
        asDSL.addArgument( context.getVarExpr( bindingId ) );
        accumulateDSL.addArgument(asDSL);

        context.popExprPointer();
    }
557182
def accumulate(self, buf):
        ''''''
        bytes = array.array('B')
        if isinstance(buf, array.array):
            bytes.extend(buf)
        else:
            bytes.fromstring(buf)
        accum = self.crc
        for b in bytes:
            tmp = b ^ (accum & 0xff)
            tmp = (tmp ^ (tmp<<4)) & 0xFF
            accum = (accum>>8) ^ (tmp<<8) ^ (tmp<<3) ^ (tmp>>4)
            accum = accum & 0xFFFF
        self.crc = accum
150519
public void accumulate(Object workingMemoryContext,
                           Object context,
                           Tuple tuple,
                           InternalFactHandle handle,
                           Declaration[] declarations,
                           Declaration[] innerDeclarations,
                           WorkingMemory workingMemory) throws Exception {
        
        VariableResolverFactory factory = unit.getFactory( null, null, null, handle, tuple, null, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver()  );
        
        final Object value = MVEL.executeExpression( this.expression,
                                                     handle.getObject(),
                                                     factory );
        if ( this.function.supportsReverse() ) {
            ((MVELAccumulatorFunctionContext) context).reverseSupport.put( handle.getId(), value );
        }
        this.function.accumulate( ((MVELAccumulatorFunctionContext) context).context,
                                  value );
    }
177654
public static double sum(final double[] v1) {
    double acc = 0.;
    for(int row = 0; row < v1.length; row++) {
      acc += v1[row];
    }
    return acc;
  }
1169691
public void accumulate(CollectListData data,
                           Object value) {
        CollectListData.MutableInt counter = data.map.get( value );
        if( counter == null ) {
            counter = new CollectListData.MutableInt();
            data.map.put( value, counter );
        }
        counter.value++;
    }
106984
public double foldNonZeroInColumn(int j, VectorAccumulator accumulator) {
        eachNonZeroInColumn(j, Vectors.asAccumulatorProcedure(accumulator));
        return accumulator.accumulate();
    }
486188
public void init(Object workingMemoryContext,
                     Object context,
                     Tuple tuple,
                     Declaration[] declarations,
                     WorkingMemory workingMemory) throws Exception {
        Object[] localVars = new Object[initUnit.getOtherIdentifiers().length];
        
        MVELAccumulatorFactoryContext factoryContext = (MVELAccumulatorFactoryContext)workingMemoryContext;
        VariableResolverFactory factory = factoryContext.getInitFactory();
        initUnit.updateFactory( null, tuple, localVars, (InternalWorkingMemory) workingMemory, workingMemory.getGlobalResolver(), factory );

        InternalKnowledgePackage pkg = workingMemory.getKnowledgeBase().getPackage( "MAIN" );
        if ( pkg != null ) {
            MVELDialectRuntimeData data = (MVELDialectRuntimeData) pkg.getDialectRuntimeRegistry().getDialectData( "mvel" );
            factory.setNextFactory( data.getFunctionFactory() );
        }

        MVELSafeHelper.getEvaluator().executeExpression( this.init,
                                null,
                                factory );
        
        
        DroolsVarFactory df = ( DroolsVarFactory ) factory.getNextFactory();
        if ( localVars.length > 0 ) {
            for ( int i = 0; i < df.getOtherVarsLength(); i++ ) {
                localVars[i] = factory.getIndexedVariableResolver( df.getOtherVarsPos() + i ).getValue();
            }
        }
        
        ((MVELAccumulatorContext) context).setVariables( localVars );
    }
1308742
@Private
  @Override
  public void aggregationCompleted(final List<Integer> taskletIds, final TOutput result) {
    try {
      completedTasklets(result, taskletIds);
    } catch (final InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
402258
protected void aggregateSpecial(T value, int bin) {
    final T exist = getSpecial(bin);
    // Note: do not inline above accessor, as getSpecial will initialize the
    // special variable used below!
    special[bin] = aggregate(exist, value);
  }