Python types.IntType() Examples

The following are code examples for showing how to use types.IntType(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: core   Author: lifemapper   File: lmobj.py    GNU General Public License v3.0 6 votes vote down vote up
def _setEPSG(self, epsg=None):
        if epsg == None:
            self._epsg = None
        else:
            if isinstance(epsg, (StringType, UnicodeType)): 
                try:
                    epsg = int(epsg)
                    self._epsg = epsg
                except:
                    raise LMError('Invalid epsg code {}'.format(epsg))
            elif isinstance(epsg, IntType):
                self._epsg = epsg
            elif isinstance(epsg, ListType) or isinstance(epsg, TupleType):
                epsgcodes = set(epsg).discard(None)
                if len(epsgcodes) == 1:
                    self._epsg = epsgcodes[0]
                else:
                    raise LMError('LMSpatialObject may only contain a single EPSG code'
                                      .format(epsgcodes))
            else:
                raise LMError('Invalid EPSG code {} type {}'.format(epsg, type(epsg))) 
Example 2
Project: neos-classic-electrum-server   Author: neoscoin   File: deserialize.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, name, enumList):
        self.__doc__ = name
        lookup = {}
        reverseLookup = {}
        i = 0
        uniqueNames = []
        uniqueValues = []
        for x in enumList:
            if isinstance(x, types.TupleType):
                x, i = x
            if not isinstance(x, types.StringType):
                raise EnumException("enum name is not a string: %r" % x)
            if not isinstance(i, types.IntType):
                raise EnumException("enum value is not an integer: %r" % i)
            if x in uniqueNames:
                raise EnumException("enum name is not unique: %r" % x)
            if i in uniqueValues:
                raise EnumException("enum value is not unique for %r" % x)
            uniqueNames.append(x)
            uniqueValues.append(i)
            lookup[x] = i
            reverseLookup[i] = x
            i = i + 1
        self.lookup = lookup
        self.reverseLookup = reverseLookup 
Example 3
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 6 votes vote down vote up
def to64(number):
    """Converts a number in the range of 0 to 63 into base 64 digit
    character in the range of '0'-'9', 'A'-'Z', 'a'-'z','-','_'.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 0 <= number <= 9:            #00-09 translates to '0' - '9'
        return byte(number + 48)

    if 10 <= number <= 35:
        return byte(number + 55)     #10-35 translates to 'A' - 'Z'

    if 36 <= number <= 61:
        return byte(number + 61)     #36-61 translates to 'a' - 'z'

    if number == 62:                # 62   translates to '-' (minus)
        return byte(45)

    if number == 63:                # 63   translates to '_' (underscore)
        return byte(95)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 4
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 6 votes vote down vote up
def from64(number):
    """Converts an ordinal character value in the range of
    0-9,A-Z,a-z,-,_ to a number in the range of 0-63.
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    if 48 <= number <= 57:         #ord('0') - ord('9') translates to 0-9
        return(number - 48)

    if 65 <= number <= 90:         #ord('A') - ord('Z') translates to 10-35
        return(number - 55)

    if 97 <= number <= 122:        #ord('a') - ord('z') translates to 36-61
        return(number - 61)

    if number == 45:               #ord('-') translates to 62
        return(62)

    if number == 95:               #ord('_') translates to 63
        return(63)

    raise ValueError('Invalid Base64 value: %i' % number) 
Example 5
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 6 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo n"""

    if type(message) is types.IntType:
        message = long(message)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or int")

    if message < 0 or message > n:
        raise OverflowError("The message is too long")

    #Note: Bit exponents start at zero (bit counts start at 1) this is correct
    safebit = bit_size(n) - 2                   #compute safe bit (MSB - 1)
    message += (1 << safebit)                   #add safebit to ensure folding

    return pow(message, ekey, n) 
Example 6
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get_id(self, xml_id):
        if xml_id is False or xml_id is None:
            return False
        #if not xml_id:
        #    raise YamlImportException("The xml_id should be a non empty string.")
        elif isinstance(xml_id, types.IntType):
            id = xml_id
        elif xml_id in self.id_map:
            id = self.id_map[xml_id]
        else:
            if '.' in xml_id:
                module, checked_xml_id = xml_id.split('.', 1)
            else:
                module = self.module
                checked_xml_id = xml_id
            try:
                _, id = self.pool.get('ir.model.data').get_object_reference(self.cr, self.uid, module, checked_xml_id)
                self.id_map[xml_id] = id
            except ValueError:
                raise ValueError("""%s not found when processing %s.
    This Yaml file appears to depend on missing data. This often happens for
    tests that belong to a module's test suite and depend on each other.""" % (checked_xml_id, self.filename))

        return id 
