Returns a string representation of the quantity, using the unit symbol
167592
def to_s format=:symbol
      if format == :name
        unit_string = @value == 1 || @value == -1 ? @unit.name : @unit.pluralized_name 
      else
        unit_string = @unit.send format 
      end

      string =  "#{@value}"
      string += " #{unit_string}" unless unit_string.empty?

      string
    end
635279
def _asString(self, value):
        """"""
        if sys.version_info[0] == 3:
            if isinstance(value, str):
                return value
            elif isinstance(value, bytes):
                return value.decode('utf-8')
        elif sys.version_info[0] == 2:
            return value.encode('ascii')
1081898
def string(v):
    """"""
    if nodesetp(v):
        if not v:
            return u''
        return string_value(v[0])
    elif numberp(v):
        if v == float('inf'):
            return u'Infinity'
        elif v == float('-inf'):
            return u'-Infinity'
        elif str(v) == 'nan':
            return u'NaN'
        elif int(v) == v and v <= 0xffffffff:
            v = int(v)
        return unicode(v)
    elif booleanp(v):
        return u'true' if v else u'false'
    return v
927814
def label(self) -> str:
        """"""
        label = self.expression.replace("_", "\\;")
        if self.units_kind:
            symbol = wt_units.get_symbol(self.units)
            for v in self.variables:
                vl = "%s_{%s}" % (symbol, v.label)
                vl = vl.replace("_{}", "")  # label can be empty, no empty subscripts
                label = label.replace(v.natural_name, vl)
            units_dictionary = getattr(wt_units, self.units_kind)
            label += r"\,"
            label += r"\left("
            label += units_dictionary[self.units][2]
            label += r"\right)"
        label = r"$\mathsf{%s}$" % label
        return label
694886
function getBytesWithUnit(bytes) {
        if (isNaN(bytes)) {
            return;
        }
        var units = [ ' bytes', ' KB', ' MB', ' GB', ' TB', ' PB', ' EB', ' ZB', ' YB' ];
        var amountOf2s = Math.floor(Math.log(+bytes) / Math.log(2));
        if (amountOf2s < 1) {
            amountOf2s = 0;
        }
        var i = Math.floor(amountOf2s / 10);
        bytes = +bytes / Math.pow(2, 10 * i);


        if (bytes.toString().length > bytes.toFixed(2).toString().length) {
            bytes = bytes.toFixed(2);
        }
        return bytes + units[i];
    }
980221
def to_si(self, values, from_unit):
        """"""
        if from_unit in self.si_units:
            return values, from_unit
        elif from_unit == 'ton':
            return self.to_unit(values, 'tonne', from_unit), 'tonne'
        else:
            return self.to_unit(values, 'kg', from_unit), 'kg'
1261991
def from_string(cls, s):
        
        # Extract num and unit string.
        s = s.strip()
        for i, char in enumerate(s):
            if char.isalpha() or char.isspace():
                break
        else:
            raise Exception("Unit is missing in string %s" % s)
        num, unit = float(s[:i]), s[i:]

        # Find unit type (set it to None if it cannot be detected)
        for unit_type, d in BASE_UNITS.items():
            if unit in d:
                break
        else:
            unit_type = None

        return cls(num, unit, unit_type=unit_type)
