2004.05.02 wdn5e -- sort on selected fields
182621
private String logAndGetQueryText(FieldSearchQuery query,
                                      String[] resultFields) //2004.05.02 wdn5e
            throws SQLException, QueryParseException {
        StringBuffer queryText = new StringBuffer("SELECT");
        if (query.getType() == FieldSearchQuery.TERMS_TYPE) {
            queryText.append(" doFields.pid FROM doFields"
                    + getWhereClause(query.getTerms()));
        } else {
            StringBuffer resultFieldsString = new StringBuffer();
            if (resultFields.length > 0) {
                String delimiter = " ";
                for (String element : resultFields) {
                    String dbColumn = "doFields." + dcFixup(element);
                    resultFieldsString.append(delimiter + dbColumn);
                    delimiter = ", ";
                }
            }
            queryText.append(resultFieldsString);
            queryText.append(" FROM doFields");
            queryText.append(getWhereClause(query.getConditions()));
            // disabled sorting: see bug 78
            //            queryText.append(" ORDER BY");
            //            queryText.append(resultFieldsString);

        }
        String qt = queryText.toString();
        logger.debug(qt);
        return qt;
    }
1020335
def sort(self, request, reverse=False):
        """"""
        field = self.model._meta.fields.get(self.columns_sort)
        if not field:
            return self.collection

        if reverse:
            field = field.desc()

        return self.collection.order_by(field)
43071
def _apply_sort(cursor, sort_by, sort_direction):
        
        if sort_direction is not None and sort_direction.lower() == "desc":
            sort = pymongo.DESCENDING
        else:
            sort = pymongo.ASCENDING
        return cursor.sort(sort_by, sort)
1019202
public void addOrderBy(String fieldName, boolean sortAscending)
    {
        if (fieldName != null)
        {
            _getOrderby().add(new FieldHelper(fieldName, sortAscending));
        }
    }
533333
def _build_field_choices(self, fields):
        
        return tuple(sorted(
            [(fquery, capfirst(fname)) for fquery, fname in fields.items()],
            key=lambda f: f[1].lower())
        ) + self.FIELD_CHOICES
541006
def sortable_fields_for(model)
      if model.respond_to?(:sortable_fields)
        model.sortable_fields.map(&:to_sym)
      elsif model.respond_to?(:column_names)
        model.column_names.map(&:to_sym)
      else
        []
      end
    end
1310167
function orderAndSort(sortConf) {
    return {
        sortFieldName: sortConf.sortBy,
        sortDesc: sortConf.sortAsc === undefined ? false : !sortConf.sortAsc
    };
}
696847
def orderBy(self, field, direct="desc"):
        
        if direct == "desc":
            self._query = self._query.order_by(r.desc(field))
        else:
            self._query = self._query.order_by(r.asc(field))

        return self
78010
void selectFieldFacet(String field, String value) {

        m_selectedFieldFacets.clear();
        m_selectedRangeFacets.clear();
        m_selectedFieldFacets.put(field, Collections.singletonList(value));
        m_manager.search(m_selectedFieldFacets, m_selectedRangeFacets);
    }
860458
function(fieldName, toggleDirection) {
                var direction = toggleDirection ? 0 - this.state.order : this.state.order;
                if (fieldName !== this.state.sortKey || toggleDirection) {
                    this.setSorting(fieldName, direction);
                    this.isStale = true;
                }
            }
586182
private function setOrderByFieldIndices()
    {
        $keyParts = $this->explodeKey($this->key);

        foreach ($this->orderBys as $field => $order) {
            $needle = $this->fieldWrapper[0] . $field . $this->fieldWrapper[1];
            $this->orderByFieldIndices[array_search($needle, $keyParts)] = $order;
        }
    }