Example 7
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 8
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 6 votes vote down vote up
def __getitem__(self, index):
	"""If index is a String, return the Word whose form is
	index.  If index is an integer n, return the Word
	indexed by the n'th Word in the Index file.
	
	>>> N['dog']
	dog(n.)
	>>> N[0]
	'hood(n.)
	"""
	if isinstance(index, StringType):
	    return self.getWord(index)
	elif isinstance(index, IntType):
	    line = self.indexFile[index]
	    return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 9
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def __getitem__(self, index):
        """If index is a String, return the Word whose form is
        index.  If index is an integer n, return the Word
        indexed by the n'th Word in the Index file.

        >>> N['dog']
        dog(n.)
        >>> N[0]
        'hood(n.)
        """
        if isinstance(index, StringType):
            return self.getWord(index)
        elif isinstance(index, IntType):
            line = self.indexFile[index]
            return self.getWord(string.replace(line[:string.find(line, ' ')], '_', ' '), line)
        else:
            raise TypeError, "%s is not a String or Int" % `index`
    
    #
    # Dictionary protocol
    #
    # a Dictionary's values are its words, keyed by their form
    # 
Example 10
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 6 votes vote down vote up
def __init__(self, assignments, len, default=0):
        """
        Construct a new C{SimpleFeatureValueList}.

        @type assignments: C{list} of (C{tuple} of C{int} and (immutable))
        @param assignments: A list of the feature value assignments for
            each feature in this feature value list whose value is not
            the default value.  These assignments are specified as a
            list of C{(id, value)} pairs.
        @type len: C{int}
        @param len: The number of features whose values are specified
            by this feature value list.
        @type default: (immutable)
        @param default: The default value for this feature value list.
            If a feature's value is not specified by C{assignments},
            then that feature's value is the default value.
        """
        assert _chktype(1, assignments, [()], ((),))
        assert _chktype(2, len, types.IntType)
        self._assignments = assignments
        self._len = len
        self._default = default 
Example 11
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def __init__(self, grammar, trace=0, **property_names):
        """
        Create a new C{ShiftReduceParser}, that uses C{grammar} to
        parse texts.

        @type grammar: C{CFG}
        @param grammar: The grammar used to parse texts.
        @type trace: C{int}
        @param trace: The level of tracing that should be used when
            parsing a text.  C{0} will generate no tracing output;
            and higher numbers will produce more verbose tracing
            output.
        @type property_names: C{dict}
        @param property_names: A dictionary that can be used to override
            the default property names.  Each entry maps from a
            default property name to a new property name.
        """
        assert chktype(1, grammar, CFG)
        assert chktype(2, trace, types.IntType)
        self._grammar = grammar
        self._trace = trace
        AbstractParser.__init__(self, **property_names)
        self._check_grammar() 
Example 12
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def trace(self, trace=2):
        """
        Set the level of tracing output that should be generated when
        parsing a text.

        @type trace: C{int}
        @param trace: The trace level.  A trace level of C{0} will
            generate no tracing output; and higher trace levels will
            produce more verbose tracing output.
        @rtype: C{None}
        """
        assert chktype(1, trace, types.IntType)
        # 1: just show shifts.
        # 2: show shifts & reduces
        # 3: display which tokens & productions are shifed/reduced
        self._trace = trace 
Example 13
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def __init__(self, grammar, trace=0, **property_names):
        """
        Create a new C{RecursiveDescentParser}, that uses C{grammar}
        to parse texts.

        @type grammar: C{CFG}
        @param grammar: The grammar used to parse texts.
        @type trace: C{int}
        @param trace: The level of tracing that should be used when
            parsing a text.  C{0} will generate no tracing output;
            and higher numbers will produce more verbose tracing
            output.
        @type property_names: C{dict}
        @param property_names: A dictionary that can be used to override
            the default property names.  Each entry maps from a
            default property name to a new property name.
        """
        assert chktype(1, grammar, CFG)
        assert chktype(2, trace, types.IntType)
        self._grammar = grammar
        self._trace = trace
        AbstractParser.__init__(self, **property_names) 
Example 14
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 6 votes vote down vote up
def __init__(self, grammar, trace=0, **property_names):
        assert chktype(1, grammar, CFG)
        assert chktype(2, trace, types.IntType)
        self._grammar = grammar
        self._trace = trace
        self._rtext = None
        self._tree = None
        self._frontier = [()]
        self._tried_e = {}
        self._tried_m = {}
        self._history = []
        self._parses = []
        AbstractParser.__init__(self, **property_names)

    # [XX] TEMPORARY HACK WARNING!  This should be replaced with
    # something nicer when we get the chance. 
