Aggregate census table variables by a custom label.
546017
def aggregate_variable(estimate, id):
        
        estimates = [
            variable.estimates.get(division__id=id).estimate
            for variable in estimate.variable.label.variables.all()
        ]
        method = estimate.variable.label.aggregation
        if method == "s":
            aggregate = sum(estimates)
        elif method == "a":
            aggregate = statistics.mean(estimates)
        elif method == "m":
            aggregate = statistics.median(estimates)
        else:
            aggregate = None
        return aggregate
1015481
def add_metric(self, labels, value, created=None, timestamp=None):
        
        self.samples.append(Sample(self.name + '_total', dict(zip(self._labelnames, labels)), value, timestamp))
        if created is not None:
            self.samples.append(Sample(self.name + '_created', dict(zip(self._labelnames, labels)), created, timestamp))
636295
def stacked_graph(labels, data, normal_data, len_categories, args, colors):
    """"""
    val_min = find_min(data)

    for i in range(len(labels)):
        if args['no_labels']:
            # Hide the labels.
            label = ''
        else:
            label = "{:<{x}}: ".format(labels[i],
                                       x=find_max_label_length(labels))

        print(label, end="")
        values = data[i]
        num_blocks = normal_data[i]

        for j in range(len(values)):
            print_row(values[j], int(num_blocks[j]), val_min, colors[j])

        tail = ' {}{}'.format(args['format'].format(sum(values)),
                              args['suffix'])
        print(tail)
125625
def label(self):
        """""""

        if self.valuetype_class.is_label():
            return self

        for c in self.table.columns:
            if c.parent == self.name and  c.valuetype_class.is_label():
                return c

        return None
993333
def _populate_label_legacy_structures():
    
    global DIE_CUT_LABEL, ENDLESS_LABEL, ROUND_DIE_CUT_LABEL
    global label_sizes, label_type_specs

    from brother_ql.labels import FormFactor
    DIE_CUT_LABEL =       FormFactor.DIE_CUT
    ENDLESS_LABEL =       FormFactor.ENDLESS
    ROUND_DIE_CUT_LABEL = FormFactor.ROUND_DIE_CUT

    from brother_ql.labels import LabelsManager
    lm = LabelsManager()
    label_sizes = list(lm.iter_identifiers())
    for label in lm.iter_elements():
        l = {}
        l['name'] = label.name
        l['kind'] = label.form_factor
        l['color'] = label.color
        l['tape_size'] = label.tape_size
        l['dots_total'] = label.dots_total
        l['dots_printable'] = label.dots_printable
        l['right_margin_dots'] = label.offset_r
        l['feed_margin'] = label.feed_margin
        l['restrict_printers'] = label.restricted_to_models
        label_type_specs[label.identifier] = l
473399
def gauge(self, key, gauge=None, default=float("nan"), **dims):
        """"""
        return super(MetricsRegistry, self).gauge(
            self.metadata.register(key, **dims), gauge=gauge, default=default)
953076
def stats(args):
    
    from jcvi.utils.table import tabulate

    p = OptionParser(stats.__doc__)
    p.add_option("--warn", default=False, action="store_true",
                 help="Warnings on small component spans [default: %default]")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(p.print_help())

    agpfile, = args

    agp = AGP(agpfile)
    gap_lengths = []
    component_lengths = []
    for a in agp:
        span = a.object_span
        if a.is_gap:
            label = a.gap_type
            gap_lengths.append((span, label))
        else:
            label = "{0}:{1}-{2}".format(a.component_id, a.component_beg, \
                   a.component_end)
            component_lengths.append((span, label))
            if opts.warn and span < 50:
                logging.error("component span too small ({0}):\n{1}".\
                    format(span, a))

    table = dict()
    for label, lengths in zip(("Gaps", "Components"),
            (gap_lengths, component_lengths)):

        if not lengths:
            table[(label, "Min")] = table[(label, "Max")] \
                                  = table[(label, "Sum")] = "n.a."
            continue

        table[(label, "Min")] = "{0} ({1})".format(*min(lengths))
        table[(label, "Max")] = "{0} ({1})".format(*max(lengths))
        table[(label, "Sum")] = sum(x[0] for x in lengths)

    print(tabulate(table), file=sys.stderr)