19658
def bytes_to_string(num, suffix='B'):
    
    extensions = ["%s%s" % (x, suffix) for x in ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']]
    if num == 0:
        return "0%s" % extensions[0]
    else:
        n_bytes = float(abs(num))
        place = int(math.floor(math.log(n_bytes, 1024)))
        return "%.1f%s" % (np.sign(num) * (n_bytes / 1024** place), extensions[place])
210934
def val_mb(valstr: Union[int, str]) -> str:
    
    try:
        return "{:.3f}".format(int(valstr) / (1024 * 1024))
    except (TypeError, ValueError):
        return '?'
1361882
def _stringify_number(v):
    '''
    
    '''
    if isinstance(v, (float, Decimal)):
        if math.isinf(v) and v > 0:
            v = 'Infinity'
        elif math.isinf(v) and v < 0:
            v = '-Infinity'
        else:
            v = '{:f}'.format(v)
    elif isinstance(v, BinarySize):
        v = '{:d}'.format(int(v))
    elif isinstance(v, int):
        v = '{:d}'.format(v)
    else:
        v = str(v)
    return v
1369823
def to_si(self, values, from_unit):
        """"""
        if from_unit == 'W/m2-K':
            return values, from_unit
        else:
            return self.to_unit(values, 'W/m2-K', from_unit), 'W/m2-K'
839083
def format_sizeof(num, suffix='bytes'):
    ''''''
    for unit in ['','K','M','G','T','P','E','Z']:
        if abs(num) < 1000.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1000.0
    return "%.1f%s%s" % (num, 'Y', suffix)
198867
def build_quantity(orig_text, text, item, values, unit, surface, span, uncert):
    """"""
    # Discard irrelevant txt2float extractions, cardinal numbers, codes etc.
    if surface.lower() in ['a', 'an', 'one'] or \
            re.search(r'1st|2nd|3rd|[04-9]th', surface) or \
            re.search(r'\d+[A-Z]+\d+', surface) or \
            re.search(r'\ba second\b', surface, re.IGNORECASE):
        logging.debug(u'\tMeaningless quantity ("%s"), discard', surface)
        return

    # Usually "$3T" does not stand for "dollar tesla"
    elif unit.entity.dimensions and \
            unit.entity.dimensions[0]['base'] == 'currency':
        if len(unit.dimensions) > 1:
            try:
                suffix = re.findall(r'\d(K|M|B|T)\b(.*?)$', surface)[0]
                values = [i * r.SUFFIXES[suffix[0]] for i in values]
                unit = l.UNITS[unit.dimensions[0]['base']][0]
                if suffix[1]:
                    surface = surface[:surface.find(suffix[1])]
                    span = (span[0], span[1] - len(suffix[1]))
                logging.debug(u'\tCorrect for "$3T" pattern')
            except IndexError:
                pass
        else:
            try:
                suffix = re.findall(r'%s(K|M|B|T)\b' % re.escape(surface),
                                    orig_text)[0]
                surface += suffix
                span = (span[0], span[1] + 1)
                values = [i * r.SUFFIXES[suffix] for i in values]
                logging.debug(u'\tCorrect for "$3T" pattern')
            except IndexError:
                pass

    # Usually "1990s" stands for the decade, not the amount of seconds
    elif re.match(r'[1-2]\d\d0s', surface):
        unit = l.NAMES['dimensionless']
        surface = surface[:-1]
        span = (span[0], span[1] - 1)
        logging.debug(u'\tCorrect for decade pattern')

    # Usually "in" stands for the preposition, not inches
    elif unit.dimensions[-1]['base'] == 'inch' and \
            re.search(r' in$', surface) and '/' not in surface:
        if len(unit.dimensions) > 1:
            unit = get_unit_from_dimensions(unit.dimensions[:-1], orig_text)
        else:
            unit = l.NAMES['dimensionless']
        surface = surface[:-3]
        span = (span[0], span[1] - 3)
        logging.debug(u'\tCorrect for "in" pattern')

    elif is_quote_artifact(text, item.span()):
        if len(unit.dimensions) > 1:
            unit = get_unit_from_dimensions(unit.dimensions[:-1], orig_text)
        else:
            unit = l.NAMES['dimensionless']
        surface = surface[:-1]
        span = (span[0], span[1] - 1)
        logging.debug(u'\tCorrect for quotes')

    elif re.search(r' time$', surface) and len(unit.dimensions) > 1 and \
            unit.dimensions[-1]['base'] == 'count':
        unit = get_unit_from_dimensions(unit.dimensions[:-1], orig_text)
        surface = surface[:-5]
        span = (span[0], span[1] - 5)
        logging.debug(u'\tCorrect for "time"')

    objs = []
    for value in values:
        obj = c.Quantity(value=value,
                         unit=unit,
                         surface=surface,
                         span=span,
                         uncertainty=uncert)
        objs.append(obj)

    return objs
551790
def _si(number):
    """"""
    prefixes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']
    while number > 1024:
        number /= 1024.0
        prefixes.pop(0)
    return '%0.2f%s' % (number, prefixes.pop(0))
757250
def int_bytes(cls, string):
        ''''''
        if string[-1] in ('k', 'm'):
            value = cls.int_0_inf(string[:-1])
            unit = string[-1]
            if unit == 'k':
                value *= 2 ** 10
            else:
                value *= 2 ** 20
            return value
        else:
            return cls.int_0_inf(string)
1050356
def to_string_short(self):
        
        if hasattr(self, 'constrained_by') and len(self.constrained_by) > 0:
            return "* {:>30}: {}".format(self.uniquetwig_trunc, self.get_quantity() if hasattr(self, 'quantity') else self.get_value())
        else:
            return "{:>32}: {}".format(self.uniquetwig_trunc, self.get_quantity() if hasattr(self, 'quantity') else self.get_value())
1370367
def to_h(num, suffix='B'):
    """"""
    if num is None:  # Show None when data is missing
        return "None"
    for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)