Produce a TopNumber, with a length to match the given assignment
        class, based on an input hex string.

        This can be used to create TopNumbers from a hash of a string.
7112
def from_hex(cls, h, space, assignment_class='self'):
        

        from math import log

        # Use the ln(N)/ln(base) trick to find the right number of hext digits
        # to  use

        hex_digits = int(
            round(log(62 ** TopNumber.DLEN.DATASET_CLASSES[assignment_class]) / log(16), 0))

        i = int(h[:hex_digits], 16)

        return TopNumber(space, i, assignment_class=assignment_class)
807680
def string_from_number(number)
      if @style == :btc
        number = number.to_i
        return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}".gsub(/0+$/,"").gsub(/\.$/,".0")
      elsif @style == :btc_long
        number = number.to_i
        return "#{number / BTC::COIN}.#{'%08d' % [number % BTC::COIN]}"
      else
        # TODO: parse other styles
        raise "Not implemented"
      end
    end
291475
def make_slice_key(cls, start_string, size_string):
        
        try:
            start = int(start_string)
        except ValueError:
            raise ValueError('Query parameter "start" must be a number.')
        if start < 0:
            raise ValueError('Query parameter "start" must be zero or '
                             'a positive number.')
        try:
            size = int(size_string)
        except ValueError:
            raise ValueError('Query parameter "size" must be a number.')
        if size < 1:
            raise ValueError('Query parameter "size" must be a positive '
                             'number.')
        return slice(start, start + size)
100253
def _long_from_raw(thehash):
    """"""
    hashnum = 0
    for h in thehash:
        hashnum <<= 8
        hashnum |= ord(bytes([h]))
    return hashnum
1242611
def nscolor_from_hex(hex_string):
        

        hex_string = hex_string[1:]     # Remove leading hash
        if len(hex_string) == 3:
            hex_string = ''.join([c*2 for c in hex_string]) # 3-digit to 6-digit

        hex_int = int(hex_string, 16)
        rgb = (
            (hex_int >> 16) & 0xff,     # Red byte
            (hex_int >> 8) & 0xff,      # Blue byte
            (hex_int) & 0xff            # Green byte
        )
        rgb = [i / 255.0 for i in rgb]      # Normalize to range(0.0, 1.0)

        return AppKit.NSColor.colorWithSRGBRed_green_blue_alpha_(rgb[0], rgb[1], rgb[2], 1.0)
943135
def bits_from_str(cls, s):
        
        try:
            if len(s) <= len(cls.__name__) or not s.startswith(cls.__name__):
                return cls.bits_from_simple_str(s)
            c = s[len(cls.__name__)]
            if c == '(':
                if not s.endswith(')'):
                    raise ValueError
                return cls.bits_from_simple_str(s[len(cls.__name__)+1:-1])
            elif c == '.':
                member_name = s[len(cls.__name__)+1:]
                return int(cls.__all_members__[member_name])
            else:
                raise ValueError
        except ValueError as ex:
            if ex.args:
                raise
            raise ValueError("%s.%s: invalid input: %r" % (cls.__name__, cls.bits_from_str.__name__, s))
        except KeyError as ex:
            raise ValueError("%s.%s: Invalid flag name '%s' in input: %r" % (cls.__name__, cls.bits_from_str.__name__,
                                                                             ex.args[0], s))
1275635
private static String toPaddedHex(long n) {
        String hexValue = Long.toHexString(n);
        hexValue = upperCaseHex(hexValue);
        String paddedHexValue = hexValue.length() <= 12 ? ZEROES.substring(hexValue.length()) + hexValue : hexValue;
        return paddedHexValue;
    }
172082
public static String toPaddedNumber(int value, int width) {
		StringBuilder s = new StringBuilder("00000000").append(Integer.toString(value));
		return s.substring(s.length() - width);
	}
902272
def serialize_input(input, signature_script_hex=''):
    
    if not (isinstance(input, dict) and 'transaction_hash' in input \
            and 'output_index' in input):
        raise Exception('Required parameters: transaction_hash, output_index')

    if is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 64:
        raise Exception("Transaction hash '%s' must be 32 bytes" % input['transaction_hash'])

    elif not is_hex(str(input['transaction_hash'])) and len(str(input['transaction_hash'])) != 32:
        raise Exception("Transaction hash '%s' must be 32 bytes" % hexlify(input['transaction_hash']))

    if not 'sequence' in input:
        input['sequence'] = UINT_MAX

    return ''.join([
        flip_endian(input['transaction_hash']),
        hexlify(struct.pack('<I', input['output_index'])),
        hexlify(variable_length_int(len(signature_script_hex)/2)),
        signature_script_hex,
        hexlify(struct.pack('<I', input['sequence']))
    ])
