Bulk ---------------
511250
protected function applyBulk( $model, $column, $action, $target, $config = [] ) {

		switch( $column ) {

			case 'model': {

				switch( $action ) {

					case 'sent': {

						$model->sent = true;

						$model->update();

						break;
					}
					case 'delivered': {

						$model->delivered = true;

						$model->update();

						break;
					}
					case 'consumed': {

						$model->consumed = true;

						$model->update();

						break;
					}
					case 'delete': {

						$this->delete( $model );

						break;
					}
				}

				break;
			}
		}
	}
558480
private boolean bulkRemove(Predicate<? super E> filter) {
        boolean removed = false;
        for (Node<E> p = first(), succ; p != null; p = succ) {
            succ = succ(p);
            final E item;
            if ((item = p.item) != null
                && filter.test(item)
                && ITEM.compareAndSet(p, item, null)) {
                unlink(p);
                removed = true;
            }
        }
        return removed;
    }
1210764
def _add_to_bulk(self, bulkobj):
        """"""
        bulkobj.add_replace(self._filter, self._doc, self._upsert,
                            collation=self._collation)
892818
function _jsifyBulkSet(bulkSet) {
        var arr = [];
        var it = bulkSet.iterator();
        while (it.hasNext()) {
            var key = it.next();
            var count = bulkSet.get(key);
            var elem = {
                key: jsify(key),
                count: count
            };
            arr.push(elem);
        }
        return arr;
    }
1313371
function bulkGet(db, opts, callback) {
  var requests = opts.docs;

  // consolidate into one request per doc if possible
  var requestsById = new pouchdbCollections.Map();
  requests.forEach(function (request) {
    if (requestsById.has(request.id)) {
      requestsById.get(request.id).push(request);
    } else {
      requestsById.set(request.id, [request]);
    }
  });

  var numDocs = requestsById.size;
  var numDone = 0;
  var perDocResults = new Array(numDocs);

  function collapseResultsAndFinish() {
    var results = [];
    perDocResults.forEach(function (res) {
      res.docs.forEach(function (info) {
        results.push({
          id: res.id,
          docs: [info]
        });
      });
    });
    callback(null, {results: results});
  }

  function checkDone() {
    if (++numDone === numDocs) {
      collapseResultsAndFinish();
    }
  }

  function gotResult(docIndex, id, docs) {
    perDocResults[docIndex] = {id: id, docs: docs};
    checkDone();
  }

  var allRequests = [];
  requestsById.forEach(function (value, key) {
    allRequests.push(key);
  });

  var i = 0;

  function nextBatch() {

    if (i >= allRequests.length) {
      return;
    }

    var upTo = Math.min(i + MAX_NUM_CONCURRENT_REQUESTS, allRequests.length);
    var batch = allRequests.slice(i, upTo);
    processBatch(batch, i);
    i += batch.length;
  }

  function processBatch(batch, offset) {
    batch.forEach(function (docId, j) {
      var docIdx = offset + j;
      var docRequests = requestsById.get(docId);

      // just use the first request as the "template"
      // TODO: The _bulk_get API allows for more subtle use cases than this,
      // but for now it is unlikely that there will be a mix of different
      // "atts_since" or "attachments" in the same request, since it's just
      // replicate.js that is using this for the moment.
      // Also, atts_since is aspirational, since we don't support it yet.
      var docOpts = pick(docRequests[0], ['atts_since', 'attachments']);
      docOpts.open_revs = docRequests.map(function (request) {
        // rev is optional, open_revs disallowed
        return request.rev;
      });

      // remove falsey / undefined revisions
      docOpts.open_revs = docOpts.open_revs.filter(identityFunction);

      var formatResult = identityFunction;

      if (docOpts.open_revs.length === 0) {
        delete docOpts.open_revs;

        // when fetching only the "winning" leaf,
        // transform the result so it looks like an open_revs
        // request
        formatResult = formatResultForOpenRevsGet;
      }

      // globally-supplied options
      ['revs', 'attachments', 'binary', 'ajax', 'latest'].forEach(function (param) {
        if (param in opts) {
          docOpts[param] = opts[param];
        }
      });
      db.get(docId, docOpts, function (err, res) {
        var result;
        /* istanbul ignore if */
        if (err) {
          result = [{error: err}];
        } else {
          result = formatResult(res);
        }
        gotResult(docIdx, docId, result);
        nextBatch();
      });
    });
  }

  nextBatch();

}
353092
def bulk(self, request, *args, **kwargs):
        
        manager = self.get_manager()
        errors = {}
        preferences = []
        payload = request.data

        # first, we check updated preferences actually exists in the registry
        try:
            for identifier, value in payload.items():
                try:
                    preferences.append(
                        self.queryset.model.registry.get(identifier))
                except exceptions.NotFoundInRegistry:
                    errors[identifier] = 'invalid preference'
        except (TypeError, AttributeError):
            return Response('invalid payload', status=400)

        if errors:
            return Response(errors, status=400)

        # now, we generate an optimized Q objects to retrieve all matching
        # preferences at once from database
        queries = [
            Q(section=p.section.name, name=p.name)
            for p in preferences
        ]

        query = queries[0]
        for q in queries[1:]:
            query |= q
        preferences_qs = self.get_queryset().filter(query)

        # next, we generate a serializer for each database preference
        serializer_objects = []
        for p in preferences_qs:
            s = self.get_serializer_class()(
                p, data={'value': payload[p.preference.identifier()]})
            serializer_objects.append(s)

        validation_errors = {}

        # we check if any serializer is invalid
        for s in serializer_objects:
            if s.is_valid():
                continue
            validation_errors[s.instance.preference.identifier()] = s.errors

        if validation_errors:
            return Response(validation_errors, status=400)

        for s in serializer_objects:
            s.save()

        return Response(
            [s.data for s in serializer_objects],
            status=200,
        )
