Python exceptions.ValueError() Examples

The following are 10 code examples of exceptions.ValueError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module exceptions , or try the search function .
Example #1
Source File: discover_nodes.py    From JetPack with Apache License 2.0 6 votes vote down vote up
def ip_address_from_address(address):
    try:
        ip_address = netaddr.IPAddress(address)
    except ValueError as e:
        # address contains a CIDR prefix, netmask, or hostmask.
        e.message = ('invalid IP address: %(address)s (detected CIDR, netmask,'
                     ' hostmask, or subnet)') % {'address': address}
        raise
    except netaddr.AddrFormatError as e:
        # address is not an IP address represented in an accepted string
        # format.
        e.message = ("invalid IP address: '%(address)s' (failed to detect a"
                     " valid IP address)") % {'address': address}
        raise

    if ip_address.version == 4:
        return ip_address
    else:
        raise NotSupported(
            ('invalid IP address: %(address)s (Internet Protocol version'
             ' %(version)s is not supported)') % {
                'address': address,
                'version': ip_address.version}) 
Example #2
Source File: pefile.py    From MalScan with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def dump(self, indentation=0):
        """Returns a string representation of the structure."""
    
        dump = []
        
        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('%-30s %s' % (key+':', val_str)) 
Example #3
Source File: discover_nodes.py    From JetPack with Apache License 2.0 5 votes vote down vote up
def ip_set_from_idrac(idrac):
    range_bounds = idrac.split('-')

    if len(range_bounds) == 2:
        start, end = range_bounds
        ip_set = ip_set_from_address_range(start, end)
    elif len(range_bounds) == 1:
        ip_set = ip_set_from_address(range_bounds[0])
    else:
        # String contains more than one (1) dash.
        raise ValueError(
            ('invalid IP range: %(idrac)s (contains more than one hyphen)') % {
                'idrac': idrac})

    return ip_set 
Example #4
Source File: discover_nodes.py    From JetPack with Apache License 2.0 5 votes vote down vote up
def ip_set_from_address_range(start, end):
    try:
        start_ip_address = ip_address_from_address(start)
        end_ip_address = ip_address_from_address(end)
    except (NotSupported, ValueError) as e:
        raise ValueError(
            ('invalid IP range: %(start)s-%(end)s (%(message)s)') %
            {
                'start': start,
                'end': end,
                'message': e.message})
    except netaddr.AddrFormatError as e:
        raise ValueError(
            ("invalid IP range: '%(start)s-%(end)s' (%(message)s)") %
            {
                'start': start,
                'end': end,
                'message': e.message})

    if start_ip_address > end_ip_address:
        raise ValueError(
            ('invalid IP range: %(start)s-%(end)s (lower bound IP greater than'
             ' upper bound)') %
            {
                'start': start,
                'end': end})

    ip_range = netaddr.IPRange(start_ip_address, end_ip_address)

    return netaddr.IPSet(ip_range) 
Example #5
Source File: discover_nodes.py    From JetPack with Apache License 2.0 5 votes vote down vote up
def ip_set_from_address(address):
    ip_set = netaddr.IPSet()

    try:
        ip_address = ip_address_from_address(address)
        ip_set.add(ip_address)
    except ValueError:
        ip_network = ip_network_from_address(address)
        ip_set.update(ip_network.iter_hosts())

    return ip_set 
Example #6
Source File: configclient.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get_config(self, section=None, option=None):
        """
        Sends the request to get the matching configuration.

        :param section: the optional name of the section.
        :param option: the optional option within the section.
        :return: dictionary containing the configuration.
        """

        if section is None and option is not None:
            raise ValueError('--section not specified')

        path = self.CONFIG_BASEURL
        if section is not None and option is None:
            path += '/' + section
        elif section is not None and option is not None:
            path += '/'.join(['', section, option])

        url = build_url(choice(self.list_hosts), path=path)

        r = self._send_request(url, type='GET')
        if r.status_code == codes.ok:
            return r.json()
        else:
            exc_cls, exc_msg = self._get_exception(headers=r.headers, status_code=r.status_code, data=r.content)
            raise exc_cls(exc_msg) 
