group the data for report
771892
async function prepareDataSource() {
    const orders = await fetchOrders()
    const ordersByShipCountry = orders.reduce((a, v) => {
        a[v.ShipCountry] = a[v.ShipCountry] || []
        a[v.ShipCountry].push(v)
        return a
    }, {})

    return Object.keys(ordersByShipCountry).map((country) => {
        const ordersInCountry = ordersByShipCountry[country]

        const accumulated = {}

        ordersInCountry.forEach((o) => {
            o.OrderDate = new Date(o.OrderDate);
            const key = o.OrderDate.getFullYear() + '/' + (o.OrderDate.getMonth() + 1);
            accumulated[key] = accumulated[key] || {
                value: 0,
                orderDate: o.OrderDate
            };
            accumulated[key].value++;
        });

        return {
            rows: ordersInCountry,
            country,
            accumulated
        }

    }).slice(0, 2)
}
960635
def group_items(items, opts = {})
      default_opts          = {:group_size => 10, :header => proc { |c| c.to_s[0, 1].upcase }}
      opts                  = default_opts.merge(opts)
      group_size            = opts[:group_size]
      header                = opts[:header]

      items                 = items.sort_by &header
      items_group_by_header = items.group_by &header

      items_by_headers      = []
      merge_headers         = []
      merge_items           = []

      items_group_by_header.sort.each do |header, items|
        merge_headers << header
        merge_items.concat items
        if merge_items.length >= group_size
          items_by_headers << [merge_headers, merge_items]
          merge_headers = []
          merge_items   = []
        end
      end

      if merge_items.length > 0
        items_by_headers << [merge_headers, merge_items]
      end
      items_by_headers
    end
243074
function(groupName, totalSites, totalPages,
                                totalPageviews) {
            var format = d3.format(',d');
            // build
            var summary = 
              '<tr>' +
              '<td>' + groupName + '</td>' +
              '<td>' + format(totalPageviews) + '</td>' +
              '<td>' + format(totalPages) + '</td>' +
              //'<td>' + totalSites + '</td>' +
              '</tr>';

            return summary;
        }
260293
def groupby(self, by=None, **kwargs):
        
        if by is None:
            by = self.plydata_groups

        # Turn off sorting by groups messes with some verbs
        if 'sort' not in kwargs:
            kwargs['sort'] = False

        return super().groupby(by, **kwargs)
550894
def tabulate(collection, headers, datetime_fmt='%Y-%m-%d %H:%M:%S', **kwargs):
    """"""
    if isinstance(headers, dict):
        attrs = headers.keys()
        # if mapping is not specified keep original
        names = [
            key if value is None else value for key, value in headers.items()
        ]
    else:
        attrs = names = headers
    table = [(
        format_cell(cell, datetime_fmt=datetime_fmt)
        for cell in attrgetter(*attrs)(c)
    ) for c in collection]
    return tblte(table, headers=[h.upper() for h in names], **kwargs)
956964
def get_flat_groups(self, field=None):
        '''
        
        '''
        field = field if field else self._determine_group_field(field)
        temp_groups = self.data['grouped'][field]['groups']
        return [y for x in temp_groups for y in x['doclist']['docs']]
1165555
def groupBy(self, val):
        

        def by(result, key, value):
            if key not in result:
                result[key] = []
            result[key].append(value)

        res = self._group(self.obj, val, by)

        return self._wrap(res)
560796
def build_grouping_body
      arr = []
      data.each do |_,group|                     
        arr << render_group(group, options)
      end
      output << arr.join(",\n")
    end
1350670
function groupBy(item) {
    if (item instanceof Raw) {
      return this.groupByRaw.apply(this, arguments);
    }
    this._statements.push({
      grouping: 'group',
      type: 'groupByBasic',
      value: normalizeArr.apply(null, arguments)
    });
    return this;
  }
535628
function grouped(array, groups, order) {
  if (!groups) { groups = [returnFalse]; }
  var sorted = [];
  var ordered = [];
  var remaining = array.slice();
  var unmatchedPosition = groups.indexOf('unmatched');
  groups.forEach(function(criteria, index) {
    if (index === unmatchedPosition) { return; }
    var tieBreakers = [];
    if (index !== groups.length - 1) {
      tieBreakers = groups.slice(index + 1);
      if (index < unmatchedPosition) {
        tieBreakers.splice(unmatchedPosition - index - 1, 1);
      }
    }
    var spliced = splice(remaining, criteria, tieBreakers);
    var matched = spliced.matched;
    var unmatched = spliced.unmatched;
    sorted[index] = matched;
    remaining = unmatched;
  });
  if (unmatchedPosition === -1) { unmatchedPosition = sorted.length; }
  sorted[unmatchedPosition] = remaining;
  if (Array.isArray(order)) {
    order.forEach(function(position, index) {
      ordered[index] = sorted[position];
    });
  } else {
    ordered = sorted;
  }
  return ordered.reduce(function(flat, group) {
    return flat.concat(group);
  }, []);
}
1267516
def _group(tlist, cls, match,
           valid_prev=lambda t: True,
           valid_next=lambda t: True,
           post=None,
           extend=True,
           recurse=True
           ):
    """"""

    tidx_offset = 0
    pidx, prev_ = None, None
    for idx, token in enumerate(list(tlist)):
        tidx = idx - tidx_offset

        if token.is_whitespace:
            continue

        if recurse and token.is_group and not isinstance(token, cls):
            _group(token, cls, match, valid_prev, valid_next, post, extend)

        if match(token):
            nidx, next_ = tlist.token_next(tidx)
            if prev_ and valid_prev(prev_) and valid_next(next_):
                from_idx, to_idx = post(tlist, pidx, tidx, nidx)
                grp = tlist.group_tokens(cls, from_idx, to_idx, extend=extend)

                tidx_offset += to_idx - from_idx
                pidx, prev_ = from_idx, grp
                continue

        pidx, prev_ = tidx, token