Example 15
Project: robot-navigation   Author: ronaldahmed   File: chunk.py    MIT License 6 votes vote down vote up
def f_measure(self, alpha=0.5):
        """
        @return: the overall F measure for all texts that have been
            scored by this C{ChunkScore}.
        @rtype: C{float}
        
        @param alpha: the relative weighting of precision and recall.
            Larger alpha biases the score towards the precision value,
            while smaller alpha biases the score towards the recall
            value.  C{alpha} should have a value in the range [0,1].
        @type alpha: C{float}
        """
        assert chktype(1, alpha, types.FloatType, types.IntType)
        p = self.precision()
        r = self.recall()
        if p == 0 or r == 0:    # what if alpha is 0 or 1?
            return 0
        return 1/(alpha/p + (1-alpha)/r) 
Example 16
Project: robot-navigation   Author: ronaldahmed   File: probabilistic.py    MIT License 6 votes vote down vote up
def __init__(self, grammar, trace=0, **property_names):
        """
        Create a new C{BottomUpPCFGChartParser}, that uses C{grammar}
        to parse texts.

        @type grammar: C{PCFG}
        @param grammar: The grammar used to parse texts.
        @type trace: C{int}
        @param trace: The level of tracing that should be used when
            parsing a text.  C{0} will generate no tracing output;
            and higher numbers will produce more verbose tracing
            output.
        """
        assert _chktype(1, grammar, PCFG)
        assert _chktype(2, trace, types.IntType)
        self._grammar = grammar
        self._trace = trace
        AbstractParser.__init__(self, **property_names) 
Example 17
Project: robot-navigation   Author: ronaldahmed   File: probabilistic.py    MIT License 6 votes vote down vote up
def __init__(self, beam_size, grammar, trace=0, **property_names):
        """
        Create a new C{BottomUpPCFGChartParser}, that uses C{grammar}
        to parse texts.

        @type beam_size: C{int}
        @param beam_size: The maximum length for the parser's edge queue.
        @type grammar: C{PCFG}
        @param grammar: The grammar used to parse texts.
        @type trace: C{int}
        @param trace: The level of tracing that should be used when
            parsing a text.  C{0} will generate no tracing output;
            and higher numbers will produce more verbose tracing
            output.
        """
        assert _chktype(1, beam_size, types.IntType)
        assert _chktype(2, grammar, PCFG)
        assert _chktype(3, trace, types.IntType)
        BottomUpPCFGChartParser.__init__(self, grammar, trace,
                                         **property_names)
        self._beam_size = beam_size 
Example 18
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 6 votes vote down vote up
def inc(self, sample, count=1):
        """
        Increment this C{FreqDist}'s count for the given
        sample.
        
        @param sample: The sample whose count should be incremented.
        @type sample: any
        @param count: The amount to increment the sample's count by.
        @type count: C{int}
        @rtype: None
        @raise NotImplementedError: If C{sample} is not a
               supported sample type.
        """
        assert _chktype(2, count, types.IntType)
        if count == 0: return
        
        self._N += count
        self._count[sample] = self._count.get(sample,0) + count

        # Invalidate the Nr cache and max cache.
        self._Nr_cache = None
        self._max_cache = None 
