@param array $records

@return DecisionTreeLeaf
167249
protected function getBestSplit(array $records) : DecisionTreeLeaf
    {
        $targets = array_intersect_key($this->targets, array_flip($records));
        $samples = array_intersect_key($this->samples, array_flip($records));
        $samples = array_combine($records, $this->preprocess($samples));
        $bestGiniVal = 1;
        $bestSplit = null;
        $features = $this->getSelectedFeatures();
        foreach ($features as $i) {
            $colValues = [];
            foreach ($samples as $index => $row) {
                $colValues[$index] = $row[$i];
            }
            $counts = array_count_values($colValues);
            arsort($counts);
            $baseValue = key($counts);
            $gini = $this->getGiniIndex($baseValue, $colValues, $targets);
            if ($bestSplit === null || $bestGiniVal > $gini) {
                $split = new DecisionTreeLeaf();
                $split->value = $baseValue;
                $split->giniIndex = $gini;
                $split->columnIndex = $i;
                $split->isContinuous = $this->columnTypes[$i] == self::CONTINUOUS;
                $split->records = $records;

                // If a numeric column is to be selected, then
                // the original numeric value and the selected operator
                // will also be saved into the leaf for future access
                if ($this->columnTypes[$i] == self::CONTINUOUS) {
                    $matches = [];
                    preg_match("/^([<>=]{1,2})\s*(.*)/", strval($split->value), $matches);
                    $split->operator = $matches[1];
                    $split->numericValue = floatval($matches[2]);
                }

                $bestSplit = $split;
                $bestGiniVal = $gini;
            }
        }

        return $bestSplit;
    }