708066
def write_county_estimate(self, table, variable, code, datum):
        
        try:
            division = Division.objects.get(
                code="{}{}".format(datum["state"], datum["county"]),
                level=self.COUNTY_LEVEL,
            )
            CensusEstimate.objects.update_or_create(
                division=division,
                variable=variable,
                defaults={"estimate": datum[code] or 0},
            )
        except ObjectDoesNotExist:
            print("ERROR: {}, {}".format(datum["NAME"], datum["state"]))
1173634
def _aggregate_dataset(self, obj, xcoords, ycoords):
        
        dim_labels = obj.dimensions(label=True)
        vdims = obj.dimensions()[2:]
        xdim, ydim = dim_labels[:2]
        shape = (len(ycoords), len(xcoords))
        nsamples = np.product(shape)
        grid_data = {xdim: xcoords, ydim: ycoords}

        ys, xs = cartesian_product([ycoords, xcoords], copy=True)
        data = {xdim: xs, ydim: ys}
        for vdim in vdims:
            values = np.empty(nsamples)
            values[:] = np.NaN
            data[vdim.name] = values
        dtype = default_datatype
        dense_data = Dataset(data, kdims=obj.kdims, vdims=obj.vdims, datatype=[dtype])
        concat_data = obj.interface.concatenate([dense_data, obj], datatype=dtype)
        reindexed = concat_data.reindex([xdim, ydim], vdims)
        if not reindexed:
            agg = reindexed
        elif pd:
            df = PandasInterface.as_dframe(reindexed)
            df = df.groupby([xdim, ydim], sort=False).first().reset_index()
            agg = reindexed.clone(df)
        else:
            agg = reindexed.aggregate([xdim, ydim], reduce_fn)

        # Convert data to a gridded dataset
        for vdim in vdims:
            grid_data[vdim.name] = agg.dimension_values(vdim).reshape(shape)
        return agg.clone(grid_data, kdims=[xdim, ydim], vdims=vdims,
                         datatype=self.p.datatype)
1298169
def _get_label(self, axis):
        """"""

        if axis == 'x':
            colname = self.x_col
        else:  # y
            colname = self.y_col

        if colname == self._idxname:
            label = 'Index'
        else:
            col = self.tab[colname]
            if col.unit:
                label = '{0} ({1})'.format(col.name, col.unit)
            else:
                label = col.name

        return label
1139270
def _attach_dim_scales(self):
        """"""
        for name, var in self.variables.items():
            if name not in self.dimensions:
                for n, dim in enumerate(var.dimensions):
                    var._h5ds.dims[n].attach_scale(self._all_h5groups[dim])

        for subgroup in self.groups.values():
            subgroup._attach_dim_scales()
826369
def aggregate_tile(cells, ti, tj, aggregate, params, metadata, layout, summary):
  
  tile = []
  keys = cells.keys()
  for i,key in enumerate(keys):
    print("cell", i+1, "/", len(keys), end='\r')
    cell_json = aggregate(cells[key], params, metadata, layout, summary)
    tile.append({"aggregate":cell_json, "i":int(key[0]), "j":int(key[1])})
  return tile
1084690
def is_label_dataframe(label, df):
    """"""

    setdiff = set(label) - set(df.columns.tolist())

    if len(setdiff) == 0:
        return True
    else:
        return False