947845
public function Sort() {
      $this->Permission('Garden.Settings.Manage');
      
      $Session = Gdn::Session();
      $TransientKey = GetPostValue('TransientKey', '');
      $Target = GetPostValue('Target', '');
      if ($Session->ValidateTransientKey($TransientKey)) {
         $TableID = GetPostValue('TableID', FALSE);
         if ($TableID) {
            $Rows = GetPostValue($TableID, FALSE);
            if (is_array($Rows)) {
               try {
                  $Table = str_replace('Table', '', $TableID);
                  $TableModel = new Gdn_Model($Table);
                  foreach ($Rows as $Sort => $ID) {
                     $TableModel->Update(array('Sort' => $Sort), array($Table.'ID' => $ID));
                  }
               } catch (Exception $ex) {
                  $this->Form->AddError($ex->getMessage());
               }
            }
         }
      }
      if ($this->DeliveryType() != DELIVERY_TYPE_BOOL)
         Redirect($Target);
         
      $this->Render();
   }
1311916
def sort_field(self, field_name, direction, field_vals=None):
        
        field_name = self._normalize_field_name(field_name)
        if direction > 0:
            direction = 1
        elif direction < 0:
            direction = -1
        else:
            raise ValueError("direction {} is undefined".format(direction))

        self.fields_sort.append(field_name, [direction, field_name, list(field_vals) if field_vals else field_vals])
        return self
446927
def on_lstFields_itemSelectionChanged(self):
        
        self.clear_further_steps()
        field_names = self.selected_fields()
        layer_purpose = self.parent.step_kw_purpose.selected_purpose()
        # Exit if no selection
        if not field_names:
            self.parent.pbnNext.setEnabled(False)
            self.lblDescribeField.setText('')
            return
        # Compulsory fields can be list of field name or single field name.
        # We need to iterate through all of them
        if not isinstance(field_names, list):
            field_names = [field_names]
        field_descriptions = ''
        feature_count = self.parent.layer.featureCount()
        for field_name in field_names:
            layer_fields = self.parent.layer.fields()
            field_index = layer_fields.indexFromName(field_name)
            # Exit if the selected field_names comes from a previous wizard run
            if field_index < 0:
                return

            # Generate description for the field.
            field_type = layer_fields.field(field_name).typeName()
            field_index = layer_fields.indexFromName(field_name)
            unique_values = self.parent.layer.uniqueValues(field_index)
            unique_values_str = [
                i is not None and str(i) or 'NULL'
                for i in list(unique_values)[0:48]]
            unique_values_str = ', '.join(unique_values_str)
            field_descriptions += tr('<b>Field name</b>: {field_name}').format(
                field_name=field_name)
            field_descriptions += tr(
                '<br><b>Field type</b>: {field_type}').format(
                field_type=field_type)
            if (feature_count != -1 and (
                    layer_purpose == layer_purpose_aggregation)):
                if len(unique_values) == feature_count:
                    unique = tr('Yes')
                else:
                    unique = tr('No')
                field_descriptions += tr(
                    '<br><b>Unique</b>: {unique} ({unique_values_count} '
                    'unique values from {feature_count} features)'.format(
                        unique=unique,
                        unique_values_count=len(unique_values),
                        feature_count=feature_count))
            field_descriptions += tr(
                '<br><b>Unique values</b>: {unique_values_str}<br><br>'
            ).format(unique_values_str=unique_values_str)

        self.lblDescribeField.setText(field_descriptions)

        self.parent.pbnNext.setEnabled(True)
1221330
function(field,sortType){
			if(this.gridComp.options.showTree){
				this.treeSortRows(field,sortType);
			}else{
				this.basicSortRows(field,sortType);
			}
			this.gridComp.eidtRowIndex = -1;
		}
1352925
def _get_order_by(order, orderby, order_by_fields):
    
    try:
        # Find the actual database fieldnames for the keyword.
        db_fieldnames = order_by_fields[orderby]
    except KeyError:
        raise ValueError("Invalid value for 'orderby': '{0}', supported values are: {1}".format(orderby, ', '.join(sorted(order_by_fields.keys()))))

    # Default to descending for some fields, otherwise be ascending
    is_desc = (not order and orderby in ORDER_BY_DESC) \
        or (order or 'asc').lower() in ('desc', 'descending')

    if is_desc:
        return map(lambda name: '-' + name, db_fieldnames)
    else:
        return db_fieldnames
1287669
def es_field_sort(fld_name):
    
    parts = fld_name.split(".")
    if "_" not in parts[-1]:
        parts[-1] = "_" + parts[-1]
    return ".".join(parts)