Example 19
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 6 votes vote down vote up
def __init__(self, freqdist, bins=None):
        """
        Use the Laplace estimate to create a probability distribution
        for the experiment used to generate C{freqdist}.

        @type freqdist: C{FreqDist}
        @param freqdist: The frequency distribution that the
            probability estimates should be based on.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, freqdist, FreqDist)
        assert _chktype(2, bins, types.IntType, types.NoneType)
        LidstoneProbDist.__init__(self, freqdist, 1, bins) 
Example 20
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 6 votes vote down vote up
def __init__(self, assignments, len, default=0):
        """
        Construct a new C{SimpleFeatureValueList}.

        @type assignments: C{list} of (C{tuple} of C{int} and (immutable))
        @param assignments: A list of the feature value assignments for
            each feature in this feature value list whose value is not
            the default value.  These assignments are specified as a
            list of C{(id, value)} pairs.
        @type len: C{int}
        @param len: The number of features whose values are specified
            by this feature value list.
        @type default: (immutable)
        @param default: The default value for this feature value list.
            If a feature's value is not specified by C{assignments},
            then that feature's value is the default value.
        """
        assert _chktype(1, assignments, [()], ((),))
        assert _chktype(2, len, types.IntType)
        self._assignments = assignments
        self._len = len
        self._default = default 
Example 21
Project: DDEA-DEV   Author: TinyOS-Camp   File: mytool.py    GNU General Public License v2.0 6 votes vote down vote up
def read(filename, index, delim="", ctype=""):
	openfile = open(filename, "r")
	lines = openfile.readlines()
	openfile.close()

	_ctype = type(ctype)
	value = []

	for line in lines:
		tmp = line.rstrip().rsplit(delim)
		for i in index:
			val = tmp[i]
			if _ctype == types.IntType:
				convertedval = int(val)
			elif _ctype == types.FloatType:
				convertedval = float(val)
			elif _ctype == types.StringType:
				convertedval = val
			elif _ctype == types.BooleanType:
				convertedval = bool(val)
			else:
				convertedval = val
			value.append(convertedval)

	return value 
Example 22
Project: pyblish-win   Author: pyblish   File: test_optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_old_type_object(self):
        self.parser.add_option("-s", type=types.StringType)
        self.assertEqual(self.parser.get_option("-s").type, "string")
        self.parser.add_option("-x", type=types.IntType)
        self.assertEqual(self.parser.get_option("-x").type, "int")


# Custom type for testing processing of default values. 
Example 23
Project: core   Author: lifemapper   File: initWorkflow.py    GNU General Public License v3.0 5 votes vote down vote up
def _getAlgorithm(self, config, algHeading):
        """
        @note: Returns configured algorithm
        """
        acode =  config.get(algHeading, BoomKeys.ALG_CODE)
        alg = Algorithm(acode)
        alg.fillWithDefaults()
        inputs = {}
        # override defaults with any option specified
        algoptions = config.getoptions(algHeading)
        for name in algoptions:
            pname, ptype = alg.findParamNameType(name)
            if pname is not None:
                if ptype == types.IntType:
                    val = config.getint(algHeading, pname)
                elif ptype == types.FloatType:
                    val = config.getfloat(algHeading, pname)
                else:
                    val = config.get(algHeading, pname)
                    # Some algorithms(mask) may have a parameter indicating a layer,
                    # if so, add name to parameters and object to inputs
                    if acode == 'hull_region_intersect' and pname == 'region':
                    # TODO: re-enable this later.  
                    #       Now, always use layer in SDM_MASK_META in scenario meta
                        pass
#                         if val.endswith(LMFormat.GTIFF.ext):
#                             val = val[:-len(LMFormat.GTIFF.ext)]
#                         inputs[pname] = val
                alg.setParameter(pname, val)
        if inputs:
            alg.setInputs(inputs)
        return alg
      
    # ............................................................................. 
Example 24
Project: core   Author: lifemapper   File: shapegrid.py    GNU General Public License v3.0 5 votes vote down vote up
def _setCellMeasurements(self, size=None):
        if size is not None and isinstance(size, IntType):
            self._size = size
        else:
            self._size = self._getFeatureCount() 
Example 25
Project: core   Author: lifemapper   File: cwalken.py    GNU General Public License v3.0 5 votes vote down vote up
def _getAlgorithm(self, algHeading):
        """
        @note: Returns configured algorithm
        """
        acode =  self.cfg.get(algHeading, BoomKeys.ALG_CODE)
        alg = Algorithm(acode)
        alg.fillWithDefaults()
        inputs = {}
        # override defaults with any option specified
        algoptions = self.cfg.getoptions(algHeading)
        for name in algoptions:
            pname, ptype = alg.findParamNameType(name)
            if pname is not None:
                if ptype == IntType:
                    val = self.cfg.getint(algHeading, pname)
                elif ptype == FloatType:
                    val = self.cfg.getfloat(algHeading, pname)
                else:
                    val = self.cfg.get(algHeading, pname)
                    # Some algorithms(mask) may have a parameter indicating a layer,
                    # if so, add name to parameters and object to inputs
                    if acode == ECOREGION_MASK_METHOD and pname == 'region':
                        inputs[pname] = val
                alg.setParameter(pname, val)
        if inputs:
            alg.setInputs(inputs)
        return alg

    # ............................................................................. 
Example 26
Project: AshsSDK   Author: thehappydinoa   File: _version133.py    MIT License 5 votes vote down vote up
def int2bytes(number):
    """Converts a number to a string of bytes
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    string = ""

    while number > 0:
        string = "%s%s" % (byte(number & 0xFF), string)
        number /= 256
    
    return string 
Example 27
Project: AshsSDK   Author: thehappydinoa   File: _version133.py    MIT License 5 votes vote down vote up
def encrypt_int(message, ekey, n):
    """Encrypts a message using encryption key 'ekey', working modulo
    n"""

    if type(message) is types.IntType:
        return encrypt_int(long(message), ekey, n)

    if not type(message) is types.LongType:
        raise TypeError("You must pass a long or an int")

    if message > 0 and \
            math.floor(math.log(message, 2)) > math.floor(math.log(n, 2)):
        raise OverflowError("The message is too long")

    return fast_exponentiation(message, ekey, n) 