1034831
function groupBy(collection, iteratee) {
    return collection.reduce(function (records, record) {
        var key = iteratee(record);
        if (records[key] === undefined) {
            records[key] = [];
        }
        records[key].push(record);
        return records;
    }, {});
}
1285481
def aggregate(self):
        
        for report in self.reportset:
            printtime('Processing {}'.format(report.split('.')[0]), self.start)
            # Initialise the header for each report - MLST is different, as the header is different for each
            # MLST scheme. This provides a generic header instead
            header = '' if report != 'mlst.csv' else 'Strain,Genus,SequenceType,Matches,1,2,3,4,5,6,7\n'
            # Initialise a string to hold the data for each report
            data = ''
            # Open the aggregated report
            with open(os.path.join(self.reportpath, report), 'w') as aggregate:
                for sample in self.runmetadata.samples:
                    # Try to open the report for this run
                    try:
                        #
                        with open(os.path.join(sample.general.reportpath, report), 'r') as runreport:
                            # Only get the header from the first file
                            if not header:
                                header = runreport.readline()
                            else:
                                for row in runreport:
                                    # The final entry in a report does not have a newline character. Add \n as required
                                    if not row.endswith('\n'):
                                        row += '\n'
                                    # For certain reports, the header row is printed above each strain - ignore multiple
                                    # instances of the header
                                    if row.split(',')[0] != header.split(',')[0]:
                                        # Add the row to the string of data
                                        data += row
                    except IOError:
                        pass
                # Write the strings to the aggregate report file
                aggregate.write(header)
                aggregate.write(data)
1050139
def group(self):
        """"""
        yield self.current
        # start enumerate at 1 because we already yielded the last saved item
        for num, item in enumerate(self.iterator, 1):
            self.current = item
            if num == self.limit:
                break
            yield item
        else:
            self.on_going = False
229911
def totals(report, total_roles, role_name_length):
    
    roles_len_string = len(str(total_roles))
    roles_label_len = 6  # "r" "o" "l" "e" "s" " "

    if clr.has_colors:
        roles_count_offset = 22
    else:
        roles_count_offset = 13

    roles_count_offset += role_name_length

    # no idea honestly but it fixes the formatting
    # it will probably break the formatting if you have 100+ roles
    if roles_len_string > 1:
        roles_count_offset -= 2

    pad_roles_by = roles_count_offset + roles_len_string + roles_label_len

    roles = field_value(total_roles, "roles", "normal", 0)
    defaults = field_value(report["defaults"], "defaults", "blue", 16)
    facts = field_value(report["facts"], "facts", "purple", 16)
    files = field_value(report["files"], "files", "dark gray", 16)
    lines = field_value(report["lines"], "lines", "normal", 16)

    print "".join(clr.stringc("-", "black") * 79)
    print "{0} {2:>{1}} {3} {4} {5}".format(
        roles, pad_roles_by, defaults, facts, files, lines)
113777
protected void addSubreportsToGroups() {
        for (Integer groupNum : groupFooterSubreports.keySet()) {
            List<Subreport> list = groupFooterSubreports.get(groupNum);
            DJGroup group = report.getColumnsGroups().get(groupNum - 1);
            group.getFooterSubreports().addAll(list);
        }

        for (Integer groupNum : groupHeaderSubreports.keySet()) {
            List<Subreport> list = groupHeaderSubreports.get(groupNum);
            DJGroup group = report.getColumnsGroups().get(groupNum - 1);
            group.getHeaderSubreports().addAll(list);
        }

    }
883680
def _plt_gogrouped(self, goids, go2color_usr, **kws):
        """"""
        fout_img = self.get_outfile(kws['outfile'], goids)
        sections = read_sections(kws['sections'], exclude_ungrouped=True)
        # print ("KWWSSSSSSSS", kws)
        # kws_plt = {k:v for k, v in kws.items if k in self.kws_plt}
        grprobj_cur = self._get_grprobj(goids, sections)
        # GO: purple=hdr-only, green=hdr&usr, yellow=usr-only
        # BORDER: Black=hdr Blu=hdr&usr
        grpcolor = GrouperColors(grprobj_cur)  # get_bordercolor get_go2color_users
        grp_go2color = grpcolor.get_go2color_users()
        grp_go2bordercolor = grpcolor.get_bordercolor()
        for goid, color in go2color_usr.items():
            grp_go2color[goid] = color
        objcolor = Go2Color(self.gosubdag, objgoea=None,
                            go2color=grp_go2color, go2bordercolor=grp_go2bordercolor)
        go2txt = GrouperPlot.get_go2txt(grprobj_cur, grp_go2color, grp_go2bordercolor)
        objplt = GoSubDagPlot(self.gosubdag, Go2Color=objcolor, go2txt=go2txt, **kws)
        objplt.prt_goids(sys.stdout)
        objplt.plt_dag(fout_img)
        sys.stdout.write("{N:>6} sections read\n".format(
            N="NO" if sections is None else len(sections)))
        return fout_img