1116143
def bulk_update(self, request):
        
        # Delete everything in the basket
        bid = utils.destroy_basket(request)

        for item_data in request.data:
            item = BasketItem(basket_id=bid, **item_data)
            item.save()

        serializer = BasketItemSerializer(self.get_queryset(request), many=True)
        response = Response(data=serializer.data,
                            status=status.HTTP_200_OK)
        return response
1296972
def dump_bulk(cls, parent=None, keep_ids=True):
        """"""

        serializable_cls = cls._get_serializable_model()
        if (
                parent and serializable_cls != cls and
                parent.__class__ != serializable_cls
        ):
            parent = serializable_cls.objects.get(pk=parent.pk)

        # a list of nodes: not really a queryset, but it works
        objs = serializable_cls.get_tree(parent)

        ret, lnk = [], {}
        for node, pyobj in zip(objs, serializers.serialize('python', objs)):
            depth = node.get_depth()
            # django's serializer stores the attributes in 'fields'
            fields = pyobj['fields']
            del fields['parent']

            # non-sorted trees have this
            if 'sib_order' in fields:
                del fields['sib_order']

            if 'id' in fields:
                del fields['id']

            newobj = {'data': fields}
            if keep_ids:
                newobj['id'] = pyobj['pk']

            if (not parent and depth == 1) or\
               (parent and depth == parent.get_depth()):
                ret.append(newobj)
            else:
                parentobj = lnk[node.parent_id]
                if 'children' not in parentobj:
                    parentobj['children'] = []
                parentobj['children'].append(newobj)
            lnk[node.pk] = newobj
        return ret
383831
public function validateBulkModelField($field, $modelClass, $bulkField, $column = 'id')
    {
        $this->validateValidity(
            $field,
            function ($uniqueAdvertIds) use ($modelClass, $column) {
                $uniqueAdverts = $modelClass::query()->inWhere($column, $uniqueAdvertIds)->execute();
                return count($uniqueAdvertIds) == $uniqueAdverts->count();
            },
            $bulkField
        );
    }
1080983
protected void bulkInsertWithComparator() {
        if (insertionBufferSize == 0) {
            return;
        }
        int right = size + insertionBufferSize - 2;
        int left = Math.max(size, right / 2);
        while (insertionBufferSize > 0) {
            --insertionBufferSize;
            array[size] = insertionBuffer[insertionBufferSize];
            insertionBuffer[insertionBufferSize] = null;
            reverse.clear(size);
            ++size;
        }
        while (right > left + 1) {
            left = left / 2;
            right = right / 2;
            for (int j = left; j <= right; j++) {
                fixdownWithComparator(j);
            }
        }
        if (left != 0) {
            int i = dancestor(left);
            fixdownWithComparator(i);
            fixupWithComparator(i);
        }
        if (right != 0) {
            int i = dancestor(right);
            fixdownWithComparator(i);
            fixupWithComparator(i);
        }
        insertionBufferMinPos = 0;
    }