Example 28
Project: AshsSDK   Author: thehappydinoa   File: _version200.py    MIT License 5 votes vote down vote up
def int2bytes(number):
    """
    Converts a number to a string of bytes
    """

    if not (type(number) is types.LongType or type(number) is types.IntType):
        raise TypeError("You must pass a long or an int")

    string = ""

    while number > 0:
        string = "%s%s" % (byte(number & 0xFF), string)
        number /= 256
    
    return string 
Example 29
Project: SLiPy   Author: glentner   File: mpfit.py    GNU General Public License v2.0 5 votes vote down vote up
def parinfo(self, parinfo=None, key='a', default=None, n=0):
		if self.debug:
			print ('Entering parinfo...')
		if (n == 0) and (parinfo is not None):
			n = len(parinfo)
		if n == 0:
			values = default
	
			return values
		values = []
		for i in range(n):
			if (parinfo is not None) and (parinfo[i].has_key(key)):
				values.append(parinfo[i][key])
			else:
				values.append(default)

		# Convert to numeric arrays if possible
		test = default
		if type(default) == types.ListType:
			test=default[0]
		if isinstance(test, types.IntType):
			values = numpy.asarray(values, int)
		elif isinstance(test, types.FloatType):
			values = numpy.asarray(values, float)
		return values
	
	# Call user function or procedure, with _EXTRA or not, with
	# derivatives or not. 
Example 30
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _coerce_bool(self, value, default=False):
        if isinstance(value, types.BooleanType):
            b = value
        if isinstance(value, types.StringTypes):
            b = value.strip().lower() not in ('0', 'false', 'off', 'no')
        elif isinstance(value, types.IntType):
            b = bool(value)
        else:
            b = default
        return b 
Example 31
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	if isinstance(index, StringType):
	    if hasattr(self, 'indexCache'):
		return self.indexCache[index]
	    return binarySearchFile(self.file, index, self.offsetLineCache, 8)
	elif isinstance(index, IntType):
	    if hasattr(self, 'indexCache'):
		return self.get(self.keys[index])
	    if index < self.nextIndex:
		self.rewind()
	    while self.nextIndex <= index:
		self.file.seek(self.nextOffset)
		line = self.file.readline()
		if line == "":
		    raise IndexError, "index out of range"
		self.nextIndex = self.nextIndex + 1
		self.nextOffset = self.file.tell()
	    return line
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
	
    #
    # Dictionary protocol
    #
    # (an _IndexFile's values are its lines, keyed by the first word)
    # 
Example 32
Project: razzy-spinner   Author: rafasashi   File: wordnet.py    GNU General Public License v3.0 5 votes vote down vote up
def __getitem__(self, index):
	if isinstance(index, StringType):
	    if hasattr(self, 'indexCache'):
		return self.indexCache[index]
	    return binarySearchFile(self.file, index, self.offsetLineCache, 8)
	elif isinstance(index, IntType):
	    if hasattr(self, 'indexCache'):
		return self.get(self.keys[index])
	    if index < self.nextIndex:
		self.rewind()
	    while self.nextIndex <= index:
		self.file.seek(self.nextOffset)
		line = self.file.readline()
		if line == "":
		    raise IndexError, "index out of range"
		self.nextIndex = self.nextIndex + 1
		self.nextOffset = self.file.tell()
	    return line
	else:
	    raise TypeError, "%s is not a String or Int" % `index`
	
    #
    # Dictionary protocol
    #
    # (an _IndexFile's values are its lines, keyed by the first word)
    # 
Example 33
Project: pystran   Author: stijnvanhoey   File: latextablegenerator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def round_sig(x, n):
   '''round floating point x to n significant figures'''
   if type(n) is not types.IntType:
      raise TypeError, "n must be an integer"
   try:
      x = float(x)
   except:
      raise TypeError, "x must be a floating point object"
   form = "%0." + str(n-1) + "e"
   st = form % x
   num,expo = epat.findall(st)[0]
   expo = int(expo)
   fs = string.split(num,'.')
   if len(fs) < 2:
      fs = [fs[0],""]
   if expo == 0:
      return num
   elif expo > 0:
      if len(fs[1]) < expo:
         fs[1] += "0"*(expo-len(fs[1]))
      st = fs[0]+fs[1][0:expo]
      if len(fs[1][expo:]) > 0:
         st += '.'+fs[1][expo:]
      return st
   else:
      expo = -expo
      if fs[0][0] == '-':
         fs[0] = fs[0][1:]
         sign = "-"
      else:
         sign = ""
      return sign+"0."+"0"*(expo-1)+fs[0]+fs[1] 
