Calculates the average value on a given column. Returns +nil+ if there's
 no row.

   PersonMock.average(:age) # => 35.8
183233
def average(key)
      values = values_by_key(key)
      total  = values.inject { |sum, n| sum + n }
      BigDecimal.new(total) / BigDecimal.new(values.count)
    end
937269
def _avg(value1, value2, weight):
        
        if value1 is None:
            return value2
        if value2 is None:
            return value1
        return value2 * weight + value1 * (1 - weight)
601115
def _get_inferred_data_column(column):
    
    try:
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            # Get the values for this column
            values = column["values"]
            # Make sure that age and values are numpy arrays
            _values = np.array(copy.copy(values), dtype=float)
            # If we have values, keep going
            if len(_values) != 0:
                # Remove the NaNs from the values list.
                _values = _values[np.where(~np.isnan(_values))[0]]
                # Use the values to create new entries and data
                column.update(__get_inferred_data_res_2(_values))

            # Even though we're not calculating resolution, still add it with "NaN" placeholders.
            column["hasResolution"] = __get_inferred_data_res_2(None, calc=False)

    except KeyError as e:
        logger_inferred_data.debug("get_inferred_data_column: KeyError: {}".format(e))
    except Exception as e:
        logger_inferred_data.debug("get_inferred_data_column: Exception: {}".format(e))

    return column
230347
def item_at(self, row, column):
        
        return self.children[str(row)].children[str(column)]
1184806
function average(expression) {

        //Define output
        var outData;

        //If there's no expression
        if (!expression){

            //Just assign current items
            outData = this.items;
        }
        else{

            //Otherwise apply select condition
            outData = jslinq(this.items)
                .select(expression)
                .toList();
        }

        //If array has no elements, returns null
        if (outData.length === 0){
            return null;
        }
        else{

            //Sum every value
            var valuesSum = 0;

            //Iterate all elements on list
            for (var i = 0; i < outData.length; i++){

                //If element is not number, throw
                if (isNaN(outData[i]))
                    throw new Error("Element '" + outData[i] +
                        "' (index:" + i + ") is not a number");

                //Increment sum
                valuesSum = outData[i] + valuesSum;
            }

            //Calculate average
            var outAverage = valuesSum / outData.length

            //Returns first element
            return outAverage;
        }
    }
171097
def load_average(self):
        
        with io.open(self.load_average_file, 'r') as f:
            file_columns = f.readline().strip().split()
            return float(file_columns[self._load_average_file_column])
212280
public static function AVERAGE()
    {
        $returnValue = $aCount = 0;

        // Loop through arguments
        foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) {
            if ((is_bool($arg)) &&
                ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
                $arg = (integer) $arg;
            }
            // Is it a numeric value?
            if ((is_numeric($arg)) && (!is_string($arg))) {
                if (is_null($returnValue)) {
                    $returnValue = $arg;
                } else {
                    $returnValue += $arg;
                }
                ++$aCount;
            }
        }

        // Return
        if ($aCount > 0) {
            return $returnValue / $aCount;
        } else {
            return PHPExcel_Calculation_Functions::DIV0();
        }
    }
1071224
def avg(self, key=None):
        
        count = self.count()

        if count:
            return self.sum(key) / count
780079
function averageValues(categorical, numeric) {
  const sumMap = {};
  const [uniques, counts] = uniqueValues(categorical);
  for (let i = 0; i < uniques.length; ++i) {
    sumMap[uniques[i]] = {
      sum: 0,
      count: counts[i],
    };
  }
  for (let j = 0; j < numeric.length; ++j) {
    sumMap[categorical[j]].sum += parseFloat(numeric[j]);
  }
  const u = [];
  const a = [];
  Object.keys(sumMap).forEach((uniqueKey) => {
    u.push(uniqueKey);
    a.push(sumMap[uniqueKey].sum / sumMap[uniqueKey].count);
  });
  return [u, a];
}
33858
def cmd_average_response_time(self):
        """"""
        average = [
            line.time_wait_response
            for line in self._valid_lines
            if line.time_wait_response >= 0
        ]

        divisor = float(len(average))
        if divisor > 0:
            return sum(average) / float(len(average))
        return 0
