more natural concise text representation
 If a block is passed, it is used to format the numeric magnitudes (Float numbers) (e.g., for localization)
   Units.units{3*m/(2*s)}.abr{|v| v.to_s.tr('.',',') } # => "1,5 m/s"
978528
def abr
      txt = self.to_s.gsub('**','^').tr('*',' ')
      if block_given?
        txt.gsub!(/[+-]?((\d+_?)*\d+(\.(\d+_?)*\d+)?|\.(\d+_?)*\d+)([eE][+-]?(\d+_?)*\d+)?/) do
          v = $&.to_f
          yield v
        end
      end
      txt
    end
216971
def strsize (b, grouping=True):
    """"""
    if b < 0:
        raise ValueError("Invalid negative byte number")
    if b < 1024:
        return u"%sB" % locale.format("%d", b, grouping)
    if b < 1024 * 10:
        return u"%sKB" % locale.format("%d", (b // 1024), grouping)
    if b < 1024 * 1024:
        return u"%sKB" % locale.format("%.2f", (float(b) / 1024), grouping)
    if b < 1024 * 1024 * 10:
        return u"%sMB" % locale.format("%.2f", (float(b) / (1024*1024)), grouping)
    if b < 1024 * 1024 * 1024:
        return u"%sMB" % locale.format("%.1f", (float(b) / (1024*1024)), grouping)
    if b < 1024 * 1024 * 1024 * 10:
        return u"%sGB" % locale.format("%.2f", (float(b) / (1024*1024*1024)), grouping)
    return u"%sGB" % locale.format("%.1f", (float(b) / (1024*1024*1024)), grouping)
617583
def str_numerator(self):
        """"""
        if not self.undefined:
            return None
        unit_numerator, unit = self._unit_class(self.numerator).auto
        formatter = '%d' if unit_numerator == self.numerator else '%0.2f'
        numerator = locale.format(formatter, unit_numerator, grouping=True)
        return '{0} {1}'.format(numerator, unit)
163718
function _encode(value, top) {

        // Numbers
        if (typeof value === 'number') {

            var type = value !== (value | 0) ? 1 : 0,
                sign = 0;

            if (value < 0) {
                value = -value;
                sign = 1;
            }

            write(1 + type, 3);

            // Float
            if (type) {

                var shift = 0,
                    step = 10,
                    m = value,
                    tmp = 0;

                // Figure out the exponent
                do {
                    m = value * step;
                    step *= 10;
                    shift++;
                    tmp = m | 0;

                } while(m - tmp > 1 / step && shift < 8 && m < 214748364);

                // Correct if we overshoot
                step = tmp / 10;
                if (step === (step | 0)) {
                    tmp = step;
                    shift--;
                }

                value = tmp;

            }

            // 2 size 0-3: 0 = < 16 1 = < 256 2 = < 65536 3 >=
            if (value < 2) {
                write(value, 4);

            } else if (value < 16) {
                write(1, 3);
                write(value, 4);

            } else if (value < 256) {
                write(2, 3);
                write(value, 8);

            } else if (value < 4096) {
                write(3, 3);
                write(value >> 8 & 0xff, 4);
                write(value & 0xff, 8);

            } else if (value < 65536) {
                write(4, 3);
                write(value >> 8 & 0xff, 8);
                write(value & 0xff, 8);

            } else if (value < 1048576) {
                write(5, 3);
                write(value >> 16 & 0xff, 4);
                write(value >> 8 & 0xff, 8);
                write(value & 0xff, 8);

            } else if (value < 16777216) {
                write(6, 3);
                write(value >> 16 & 0xff, 8);
                write(value >> 8 & 0xff, 8);
                write(value & 0xff, 8);

            } else {
                write(7, 3);
                write(value >> 24 & 0xff, 8);
                write(value >> 16 & 0xff, 8);
                write(value >> 8 & 0xff, 8);
                write(value & 0xff, 8);
            }

            write(sign, 1);

            if (type) {
                write(shift, 4);
            }

        // Strings
        } else if (typeof value === 'string') {

            var len = value.length;
            write(3, 3);

            if (len > 65535) {
                write(31, 5);
                write(len >> 24 & 0xff, 8);
                write(len >> 16 & 0xff, 8);
                write(len >> 8 & 0xff, 8);
                write(len & 0xff, 8);

            } else if (len > 255) {
                write(30, 5);
                write(len >> 8 & 0xff, 8);
                write(len & 0xff, 8);

            } else if (len > 28) {
                write(29, 5);
                write(len, 8);

            } else {
                write(len, 5);
            }

            // Write a raw string to the stream
            if (bitsLeft !== 8) {
                bitStream += chrTable[bitValue];
                bitValue = 0;
                bitsLeft = 8;
            }

            bitStream += value;

        // Booleans
        } else if (typeof value === 'boolean') {
            write(+value, 4);

        // Null
        } else if (value === null) {
            write(7, 3);
            write(0, 1);

        // Arrays
        } else if (value instanceof Array) {

            write(4, 3);
            for(var i = 0, l = value.length; i < l; i++) {
                _encode(value[i]);
            }

            if (!top) {
                write(6, 3);
            }

        // Object
        } else {

            write(5, 3);
            for(var e in value) {
                _encode(e);
                _encode(value[e]);
            }

            if (!top) {
                write(6, 3);
            }

        }

    }
1041137
def represent_float_as_str(value):
    """"""
    # In Python 2, calling str() on a float object loses precision:
    #
    # In [1]: 1.23456789012345678
    # Out[1]: 1.2345678901234567
    #
    # In [2]: 1.2345678901234567
    # Out[2]: 1.2345678901234567
    #
    # In [3]: str(1.2345678901234567)
    # Out[3]: '1.23456789012'
    #
    # The best way to ensure precision is not lost is to convert to string via Decimal:
    # https://github.com/mogui/pyorient/pull/226/files
    if not isinstance(value, float):
        raise GraphQLInvalidArgumentError(u'Attempting to represent a non-float as a float: '
                                          u'{}'.format(value))

    with decimal.localcontext() as ctx:
        ctx.prec = 20  # floats are max 80-bits wide = 20 significant digits
        return u'{:f}'.format(decimal.Decimal(value))
1107244
function byteSizeFormat(num, base, toFixed, noSpace) {
  if (typeof num !== 'number') {
    throw new TypeError('Expected a number');
  }

  var neg = num < 0 ? '-' : '';

  if (neg) {
    num = -num; // short Math.abs
  }
  if (num < 1) {
    return neg + num + ' B';
  }
  if (typeof base !== 'number' || base < 0) {
    base = 1024;
  }
  if (typeof num !== 'number' || toFixed < 0) {
    toFixed = 2;
  }

  var exponent = Math.min(Math.floor(Math.log(num) / Math.log(base)), units.length - 1);

  num = (num / Math.pow(base, exponent)).toFixed(toFixed);
  return neg + num + (noSpace ? '' : ' ') + units[exponent];
}
399193
def format_bytes(bytes):
    
    if bytes is None:
        return 'N/A'
    if type(bytes) is str:
        bytes = float(bytes)
    if bytes == 0.0:
        exponent = 0
    else:
        exponent = int(math.log(bytes, 1024.0))
    suffix = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'][exponent]
    converted = float(bytes) / float(1024 ** exponent)
    return '{0:.2f}{1}'.format(converted, suffix)
142428
def format_float(x, max_width):
    '''
    '''
    # width of (whole part + 1 (to avoid zero)) + 1 because int floors, not ceils
    whole_width = int(math.log10(abs(x) + 1)) + 1
    # for +/- sign
    sign_width = 1 if x < 0 else 0
    # for . if we show it
    decimal_point_width = 1 if max_width >= whole_width else 0
    return '%.*f' % (max_width - whole_width - sign_width - decimal_point_width, x)
142363
def numeric_summary
      summary = "\n  median: #{median}" +
                "\n  mean: %0.4f" % mean
      if sd
        summary << "\n  std.dev.: %0.4f" % sd +
                   "\n  std.err.: %0.4f" % se
      end

      if count_values(*Daru::MISSING_VALUES).zero?
        summary << "\n  skew: %0.4f" % skew +
                   "\n  kurtosis: %0.4f" % kurtosis
      end
      summary
    end
1119042
def _latex_float(f, format=".3g"):
    
    float_str = "{{0:{0}}}".format(format).format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        return r"{0}\times 10^{{{1}}}".format(base, int(exponent))
    else:
        return float_str
583728
function makeFormatter(aFragments) {
		var fnFormatter = function() {
				var aResult = [],
					l = aFragments.length,
					i;

				for (i = 0; i < l; i++) {
					if ( typeof aFragments[i] === "number" ) {
						// a numerical fragment references the part with the same number
						aResult.push(arguments[aFragments[i]]);
					} else {
						// anything else is a string fragment
						aResult.push(aFragments[i]);
					}
				}
				return aResult.join('');
			};
		fnFormatter.textFragments = aFragments;
		return fnFormatter;
	}
387598
def get(self, get_params, block):
        
        value = "{%s}" % self.key
        try:
            value = value_ = get_params(self.key)
            if self.format.startswith(":"):
                # if a parameter has been set to be formatted as a numeric
                # type then we see if we can coerce it to be.  This allows
                # the user to format types that normally would not be
                # allowed eg '123' it also allows {:d} to be used as a
                # shorthand for {:.0f}.  Use {:g} to remove insignificant
                # trailing zeroes and the decimal point too if there are
                # no remaining digits following it.  If the parameter cannot
                # be successfully converted then the format will be removed.
                try:
                    if "ceil" in self.format:
                        value = int(ceil(float(value)))
                    if "f" in self.format:
                        value = float(value)
                    if "g" in self.format:
                        value = float(value)
                    if "d" in self.format:
                        value = int(float(value))
                    output = u"{[%s]%s}" % (self.key, self.format)
                    value = output.format({self.key: value})
                    value_ = float(value)
                except ValueError:
                    pass
            elif self.format.startswith("!"):
                output = u"{%s%s}" % (self.key, self.format)
                value = value_ = output.format(**{self.key: value})

            if block.commands.not_zero:
                valid = value_ not in ["", None, False, "0", "0.0", 0, 0.0]
            else:
                # '', None, and False are ignored
                # numbers like 0 and 0.0 are not.
                valid = not (value_ in ["", None] or value_ is False)
            enough = False
        except:  # noqa e722
            # Exception raised when we don't have the param
            enough = True
            valid = False

        return valid, value, enough
835321
def format(target)
      begin
        number = number_with_precision(target, @precision)
        parts = number.split('.')
        if parts.at(1).nil?
          parts[0] + "%"
        else
          parts[0] + @separator + parts[1].to_s + "%"
        end
      rescue
        target
      end
    end
528812
def indent_block(amount, text, indent_char='\t'):
    
    rst = ""
    for line in text.splitlines():
        if amount > 0:
            rst += indent_char*amount + line + "\n"
        else:
            rst += ''.join([c for i,c in enumerate(line) if (c == indent_char and (i+1) > abs(amount)) or (not c == indent_char)]) + "\n"
    return rst
92417
def _format_value_error(self, v, e, pm=" +/- "):
        
        # If we have weird stuff
        if not _s.fun.is_a_number(v) or not _s.fun.is_a_number(e) \
            or v in [_n.inf, _n.nan, _n.NAN] or e in [_n.inf, _n.nan, _n.NAN]: 
            return str(v)+pm+str(e)
        
        # Normal values.
        try:
            sig_figs = -int(_n.floor(_n.log10(abs(e))))+1            
            return str(_n.round(v, sig_figs)) + pm + str(_n.round(e, sig_figs))

        except:
            return str(v)+pm+str(e)
26155
function (hashrate) {
    if (hashrate <= 0 || _.isNaN(hashrate)) {
      return 'N/A';
    }
    if (hashrate < 1e3) {
      return hashrate.toFixed(2) + 'MH/s';
    }
    if (hashrate < 1e6) {
      return (hashrate / 1e3).toFixed(2) + 'GH/s';
    }
    if (hashrate < 1e9) {
      return (hashrate / 1e6).toFixed(2) + 'TH/s';
    }

    return (hashrate / 1e9).toFixed(2) + 'PH/s';
  }
1333396
def _float(value):
    
    if "[" in value:
        # There is a unit field
        value, sep, unit = value.partition("[")
        unit = sep + unit

        # As defined in the CCSDS Orbital Data Message Blue Book, the unit should
        # be the same as defined in table 3-3 which are for km and km/s for position and
        # velocity respectively. Thus, there should be no other conversion to make
        if unit in ("[km]", "[km/s]"):
            multiplier = 1000
        elif unit == "[s]":
            multiplier = 1
        else:
            raise ValueError("Unknown unit for this field", unit)
    else:
        # if no unit is provided, the default is km, and km/s
        multiplier = 1000

    return float(value) * multiplier