Example 34
Project: pystran   Author: stijnvanhoey   File: latextablegenerator.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def add_header_row(self, headers, cols=None):
      '''Add a header row to the table.  [headers] should be a list of the
      strings that will be in the header.  [cols], if specified, should be a 
      list of column indexes.  If [cols] is None, it is assummed the headers
      are in order and there are no multicolumns.  If cols is specified, you
      can indicate the the ith header spans several columns by setting the
      ith value of cols to a 2-tuple of first and last columns for the span.'''
      
      if cols is None:
         if len(headers) != self.numcols:
            raise ValueError, "Error, headers must be a list of length %d" %\
                  self.numcols
         self.headers.append(headers)
         self.header_ids.append(range(self.numcols))
      else:
         ids = []
         for item in cols:
            if type(item) is types.IntType:
               ids.append(item)
            elif type(item) is types.TupleType:
               ids += range(item[0],item[1]+1)

         ids.sort
         if ids != range(self.numcols):
            raise ValueError, "Error, missing columns in cols"
         self.headers.append(headers)
         self.header_ids.append(cols)
      return 
Example 35
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def __getitem__(self, index):
        if isinstance(index, StringType):
            if hasattr(self, 'indexCache'):
                return self.indexCache[index]
            return binarySearchFile(self.file, index, self.offsetLineCache, 8)
        elif isinstance(index, IntType):
            if hasattr(self, 'indexCache'):
                return self.get(self.keys[index])
            if index < self.nextIndex:
                self.rewind()
            while self.nextIndex <= index:
                self.file.seek(self.nextOffset)
                line = self.file.readline()
                if line == "":
                    raise IndexError, "index out of range"
                self.nextIndex += 1
                self.nextOffset = self.file.tell()
                return line
            else:
                raise TypeError, "%s is not a String or Int" % `index`

    #
    # Dictionary protocol
    #
    # (an _IndexFile's values are its lines, keyed by the first word)
    # 
Example 36
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def __getitem__(self, index):
        assert _chktype(1, index, types.IntType)
        return self._confusion[index[0], index[1]] 
Example 37
Project: robot-navigation   Author: ronaldahmed   File: featureselection.py    MIT License 5 votes vote down vote up
def __init__(self, sub_fd_list, selected_ids):
        """
        Construct a new C{SelectedFDList}.  This feature detector list
        implements the features from C{sub_fd_list} that are indicated
        by C{selected_ids}.  In particular, the following is true for
        all feature ids M{0<=id<len(self)} and C{LabeledText}s M{lt}::

          self[id].detect(lt) = sub_fd_list[selected_ids.index(id)].detect(lt)

        @type sub_fd_list: C{FeatureDetectorListI}
        @param sub_fd_list: The C{FeatureDetectorList} that this
            C{SelectedFDList} is based on.
        @type selected_ids: C{sequence} of C{int}
        @param selected_ids: The feature ids for the feature detectors
            that should be included in the C{SelectedFDList}.  This
            list should not contain duplicate feature ids.
        """
        assert _chktype(1, sub_fd_list, FeatureDetectorListI)
        assert _chktype(2, selected_ids, [types.IntType], (types.IntType,))
        N = 0
        idmap = {}
        for id in selected_ids:
            if not idmap.has_key(id):
                idmap[id] = N
                N += 1
                
        self._N = N
        self._idmap = idmap
        self._sub_fd_list = sub_fd_list 
Example 38
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 5 votes vote down vote up
def __getitem__(self, feature_id):
        # Inherit docs from FeatureValueListI
        assert _chktype(1, feature_id, types.IntType)
        return self._values[feature_id] 
Example 39
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 5 votes vote down vote up
def __getitem__(self, feature_id):
        # Inherit docs from FeatureValueListI
        assert _chktype(1, feature_id, types.IntType)
        return self._default 
Example 40
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 5 votes vote down vote up
def __getitem__(self, feature_id):
        # Inherit docs from FeatureValueListI
        assert _chktype(1, feature_id, types.IntType)
        if feature_id >= self._len:
            raise IndexError('FeatureValueList index out of range')
        for (id, val) in self._assignments:
            if id == feature_id:
                return val
        return self._default 
Example 41
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 5 votes vote down vote up
def __getitem__(self, feature_id):
        # Inherit docs from FeatureDetectorListI
        assert _chktype(1, feature_id, types.IntType)
        if feature_id >= len(self) or feature_id < 0:
            raise IndexError('FeatureDetectorList index out of range')
        def f(labeled_text, detect=self.detect, id=feature_id):
            return detect(labeled_text)[id]
        return FunctionFeatureDetector(f, ('f_%d()' % feature_id)) 
Example 42
Project: robot-navigation   Author: ronaldahmed   File: feature.py    MIT License 5 votes vote down vote up
def __getitem__(self, feature_id):
        # Inherit docs from FeatureDetectorListI
        assert _chktype(1, feature_id, types.IntType)
        if feature_id >= len(self) or feature_id < 0:
            raise IndexError('FeatureDetectorList index out of range')
        return self._feature_detectors[feature_id] 