1217804
public function bulkEditForm()
    {
        $crumbs = $this->Breadcrumbs();
        if ($crumbs && $crumbs->count() >= 2) {
            $one_level_up = $crumbs->offsetGet($crumbs->count() - 2);
        }

        $actions = new FieldList();

        $actions->push(
            FormAction::create('doSave', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.SAVE_BTN_LABEL', 'Save all'))
                ->setAttribute('id', 'bulkEditingSaveBtn')
                ->addExtraClass('btn btn-success')
                ->setAttribute('data-icon', 'accept')
                ->setUseButtonTag(true)
        );

        $actions->push(
            FormAction::create('Cancel', _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.CANCEL_BTN_LABEL', 'Cancel'))
                ->setAttribute('id', 'bulkEditingUpdateCancelBtn')
                ->addExtraClass('btn btn-danger cms-panel-link')
                ->setAttribute('data-icon', 'decline')
                ->setAttribute('href', $one_level_up->Link)
                ->setUseButtonTag(true)
                ->setAttribute('src', '')//changes type to image so isn't hooked by default actions handlers
        );

        $recordList = $this->getRecordIDList();
        $recordsFieldList = new FieldList();
        $config = $this->component->getConfig();

        $editingCount = count($recordList);
        $modelClass = $this->gridField->getModelClass();
        $singleton = singleton($modelClass);
        $titleModelClass = (($editingCount > 1) ? $singleton->i18n_plural_name() : $singleton->i18n_singular_name());

        //some cosmetics
        $headerText = _t(
            'GRIDFIELD_BULKMANAGER_EDIT_HANDLER.HEADER_TEXT',
            'Editing {count} {class}',
            array(
                'count' => $editingCount,
                'class' => $titleModelClass,
            )
        );
        $header = LiteralField::create(
            'bulkEditHeader',
            '<h1 id="bulkEditHeader">'.$headerText.'</h1>'
        );
        $recordsFieldList->push($header);

        $toggle = LiteralField::create(
            'bulkEditToggle',
            '<span id="bulkEditToggle">' . _t('GRIDFIELD_BULKMANAGER_EDIT_HANDLER.TOGGLE_ALL_LINK', 'Show/Hide all') . '</span>'
        );
        $recordsFieldList->push($toggle);

        //fetch fields for each record and push to fieldList
        foreach ($recordList as $id) {
            $record = DataObject::get_by_id($modelClass, $id);
            $recordEditingFields = $this->getRecordEditingFields($record);

            $toggleField = ToggleCompositeField::create(
                'RecordFields_' . $id,
                $record->getTitle(),
                $recordEditingFields
            )
            ->setHeadingLevel(4)
            ->setAttribute('data-id', $id)
            ->addExtraClass('bulkEditingFieldHolder');

            $recordsFieldList->push($toggleField);
        }

        $bulkEditForm = Form::create(
            $this,
            'recordEditForm', //recordEditForm name is here to trick SS to pass all subform request to recordEditForm()
            $recordsFieldList,
            $actions
        );

        if ($crumbs && $crumbs->count() >= 2) {
            $bulkEditForm->Backlink = $one_level_up->Link;
        }

        //override form action URL back to bulkEditForm
        //and add record ids GET var
        $bulkEditForm->setAttribute(
            'action',
            $this->Link('bulkEditForm?records[]='.implode('&', $recordList))
        );

        return $bulkEditForm;
    }
1180253
def get_bulk(self, create=False):
        """"""
        result = []
        op_type = "index"
        if create:
            op_type = "create"
        meta = self._meta
        cmd = {op_type: {"_index": meta.index, "_type": meta.type}}
        if meta.parent:
            cmd[op_type]['_parent'] = meta.parent
        if meta.version:
            cmd[op_type]['_version'] = meta.version
        if meta.id:
            cmd[op_type]['_id'] = meta.id
        result.append(json.dumps(cmd, cls=self._meta.connection.encoder))
        result.append("\n")
        result.append(json.dumps(self, cls=self._meta.connection.encoder))
        result.append("\n")
        return ''.join(result)
243935
def get_bulk_modify(self, value):
        """"""
        if self.multiselect:
            value = value or []
            return [self.cast_to_bulk_modify(child) for child in value]

        return self.cast_to_bulk_modify(value)
423353
def bulk_submit(cls, imports, api=None):
        
        if not imports:
            raise SbgError('Imports are required')

        api = api or cls._API

        items = []
        for import_ in imports:
            volume = Transform.to_volume(import_.get('volume'))
            location = Transform.to_location(import_.get('location'))
            project = Transform.to_project(import_.get('project'))
            name = import_.get('name', None)
            overwrite = import_.get('overwrite', False)

            item = {
                'source': {
                    'volume': volume,
                    'location': location
                },
                'destination': {
                    'project': project
                },
                'overwrite': overwrite
            }

            if name:
                item['destination']['name'] = name

            items.append(item)

        data = {'items': items}

        response = api.post(url=cls._URL['bulk_create'], data=data)
        return ImportBulkRecord.parse_records(response=response, api=api)
1030753
def bulk_update_batches(aggregations)
      en = Enumerator.new do |e|
        i = 1
        batch = []
        aggregations.each do |agg|
          batch << agg
          if i % @bulk_update_size == 0
            e.yield batch
            batch = []
          end
          i += 1
        end
        e.yield batch if batch.count > 0  # last one
      end
      en.lazy
    end
1028995
public static function sendBulk($handle, $bulk) {
        $buffer = self::_parseBulk($bulk);
        return self::_writeToServer($handle, $buffer);
    }
375631
def bulk_insert(self, resource, docs, **kwargs):
        """"""
        kwargs.update(self._es_args(resource))
        parent_type = self._get_parent_type(resource)
        if parent_type:
            for doc in docs:
                if doc.get(parent_type.get('field')):
                    doc['_parent'] = doc.get(parent_type.get('field'))

        res = bulk(self.elastic(resource), docs, stats_only=False, **kwargs)
        self._refresh_resource_index(resource)
        return res