983507
protected function filterRecord(array $record)
    {
        foreach ($this->filteredKeys as $key) {
            if (isset($record[$key]) {
                unset($record[$key]);
            }
        }
        
        // Convert datetime object to string
        if (! isset($record['datetime'])) {
            $record['datetime'] = new \DateTime("now");
        }
        $record['datetime'] = $record['datetime']->format(self::DATE_FORMAT);

        return $record;
    }
1003474
protected function processSearchResults($records)
    {
        $results = [];
        foreach ($records as $record) {
            foreach ($record as $attribute => $value) {
                // if the value is an array with a single value, e.g. 'samaccountname' => array(0 => 'myusername')
                // then make sure it's just set in the results as 'samaccountname' => 'myusername' so that it
                // can be used directly by ArrayData
                if (is_array($value) && count($value) == 1) {
                    $value = $value[0];
                }

                // ObjectGUID and ObjectSID attributes are in binary, we need to convert those to strings
                if ($attribute == 'objectguid') {
                    $value = LDAPUtil::bin_to_str_guid($value);
                }
                if ($attribute == 'objectsid') {
                    $value = LDAPUtil::bin_to_str_sid($value);
                }

                $record[$attribute] = $value;
            }

            $results[] = $record;
        }

        return $results;
    }
625981
protected function _getRecords(array $records, TableSchema $schema)
    {
        $fields = $values = $types = [];
        $columns = $schema->columns();
        foreach ($records as $record) {
            $fields = array_merge($fields, array_intersect(array_keys($record), $columns));
        }
        $fields = array_values(array_unique($fields));
        foreach ($fields as $field) {
            $types[$field] = $schema->column($field)['type'];
        }
        $default = array_fill_keys($fields, null);
        foreach ($records as $record) {
            $values[] = array_merge($default, $record);
        }

        return [$fields, $values, $types];
    }
609692
protected function transform_db_records_to_entities(array $records) {
        $preprocessors = $this->get_preprocessors();
        $result = array_map(function($record) {
            return ['record' => $record];
        }, $records);

        $result = array_reduce(array_keys($preprocessors), function($carry, $preprocessor) use ($records, $preprocessors) {
            $step = $preprocessors[$preprocessor];
            $dependencies = $step->execute($records);

            foreach ($dependencies as $index => $dependency) {
                // Add the new dependency to the list.
                $carry[$index] = array_merge($carry[$index], [$preprocessor => $dependency]);
            }

            return $carry;
        }, $result);

        return $this->from_db_records($result);
    }
206857
protected function addRecord(array $record)
    {
        return $this->document->fputcsv($record, $this->delimiter, $this->enclosure, $this->escape);
    }
649072
public function createMany(array $records, array $properties = array())
    {
        $instances = new Collection;

        foreach ($records as $record)
        {
            $instances->push($this->create($record, $properties));
        }

        return $instances;
    }
451402
protected function fillArrayWithRecords( array &$results, array $records, $limit, $offset )
    {
        $length = min( count( $records ), $limit );

        $index = 0;

        foreach ($records as $record) {
            $offset += $this->fillArrayWithSingleRecord( $results, $record, $offset );

            $index++;

            if ($index >= $length) {
                break;
            }
        }
    }
1068652
protected function map(array $record)
    {
        $mapping = $this->getMapping();

        if (count($mapping) > 0) {
            $result = [];

            foreach ($mapping as $columnId => $data) {
                if (!empty($data[0])) {
                    if (!isset($result[$data[0]])) {
                        $result[$data[0]] = [];
                    }
                    $result[$data[0]][$data[1]] = $record[$columnId];
                } else {
                    $result[$data[1]] = $record[$columnId];
                }
            }

            return $result;
        } else {
            return $record;
        }
    }
762668
public function groupRecords($records)
    {
        if (!is_array($records) || empty($records)) {
            return;
        }

        $groups = array('year' => array());

        foreach ($records as $r) {
            $data = $r->getData($this->get('id'));

            $timestamp = DateTimeObj::get('U', $data['value']);
            $info = getdate($timestamp);

            $year = $info['year'];
            $month = ($info['mon'] < 10 ? '0' . $info['mon'] : $info['mon']);

            if (!isset($groups['year'][$year])) {
                $groups['year'][$year] = array(
                    'attr' => array('value' => $year),
                    'records' => array(),
                    'groups' => array()
                );
            }

            if (!isset($groups['year'][$year]['groups']['month'])) {
                $groups['year'][$year]['groups']['month'] = array();
            }

            if (!isset($groups['year'][$year]['groups']['month'][$month])) {
                $groups['year'][$year]['groups']['month'][$month] = array(
                    'attr' => array('value' => $month),
                    'records' => array(),
                    'groups' => array()
                );
            }

            $groups['year'][$year]['groups']['month'][$month]['records'][] = $r;
        }

        return $groups;
    }
396197
protected function bulkSend(array $records): void
    {
        try {
            $params = [
                'body' => [],
            ];

            foreach ($records as $record) {
                $params['body'][] = [
                    'index' => [
                        '_index' => $record['_index'],
                        '_type'  => $record['_type'],
                    ],
                ];
                unset($record['_index'], $record['_type']);

                $params['body'][] = $record;
            }

            $responses = $this->client->bulk($params);

            if ($responses['errors'] === true) {
                throw new ElasticsearchRuntimeException('Elasticsearch returned error for one of the records');
            }
        } catch (Throwable $e) {
            if (! $this->options['ignore_error']) {
                throw new RuntimeException('Error sending messages to Elasticsearch', 0, $e);
            }
        }
    }
950192
public static function bulkCreate(array $records, array $params = [])
    {
        if (empty($records)) {
            throw new BadRequestException('There are no record sets in the request.');
        }

        $response = [];
        $errors = false;
        $rollback = array_get_bool($params, ApiOptions::ROLLBACK);
        $continue = array_get_bool($params, ApiOptions::CONTINUES);

        if ($rollback) {
            //	Start a transaction
            DB::beginTransaction();
        }

        foreach ($records as $key => $record) {
            try {
                $response[$key] = static::createInternal($record, $params);
            } catch (\Exception $ex) {
                $errors = true;
                $response[$key] = $ex;
                // track the index of the error and copy error to results
                if ($rollback || !$continue) {
                    break;
                }
            }
        }

        if ($errors) {
            $msg = "Batch Error: Not all requested records could be created.";
            if ($rollback) {
                DB::rollBack();
                $msg .= " All changes rolled back.";
            }

            throw new BatchException($response, $msg);
        }

        if ($rollback) {
            DB::commit();
        }

        return $response;
    }
1352742
protected function formatBatchNewlines(array $records): string
    {
        $instance = $this;

        $oldNewline = $this->appendNewline;
        $this->appendNewline = false;
        array_walk($records, function (&$value, $key) use ($instance) {
            $value = $instance->format($value);
        });
        $this->appendNewline = $oldNewline;

        return implode("\n", $records);
    }
1055366
public function handleBatch(array $records)
    {
        $records = $this->recordFilter($records);
        if (empty($records)) {
            return true;
        }

        $lines = array_column($records, 'formatted');

        $this->write($lines);
    }
315616
public function saveRecords(array $records, DataDimensions $dataDimensions = null)
    {

        if (!$dataDimensions) {
            $dataDimensions = $this->getCurrentDataDimensions();
        }

        $recordIds = [];
        foreach ($records as $record) {
            $recordIds[] = $this->saveRecord($record, $dataDimensions);
        }

        return $recordIds;

    }
792488
public function import(array $definitions, array $records, array $defaultAttributes = [], $persist = true): array
    {
        $imported = [];
        $recordsByHandle = $this->getRecordsByHandle($records);
        foreach ($definitions as $handle => $definition) {
            $modelClass = $definition['class'];
            $converter = Craft::$app->controller->module->getConverter($modelClass);
            if ($converter) {
                $record = $this->findOrNewRecord($recordsByHandle, $definition, $handle);

                if ($converter->getRecordDefinition($record) === $definition) {
                    Schematic::info('- Skipping '.get_class($record).' '.$handle);
                } else {
                    $converter->setRecordAttributes($record, $definition, $defaultAttributes);
                    if ($persist) {
                        Schematic::info('- Saving '.get_class($record).' '.$handle);
                        if (!$converter->saveRecord($record, $definition)) {
                            Schematic::importError($record, $handle);
                        }
                    }
                }

                $imported[] = $record;
            }
            unset($recordsByHandle[$handle]);
        }

        if (Schematic::$force && $persist) {
            // Delete records not in definitions
            foreach ($recordsByHandle as $handle => $record) {
                $modelClass = get_class($record);
                Schematic::info('- Deleting '.get_class($record).' '.$handle);
                $converter = Craft::$app->controller->module->getConverter($modelClass);
                $converter->deleteRecord($record);
            }
        }

        return $imported;
    }
1123848
public static function sortRecord($records, $field, $order=true)
    {
        $new_array = array();
        $sortable_array = array();

        if (count($records) > 0) {
            foreach ($records as $k => $v) {
                if (is_array($v)) {
                    foreach ($v as $k2 => $v2) {
                        if ($k2 == $field) {
                            $sortable_array[$k] = $v2;
                        }
                    }
                } else {
                    $sortable_array[$k] = $v;
                }
            }

            switch ($order) {
                case true:
                    asort($sortable_array);
                break;
                case false:
                    arsort($sortable_array);
                break;
            }

            foreach ($sortable_array as $k => $v) {
                $new_array[$k] = $records[$k];
            }
        }

        return $new_array;
    }