Example 43
Project: robot-navigation   Author: ronaldahmed   File: DirectionCorpus.py    MIT License 5 votes vote down vote up
def printDirs(Dirs, margin=70, indent=0):
    """
    @return: A pretty-printed string representation of this tree.
    @rtype: C{string}
    @param margin: The right margin at which to do line-wrapping.
    @type margin: C{int}
    @param indent: The indentation level at which printing
        begins.  This number is used to decide how far to indent
        subsequent lines.
    @type indent: C{int}
    """
    assert _chktype(1, margin, types.IntType)
    assert _chktype(2, indent, types.IntType)
    #    return repr(Dirs)
    if (isinstance(Dirs,str) or isinstance(Dirs,tuple)
        or (isinstance(Dirs,list) and not isinstance(Dirs,Tree))):
        return '\n%s%s\n' % (' '*(indent),Dirs)
    rep = reprDirs(Dirs)
    if len(rep)+indent < margin:
        if indent: return rep
        else: return rep+'\n'
    
    if isinstance(Dirs,Token) and Dirs.has_key('TREE'): tree=Dirs['TREE']
    else: tree = Dirs
    s = ['[',tree.node]
    for child in tree:
        if isinstance(child, Tree):
            s.extend(['\n',' '*(indent+2),printDirs(child,margin, indent+2)])
        elif isinstance(child, Token):
            s.extend([' ',child['TEXT']])
        else: s.extend(['\n',' '*(indent),str(child)])
    s.append(']')
    if indent == 0: s.append('\n')
    return ''.join(s) 
Example 44
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def trace(self, trace=2):
        """
        Set the level of tracing output that should be generated when
        parsing a text.

        @type trace: C{int}
        @param trace: The trace level.  A trace level of C{0} will
            generate no tracing output; and higher trace levels will
            produce more verbose tracing output.
        @rtype: C{None}
        """
        assert chktype(1, trace, types.IntType)
        self._trace = trace 
Example 45
Project: robot-navigation   Author: ronaldahmed   File: chunk.py    MIT License 5 votes vote down vote up
def __init__(self, tagged_tokens, debug_level=3, **property_names):
        """
        Construct a new C{ChunkString} that encodes the chunking of
        the text C{tagged_tokens}.

        @type tagged_tokens: C{list} of C{Token} with C{TaggedType}s
        @param tagged_tokens: The text whose chunking is encoded by
            this C{ChunkString}.  
        @type debug_level: int
        @param debug_level: The level of debugging which should be
            applied to transformations on the C{ChunkString}.  The
            valid levels are:
                - 0: no checks
                - 1: full check on to_chunkstruct
                - 2: full check on to_chunkstruct and cursory check after
                   each transformation. 
                - 3: full check on to_chunkstruct and full check after
                   each transformation.
            We recommend you use at least level 1.  You should
            probably use level 3 if you use any non-standard
            subclasses of C{RegexpChunkParserRule}.
        """
        assert chktype(1, tagged_tokens, [Token, Tree], (Token, Tree), Tree)
        assert chktype(2, debug_level, types.IntType)
        PropertyIndirectionMixIn.__init__(self, **property_names)
        self._ttoks = tagged_tokens
        tags = [self._tag(tok) for tok in tagged_tokens]
        self._str = '<' + '><'.join(tags) + '>'
        self._debug = debug_level 
Example 46
Project: robot-navigation   Author: ronaldahmed   File: chunk.py    MIT License 5 votes vote down vote up
def __init__(self, rules, chunk_node='CHUNK', top_node='TEXT',
                 trace=0, **property_names):
        """
        Construct a new C{RegexpChunkParser}.
        
        @type rules: C{list} of C{RegexpChunkParserRule}
        @param rules: The sequence of rules that should be used to
            generate the chunking for a tagged text.
        @type chunk_node: C{string}
        @param chunk_node: The node value that should be used for
            chunk subtrees.  This is typically a short string
            describing the type of information contained by the chunk,
            such as C{"NP"} for base noun phrases.
        @type top_node: C{string}
        @param top_node: The node value that should be used for the
            top node of the chunk structure.
        @type trace: C{int}
        @param trace: The level of tracing that should be used when
            parsing a text.  C{0} will generate no tracing output;
            C{1} will generate normal tracing output; and C{2} or
            highter will generate verbose tracing output.
        """
        assert chktype(1, rules, [RegexpChunkParserRule], (RegexpChunkParserRule,))
        assert chktype(4, trace, types.IntType)
        self._rules = rules
        self._trace = trace
        self._chunk_node = chunk_node
        self._top_node = top_node
        AbstractParser.__init__(self, **property_names) 