265432
public static final void hexToBytes(String s, byte[] out, int off)
            throws NumberFormatException, IndexOutOfBoundsException {

        int slen = s.length();
        if ((slen % 2) != 0) {
            s = '0' + s;
        }

        if (out.length < off + slen / 2) {
            throw new IndexOutOfBoundsException(
                    "Output buffer too small for input (" + out.length + '<'
                            + off + slen / 2 + ')');
        }

        // Safe to assume the string is even length
        byte b1, b2;
        for (int i = 0; i < slen; i += 2) {
            b1 = (byte) Character.digit(s.charAt(i), 16);
            b2 = (byte) Character.digit(s.charAt(i + 1), 16);
            if ((b1 < 0) || (b2 < 0)) {
                throw new NumberFormatException();
            }
            out[off + i / 2] = (byte) (b1 << 4 | b2);
        }
    }
102014
def djb_hash(str, len)
      hash = 5381
      for i in (0..len) 
        hash = ((hash << 5) + hash) + str[i].to_i
      end
      return hash
    end
294497
def generate_by_hash(hashcode):
    """"""
    img = Image.new(IMAGE_MODE, IMAGE_SIZE, BACKGROUND_COLOR)
    if len(hashcode) < 32:
        print ("hashcode must have lenght >= 32, %s" % hashcode)
        raise FalseHashError

    allowed = "0123456789abcdef"
    hashcheck = [c in allowed for c in hashcode]
    if False in hashcheck:
        print ("hashcode has not allowed structure %s" % hashcode)
        raise FalseHashError

    pixelmap = setup_pixelmap(hashcode)
    draw_image(pixelmap, img)
    return img
137083
def fromhexstring(cls, hexstring):
        
        bitstring = format(int(hexstring, 16), "0" + str(len(hexstring)/4) + "b")
        return cls.fromstring(bitstring)
775424
function toParameter(value, encoding) {
  let type = Types.VAR_STRING;
  let length;
  let writer = function(value) {
    // eslint-disable-next-line no-invalid-this
    return Packet.prototype.writeLengthCodedString.call(this, value, encoding);
  };
  if (value !== null) {
    switch (typeof value) {
      case 'undefined':
        throw new TypeError('Bind parameters must not contain undefined');

      case 'number':
        type = Types.DOUBLE;
        length = 8;
        writer = Packet.prototype.writeDouble;
        break;

      case 'boolean':
        value = value | 0;
        type = Types.TINY;
        length = 1;
        writer = Packet.prototype.writeInt8;
        break;

      case 'object':
        if (Object.prototype.toString.call(value) === '[object Date]') {
          type = Types.DATETIME;
          length = 12;
          writer = Packet.prototype.writeDate;
        } else if (isJSON(value)) {
          value = JSON.stringify(value);
          type = Types.JSON;
        } else if (Buffer.isBuffer(value)) {
          length = Packet.lengthCodedNumberLength(value.length) + value.length;
          writer = Packet.prototype.writeLengthCodedBuffer;
        }
        break;

      default:
        value = value.toString();
    }
  } else {
    value = '';
    type = Types.NULL;
  }
  if (!length) {
    length = Packet.lengthCodedStringLength(value, encoding);
  }
  return { value, type, length, writer };
}
812469
function padHexStart (hex, length) {
  let len = length || hex.length
  len += len % 2

  return hex.padStart(len, '0')
}
895225
function assignFn(from, to) {
  from = setDefault(10, from);
  to   = setDefault(10, to);

  from = numToWord(from);
  to   = capitalize(numToWord(to));

  return from + 'To' + to;

  // return a copy of a string with its first letter capitalized
  function capitalize(str) {
    return str[0].toUpperCase() + str.slice(1);
  }

  // translate a number to its correlating module-specific namespace
  function numToWord(num) {
    num += '';
    switch(num) {
      case '2':
        return 'bin';
      case '8':
        return 'oct';
      case '10':
        return 'dec';
      case '16':
        return 'hex';
      default:
        throw new Error('Base "' + num + '" is not supported');
    }
  }

  // if `arg` is not provided, return a default value
  function setDefault(defaultVal, arg) {
    return (typeof arg === 'undefined' ? defaultVal : arg);
  }
}
1083290
def create_hash(inp, l=10, algo="sha256"):
    
    return getattr(hashlib, algo)(six.b(str(inp))).hexdigest()[:l]