Example #7
Source File: firebase_pushid.py    From oldnyc with Apache License 2.0 5 votes vote down vote up
def next_id(self, time_msecs):
        now = int(time_msecs)
        duplicateTime = (now == self.lastPushTime)
        self.lastPushTime = now
        timeStampChars = [''] * 8

        for i in range(7, -1, -1):
            timeStampChars[i] = self.PUSH_CHARS[now % 64]
            now = int(now / 64)

        if (now != 0):
            raise ValueError('We should have converted the entire timestamp.')

        uid = ''.join(timeStampChars)

        if not duplicateTime:
            for i in range(12):
                self.lastRandChars[i] = int(random.random() * 64)
        else:
            # If the timestamp hasn't changed since last push, use the
            # same random number, except incremented by 1.
            for i in range(11, -1, -1):
                if self.lastRandChars[i] == 63:
                    self.lastRandChars[i] = 0
                else:
                    break
            self.lastRandChars[i] += 1

        for i in range(12):
            uid += self.PUSH_CHARS[self.lastRandChars[i]]

        if len(uid) != 20:
            raise ValueError('Length should be 20.')
        return uid 
Example #8
Source File: pefile.py    From ConTroll_Remote_Access_Trojan with Apache License 2.0 5 votes vote down vote up
def dump(self, indentation=0):
        """Returns a string representation of the structure."""
        
        dump = []
        
        dump.append('[%s]' % self.name)
        
        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:
                
                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))
                
                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__, 
                    self.__field_offsets__[key], key+':', val_str)) 
Example #9
Source File: Utils.py    From AstroBox with GNU Affero General Public License v3.0 4 votes vote down vote up
def parse_command(command):
    """
    Parse the command portion of a gcode line, and return a dictionary of found codes and their respective values, and a list of found flags. Codes with integer values will have an integer type, while codes with float values will have a float type
    @param string command Command portion of a gcode line
    @return tuple containing a dict of codes, list of flags.
    """
    codes = {}
    flags = []

    pairs = command.split()
    for pair in pairs:
        code = pair[0]

        # If the code is not a letter, this is an error.
        if not code.isalpha():
            gcode_error = makerbot_driver.Gcode.InvalidCodeError()
            gcode_error.values['InvalidCode'] = code
            raise gcode_error

        # Force the code to be uppercase.
        code = code.upper()

        # If the code already exists, this is an error.
        if code in codes.keys():
            gcode_error = makerbot_driver.Gcode.RepeatCodeError()
            gcode_error.values['RepeatedCode'] = code
            raise gcode_error

        # Don't allow both G and M codes in the same line
        if (code == 'G' and 'M' in codes.keys()) or \
           (code == 'M' and 'G' in codes.keys()):
            raise makerbot_driver.Gcode.MultipleCommandCodeError()

        # If the code doesn't have a value, we consider it a flag, and set it to true.
        if len(pair) == 1:
            flags.append(code)

        else:
            try:
                codes[code] = int(pair[1:])
            except exceptions.ValueError:
                codes[code] = float(pair[1:])

    return codes, flags 
Example #10
Source File: pipelines.py    From proxy_server_crawler with MIT License 4 votes vote down vote up
def test_proxy(item):
	try:
		item['port'] = int(item['port'])
	except ValueError:
		return None
	if item['type'] == 'http':
		proxyHandler = urllib2.ProxyHandler({'http':'http://%s:%s' % (item['ip'], item['port']), 'https':'http://%s:%s' % (item['ip'], item['port'])})  
		opener = urllib2.build_opener(proxyHandler)
		opener.addheaders = {
			'Accept-Encoding': 'gzip',
			'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
			'User-Agent': 'Mozilla/5.0 (compatible; WOW64; MSIE 10.0; Windows NT 6.2)',
			'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
			'Cache-Control': 'max-age=0'
		}.items()
		try:
			req = urllib2.Request('http://httpbin.org/get')
			begin = time.time()
			resp = opener.open(req)
			content = resp.read()
			item['speed'] = int((time.time() - begin) * 1000)
			content = json.loads(content)
			if content['origin'].find(localhost) != -1:
				# print '\t[Leak Header] X-Forwarded-For: %s' % content['origin']
				item['type'] = 'transparent'
				return item
			if len(content['origin'].split(',')) > 1:
				# print '\t[Leak Header] X-Forwarded-For: %s' % content['origin']
				item['type'] = 'anonymous'
				return item
			# logger.error('ip: %s' % item['ip'])
			# for key in content['headers']:
			# 	logger.error('%s: %s' % (key, content['headers'][key]))
			for key in content['headers']:
				if content['headers'][key].find(localhost) != -1:
					# print '\t[Leak Header] %s: %s' % (key, content['headers'][key])
					item['type'] = 'transparent'
					return item
				if key.lower() in proxy_headers:
					# print '\t[Leak Header] %s: %s' % (key, content['headers'][key])
					item['type'] = 'anonymous'
			if item['type'] == 'http':
				item['type'] = 'high'
			return item
		except exceptions.ValueError, error:
			# print 'host seems to be a proxy with limitation'
			# print error
			pass
		except httplib.BadStatusLine, error:
			# print error
			pass