Example 47
Project: robot-navigation   Author: ronaldahmed   File: probabilistic.py    MIT License 5 votes vote down vote up
def trace(self, trace=2):
        """
        Set the level of tracing output that should be generated when
        parsing a text.

        @type trace: C{int}
        @param trace: The trace level.  A trace level of C{0} will
            generate no tracing output; and higher trace levels will
            produce more verbose tracing output.
        @rtype: C{None}
        """
        assert _chktype(1, trace, types.IntType)
        self._trace = trace 
Example 48
Project: robot-navigation   Author: ronaldahmed   File: __init__.py    MIT License 5 votes vote down vote up
def __init__(self, n, reverse=False, cutoff=0, **property_names):
        """
        Construct a new I{n}-th order stochastic tagger.  The new
        tagger should be trained, using the L{train()} method, before
        it is used to tag data.
        
        @param n: The order of the new C{NthOrderTagger}.
        @type n: int
        @param reverse: If true, then assign tags to subtokens in
            reverse sequential order (i.e., from last to first).
        @type cutoff: C{int}
        @param cutoff: A count-cutoff for the tagger's frequency
            distribution.  If the tagger saw fewer than
            C{cutoff} examples of a given context in training,
            then it will return a tag of C{None} for that context.
        @type property_names: C{dict}
        @param property_names: A dictionary that can be used to override
            the default property names.  Each entry maps from a
            default property name to a new property name.
        """
        assert chktype(1, n, types.IntType)
        if n < 0: raise ValueError('n must be non-negative')
        SequentialTagger.__init__(self, reverse, **property_names)
        self._freqdist = ConditionalFreqDist()
        self._n = n
        self._cutoff = cutoff

        # Record the start & end indices of the context window for
        # tags.
        if self._reverse:
            self._left = 1
            self._right = 1+n
        else:
            self._left = -n
            self._right = 0 
Example 49
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def __init__(self, freqdist, gamma, bins=None):
        """
        Use the Lidstone estimate to create a probability distribution
        for the experiment used to generate C{freqdist}.

        @type freqdist: C{FreqDist}
        @param freqdist: The frequency distribution that the
            probability estimates should be based on.
        @type gamma: C{float}
        @param gamma: A real number used to paramaterize the
            estimate.  The Lidstone estimate is equivalant to adding
            M{gamma} to the count for each bin, and taking the
            maximum likelihood estimate of the resulting frequency
            distribution.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, freqdist, FreqDist)
        assert _chktype(2, gamma, types.FloatType, types.IntType)
        assert _chktype(3, bins, types.IntType, types.NoneType)
        if (bins == 0) or (bins is None and freqdist.N() == 0):
            name = self.__class__.__name__[:-8]
            raise ValueError('A %s probability distribution ' % name +
                             'must have at least one bin.')
        if (bins is not None) and (bins < freqdist.B()):
            name = self.__class__.__name__[:-8]
            raise ValueError('\nThe number of bins in a %s must be ' % name +
                             'greater than or equal to\nthe number of '+
                             'bins in the FreqDist used to create it.')
        
        self._freqdist = freqdist
        self._gamma = float(gamma)
        self._N = self._freqdist.N()

        if bins is None: bins = freqdist.B()
        self._bins = bins 
Example 50
Project: robot-navigation   Author: ronaldahmed   File: probability.py    MIT License 5 votes vote down vote up
def __init__(self, base_fdist, heldout_fdist, bins=None):
        """
        Use the heldout estimate to create a probability distribution
        for the experiment used to generate C{base_fdist} and
        C{heldout_fdist}.

        @type base_fdist: C{FreqDist}
        @param base_fdist: The base frequency distribution.
        @type heldout_fdist: C{FreqDist}
        @param heldout_fdist: The heldout frequency distribution.
        @type bins: C{int}
        @param bins: The number of sample values that can be generated
            by the experiment that is described by the probability
            distribution.  This value must be correctly set for the
            probabilities of the sample values to sum to one.  If
            C{bins} is not specified, it defaults to C{freqdist.B()}.
        """
        assert _chktype(1, base_fdist, FreqDist)
        assert _chktype(2, heldout_fdist, FreqDist)
        assert _chktype(3, bins, types.IntType, types.NoneType)
        
        self._base_fdist = base_fdist
        self._heldout_fdist = heldout_fdist

        # The max number of times any sample occurs in base_fdist.
        self._max_r = base_fdist.count(base_fdist.max())

        # Calculate Tr, Nr, and N.
        Tr = self._calculate_Tr()
        Nr = [base_fdist.Nr(r, bins) for r in range(self._max_r+1)]
        N = heldout_fdist.N()

        # Use Tr, Nr, and N to compute the probability estimate for
        # each value of r.
        self._estimate = self._calculate_estimate(Tr, Nr, N)