Ensure columns appear in the same order for every row in table

    :param fields:
    :param unordered_row:
181277
def order_columns_in_row(fields, unordered_row):
    
    fields_idx = {f: pos for pos, f in enumerate(fields)}
    return OrderedDict(sorted(unordered_row.items(),
                              key=lambda i: fields_idx[i[0]]))
932949
@Override
    public void orderRows(final OrderBy ob) {
        if (ob != null) {
            ob.setMetaData(getMetaData());
            ob.setParser(parser);
            Collections.sort(rows, ob);
            goTop();
        }
    }
530790
def _get_normalized_columns(cls, list_):
        
        ret = []
        for row in list_:
            if len(row.keys()) > len(ret):
                ret = cls._ordered_keys(row)

        for row in list_:
            for key in row.keys():
                if key not in ret:
                    ret.append(key)
                    if not isinstance(row, OrderedDict):
                        ret.sort()
        return ret
681965
def __update(self, row):
        
        expr = self.__table.update().values(row)
        for key in self.__update_keys:
            expr = expr.where(getattr(self.__table.c, key) == row[key])
        if self.__autoincrement:
            expr = expr.returning(getattr(self.__table.c, self.__autoincrement))
        res = expr.execute()
        if res.rowcount > 0:
            if self.__autoincrement:
                first = next(iter(res))
                last_row_id = first[0]
                return last_row_id
            return 0
        return None
1368224
def join(keys, tables):
    """"""

    # Make new (merged) Table fields
    fields = OrderedDict()
    for table in tables:
        fields.update(table.fields)
    # TODO: may raise an error if a same field is different in some tables

    # Check if all keys are inside merged Table's fields
    fields_keys = set(fields.keys())
    for key in keys:
        if key not in fields_keys:
            raise ValueError('Invalid key: "{}"'.format(key))

    # Group rows by key, without missing ordering
    none_fields = lambda: OrderedDict({field: None for field in fields.keys()})
    data = OrderedDict()
    for table in tables:
        for row in table:
            row_key = tuple([getattr(row, key) for key in keys])
            if row_key not in data:
                data[row_key] = none_fields()
            data[row_key].update(row._asdict())

    merged = Table(fields=fields)
    merged.extend(data.values())
    return merged
418101
def order_by(self, field, orientation='ASC'):
        
        if isinstance(field, list):
            self.raw_order_by.append(field)
        else:
            self.raw_order_by.append([field, orientation])

        return self
664430
def sort(self, column_name=None, reverse=False):
        
        if not column_name and self.options.has_key('sorted_by'):
            column_name = self.options['sorted_by'].keys()[0]
        if column_name not in self.default_columns:
            raise ValueError("%s isn't a column in this table" % column_name)
        index = self.default_columns.index(column_name)
        self.table.sort(key = lambda row: row[index], reverse=reverse)
        self.options['sorted_by'] = {column_name: {'reverse': reverse}}
941997
function(columns, desc) {
    var self = this.chain()

    if (columns) {
      if (typeof desc === 'boolean') {
        if (!Array.isArray(columns)) columns = [columns]
      } else {
        columns = [].concat.apply(
          [],
          this.definition.store.utils.args(arguments)
        )
        desc = false
      }

      for (var i in columns) {
        self.addInternal('order', {
          column: self.store.toInternalAttributeName(columns[i]),
          order: desc ? 'DESC' : 'ASC'
        })
      }
    } else {
      self.clearInternal('order')
    }

    return self
  }
1341506
def fmt_row(self, columns, dimensions, row, **settings):
        
        cells = []
        i = 0
        for column in columns:
            cells.append(self.fmt_cell(
                    row[i],
                    dimensions[i],
                    column,
                    **settings[self.SETTING_TEXT_FORMATING]
                )
            )
            i += 1
        return self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]) + \
               self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING]).join(cells) + \
               self.bchar('v', 'm', settings[self.SETTING_BORDER_STYLE], **settings[self.SETTING_BORDER_FORMATING])
36357
def _stringify_row(self, row_index):
        '''
        
        '''
        table_row = self.table[row_index]
        prior_cell = None
        for column_index in range(self.start[1], self.end[1]):
            cell, changed = self._check_interpret_cell(table_row[column_index], prior_cell, row_index, column_index)
            if changed:
                table_row[column_index] = cell
            prior_cell = cell