524703
def column_aggregate_expectation(cls, func):
        
        if PY3:
            argspec = inspect.getfullargspec(func)[0][1:]
        else:
            argspec = inspect.getargspec(func)[0][1:]

        @cls.expectation(argspec)
        @wraps(func)
        def inner_wrapper(self, column, result_format=None, *args, **kwargs):

            if result_format is None:
                result_format = self.default_expectation_args["result_format"]

            result_format = parse_result_format(result_format)

            evaluation_result = func(self, column, *args, **kwargs)

            if 'success' not in evaluation_result:
                raise ValueError(
                    "Column aggregate expectation failed to return required information: success")

            if 'result' not in evaluation_result:
                raise ValueError(
                    "Column aggregate expectation failed to return required information: result")

            if 'observed_value' not in evaluation_result['result']:
                raise ValueError(
                    "Column aggregate expectation failed to return required information: result.observed_value")

            return_obj = {
                'success': bool(evaluation_result['success'])
            }

            if result_format['result_format'] == 'BOOLEAN_ONLY':
                return return_obj

            # Use the element and null count information from a column_aggregate_expectation if it is needed
            # it anyway to avoid an extra trip to the database

            if 'element_count' not in evaluation_result and 'null_count' not in evaluation_result:
                count_query = sa.select([
                    sa.func.count().label('element_count'),
                    sa.func.sum(
                        sa.case([(sa.column(column) == None, 1)], else_=0)
                    ).label('null_count'),
                ]).select_from(self._table)

                count_results = dict(
                    self.engine.execute(count_query).fetchone())

                # Handle case of empty table gracefully:
                if "element_count" not in count_results or count_results["element_count"] is None:
                    count_results["element_count"] = 0
                if "null_count" not in count_results or count_results["null_count"] is None:
                    count_results["null_count"] = 0

                return_obj['result'] = {
                    'observed_value': evaluation_result['result']['observed_value'],
                    "element_count": count_results['element_count'],
                    "missing_count": count_results['null_count'],
                    "missing_percent": count_results['null_count'] / count_results['element_count'] if count_results['element_count'] > 0 else None
                }
            else:
                return_obj['result'] = {
                    'observed_value': evaluation_result['result']['observed_value'],
                    "element_count": evaluation_result["element_count"],
                    "missing_count": evaluation_result["null_count"],
                    "missing_percent": evaluation_result['null_count'] / evaluation_result['element_count'] if evaluation_result['element_count'] > 0 else None
                }

            if result_format['result_format'] == 'BASIC':
                return return_obj

            if 'details' in evaluation_result['result']:
                return_obj['result']['details'] = evaluation_result['result']['details']

            if result_format['result_format'] in ["SUMMARY", "COMPLETE"]:
                return return_obj

            raise ValueError("Unknown result_format %s." %
                             (result_format['result_format'],))

        return inner_wrapper
276413
public Statistics columnAvgLength(String columnName, Double avgLen) {
		this.columnStats
			.computeIfAbsent(columnName, column -> new HashMap<>())
			.put(AVG_LENGTH, String.valueOf(avgLen));
		return this;
	}
106569
def get_average(self, default=None):
        
        try:
            first_row = self.get_first()
            if first_row:
                count0 = first_row[0]['Count']
            else:
                count0 = 0
            average = (self.count - count0) / (self.get_number_of_rows() - 1)
        except Exception as e:
            logging.error(e)
            return default
        else:
            return average
115486
private double calcMean(double[] arr) {
        double mean = 0;
        for (double resid : arr) {
            mean += resid;
        }
        mean /= arr.length;
        return mean;
    }
120071
def moving_average_value(self, date):
        
        val, conti = self.__calculate_moving_average(date, 1)
        val = (round(i / 1000, 3) for i in val)
        return list(val), conti
249437
def colum_avg(self, state):
        """"""
        self.colum_avg_enabled = state > 0
        if self.colum_avg_enabled:
            self.return_max = lambda col_vals, index: col_vals[index]
        else:
            self.return_max = global_max
        self.reset()
921805
def _get_age(columns):
    

    # Need to check multiple places for age, year, or yrbp
    # 1. Check the column variable name
    # 2. Check for an "inferredVariableType

    age = []
    try:
        # Step 1:
        # Check for age first (exact match)
        if "age" in columns:
            # Save the values
            age = columns["age"]["values"]
        # Check for year second (exact match)
        elif "year" in columns:
            # Save the values
            age = columns["year"]["values"]
        elif "yrbp" in columns:
            # Save the values
            age = columns["yrbp"]["values"]

        # Step 2 No exact matches, check for an "inferredVariableType" : "Age" or "Year"
        if not age:
            # Loop through column variableNames
            for k, v in columns.items():
                try:
                    if v["inferredVariableType"].lower() == "age":
                        age = v["values"]
                    elif v["inferredVariableType"].lower() == "year":
                        age = v["values"]
                except Exception:
                    # Not too concerned if we error here.
                    pass

        # Step 3: No year or age found, start searching for a loose match with "age" or "year" in the variableName.
        if not age:
            # Loop through column variableNames
            for k, v in columns.items():
                k_low = k.lower()
                # Check for age in the variableName (loose match)
                if "age" in k_low:
                    # Save the values
                    age = v["values"]
                # Check for year in variableName (loose match)
                elif "year" in k_low:
                    # Save the values
                    age = v["values"]
                elif "yrbp" in k_low:
                    # Save the values
                    age = v["values"]

    # If we expected a dictionary, and didn't get one
    except AttributeError as e:
        logger_inferred_data.warn("get_age: AttributeError: {}".format(e))
    # If we were looking for values, and didn't get one
    except KeyError as e:
        logger_inferred_data.warn("get_age: KeyError: {}".format(e))
    # Fail-safe for other problems
    except Exception as e:
        logger_inferred_data.warn("get_age: Exception: {}".format(e))

    return age