121048
def prepare_values(self, raw, offset=0):
        """"""
        from pygal.graph.map import BaseMap
        from pygal import Histogram

        if self.zero == 0 and isinstance(self, BaseMap):
            self.zero = 1

        if self.x_label_rotation:
            self.x_label_rotation %= 360

        if self.y_label_rotation:
            self.y_label_rotation %= 360

        for key in ('x_labels', 'y_labels'):
            if getattr(self, key):
                setattr(self, key, list(getattr(self, key)))
        if not raw:
            return

        adapters = list(self._adapters) or [lambda x: x]
        if self.logarithmic:
            for fun in not_zero, positive:
                if fun in adapters:
                    adapters.remove(fun)
            adapters = adapters + [positive, not_zero]
        adapters = adapters + [decimal_to_float]

        self._adapt = reduce(compose, adapters) if not self.strict else ident
        self._x_adapt = reduce(
            compose, self._x_adapters
        ) if not self.strict and getattr(self, '_x_adapters', None) else ident

        series = []

        raw = [(
            list(raw_values) if not isinstance(raw_values, dict) else
            raw_values, serie_config_kwargs
        ) for raw_values, serie_config_kwargs in raw]

        width = max([len(values)
                     for values, _ in raw] + [len(self.x_labels or [])])

        for raw_values, serie_config_kwargs in raw:
            metadata = {}
            values = []
            if isinstance(raw_values, dict):
                if isinstance(self, BaseMap):
                    raw_values = list(raw_values.items())
                else:
                    value_list = [None] * width
                    for k, v in raw_values.items():
                        if k in (self.x_labels or []):
                            value_list[self.x_labels.index(k)] = v
                    raw_values = value_list

            for index, raw_value in enumerate(raw_values + (
                (width - len(raw_values)) * [None]  # aligning values
                    if len(raw_values) < width else [])):
                if isinstance(raw_value, dict):
                    raw_value = dict(raw_value)
                    value = raw_value.pop('value', None)
                    metadata[index] = raw_value
                else:
                    value = raw_value

                # Fix this by doing this in charts class methods
                if isinstance(self, Histogram):
                    if value is None:
                        value = (None, None, None)
                    elif not is_list_like(value):
                        value = (value, self.zero, self.zero)
                    elif len(value) == 2:
                        value = (1, value[0], value[1])
                    value = list(map(self._adapt, value))
                elif self._dual:
                    if value is None:
                        value = (None, None)
                    elif not is_list_like(value):
                        value = (value, self.zero)
                    if self._x_adapt:
                        value = (
                            self._x_adapt(value[0]), self._adapt(value[1])
                        )
                    if isinstance(self, BaseMap):
                        value = (self._adapt(value[0]), value[1])
                    else:
                        value = list(map(self._adapt, value))
                else:
                    value = self._adapt(value)

                values.append(value)
            serie_config = SerieConfig()
            serie_config(
                **dict((k, v) for k, v in self.state.__dict__.items()
                       if k in dir(serie_config))
            )
            serie_config(**serie_config_kwargs)
            series.append(
                Serie(offset + len(series), values, serie_config, metadata)
            )
        return series
1083096
def _aggregate(df, by):
    """"""
    by = [by] if isstr(by) else by
    cols = [c for c in list(df.columns) if c not in ['value'] + by]
    return df.groupby(cols).sum()['value']
987099
def make_label(id_, lineno):
    
    entry = SYMBOL_TABLE.declare_label(id_, lineno)
    if entry:
        gl.DATA_LABELS[id_] = gl.DATA_PTR_CURRENT  # This label points to the current DATA block index
    return entry
36589
def compute_metavar(kwargs):
    """"""
    metavar = kwargs.get('metavar')
    if not metavar:
      typ = kwargs.get('type', str)
      if typ == list:
        typ = kwargs.get('member_type', str)

      if typ == dict:
        metavar = '"{\'key1\':val1,\'key2\':val2,...}"'
      else:
        type_name = typ.__name__ if typ != newstr else 'str'  # TODO(#6071): drop special case once Py2 removed
        metavar = '<{}>'.format(type_name)

    return metavar