318974
def update_row(self, ind, row_data):
        
        if sorted(row_data.keys()) != sorted(self.df.columns):
            # add any new column names
            for key in row_data:
                if key not in self.df.columns:
                    self.df[key] = None
            # add missing column names into row_data
            for col_label in self.df.columns:
                if col_label not in list(row_data.keys()):
                    row_data[col_label] = None
        try:
            self.df.iloc[ind] = pd.Series(row_data)
        except IndexError:
            return False
        return self.df
693022
def display_rows(self,
                     rows,
                     labels,
                     indent):

        ''''''

        out = []

        if not rows:
            return out

        first_row_type = type(rows[0])
        # all rows must have the same datatype
        consistent = True
        for row in rows[1:]:
            if type(row) != first_row_type:
                consistent = False

        if not consistent:
            return out

        if isinstance(labels, dict):
            labels_temp = []
            for key in sorted(labels):
                labels_temp.append(labels[key])
            labels = labels_temp

        if first_row_type is dict:  # and all the others
            temp_rows = []
            if not labels:
                labels = [six.text_type(label).replace('_', ' ').title() for label in sorted(rows[0])]
            for row in rows:
                temp_row = []
                for key in sorted(row):
                    temp_row.append(six.text_type(row[key]))
                temp_rows.append(temp_row)
            rows = temp_rows
        elif isinstance(rows[0], six.string_types):
            rows = [[row] for row in rows]  # encapsulate each row in a single-element list

        labels_and_rows = [labels] + rows if labels else rows
        has_header = self.has_header and labels

        return self.prepare_rows(labels_and_rows, indent + 4, has_header)
1197807
def order fields
      by_num = { 1 => 'asc', -1 => 'desc' }
      ordering = []
      fields.each_pair do |key, value|
        ordering << [key.to_s, by_num[value] || value]
      end
      @ordering = ordering
      self
    end
912335
private function ensureOrderColumnExists()
    {
        $attributes = $this
            ->connection
            ->createQueryBuilder()
            ->select('metamodel.tableName', 'attribute.colname')
            ->from('tl_metamodel_attribute', 'attribute')
            ->leftJoin('attribute', 'tl_metamodel', 'metamodel', 'metamodel.id=attribute.pid')
            ->where('attribute.type=:type')
            ->setParameter('type', 'file')
            ->andWhere('attribute.file_multiple=:multiple')
            ->setParameter('multiple', '1')
            ->execute();

        while ($row = $attributes->fetch(\PDO::FETCH_OBJ)) {
            if ($this->fieldExists($row->colname . '__sort', $row->tableName)) {
                continue;
            }
            $this
                ->connection
                ->exec(
                    \sprintf(
                        'ALTER TABLE %1$s ADD COLUMN %2$s__sort %3$s',
                        $row->tableName,
                        $row->colname,
                        'blob NULL'
                    )
                );
        }
    }
690093
function(fields, visible) {
        if (!$.isArray(fields)) {
            fields = [fields];
        }
        var self = this;
        $.each(fields, function(index, field) {
            $.each(self.options.column, function(i, col) {
                if (col.field === field) {
                    col.visible = visible;
                }
            });
        });
        this.refresh();
    }
607296
def adapt_table_row!(parsed_table_row, gathered_comments)
      # Saving off the original data
      parsed_table_row['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_table_row))

      # Removing parsed data for child elements in order to avoid duplicating data which the child elements will themselves include
      parsed_table_row['cuke_modeler_parsing_data']['cells'] = nil

      if parsed_table_row['comments']
        parsed_table_row['cuke_modeler_parsing_data']['comments'] = nil
        gathered_comments.concat(parsed_table_row['comments'])
      end

      parsed_table_row['cells'].collect! do |cell|
        create_cell_for(cell, parsed_table_row['line'])
      end
    end
389866
def fmt_row_header(self, columns, dimensions, **settings):
        
        row = list(map(lambda x: x['label'], columns))
        return self.fmt_row(columns, dimensions, row, **settings)