Python types.StringTypes() Examples

The following are code examples for showing how to use types.StringTypes(). 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: link-prediction_with_deep-learning   Author: cambridgeltl   File: wvlib.py    MIT License 6 votes vote down vote up
def similarity(self, v1, v2):
        """Return cosine similarity of given words or vectors.

        If v1/v2 is a string, look up the corresponding word vector.
        This is not particularly efficient function. Instead of many
        invocations, consider word_similarity() or direct computation.
        """
        
        vs = [v1, v2]
        for i, v in enumerate(vs):
            if isinstance(v, StringTypes):
                v = self.word_to_unit_vector(v)
            else:
                v = v/numpy.linalg.norm(v) # costly but safe
            vs[i] = v
        return numpy.dot(vs[0], vs[1]) 
Example 2
Project: fuzzkit   Author: VillanCh   File: core.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _render_without_enums(self, rendered_by_wraper):
        """"""
        _ksn = self._replace_table_without_enum.values()
        _ksn = tuple(_ksn)
        
        
        for i in self._replace_table_without_enum:
            _target = self._replace_table_without_enum[i].value
            if not isinstance(_target, types.StringTypes):
                _target = str(_target)
            _tag = self._replace_table_without_enum[i]
            if self._wraper_flag[_tag]:
                rendered_by_wraper = rendered_by_wraper.replace(i, self._wrap(_target))
            else:
                rendered_by_wraper = rendered_by_wraper.replace(i, _target)

            
        return rendered_by_wraper

    
    #---------------------------------------------------------------------- 
Example 3
Project: SherpaHighLevel   Author: Shedino   File: xmlifApi.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setAttribute (self, tupleOrAttrName, attributeValue):
        """Sets an attribute value of the current element node. 
        If the attribute does not yet exist, it will be created.
               
        Input parameter:
            tupleOrAttrName:  tuple '(namespace, attributeName)' or 'attributeName' if no namespace is used
            attributeValue:   attribute value to be set
        """
        if not isinstance(attributeValue, StringTypes):
            raise TypeError, "%s (attribute %s) must be a string!" %(repr(attributeValue), repr(tupleOrAttrName))

        nsNameAttrName = NsNameTupleFactory(tupleOrAttrName)
        if nsNameAttrName not in self.attributeSequence:
            self.attributeSequence.append(nsNameAttrName)

        if self.__useCaching():
            if self.__qNameAttrCache.has_key(nsNameAttrName):
                del self.__qNameAttrCache[nsNameAttrName]

        self.element.xmlIfExtSetAttribute(nsNameAttrName, attributeValue, self.getCurrentNamespaces()) 
Example 4
Project: appsdk-python   Author: elves-project   File: log4py.py    Apache License 2.0 6 votes vote down vote up
def fmtstr(self, *fmt):  
        str = ''  
        encoding = 'utf8'#缺省utf8编码  
        for i in fmt:  
            if not type(i) in [types.UnicodeType, types.StringTypes, types.StringType]:  
                s= repr(i)  
            else:  
                s = i  
            if type(s) == type(u''):  
                str += s.encode(encoding)  
            else:  
                str += s  
            str += '.'  
        #str += '/n'  
        #print 'fmtstr:'+str  
        return str 
Example 5
Project: kotori   Author: daq-tools   File: influx.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def data_to_float(self, data):
        return convert_floats(data)

        for key, value in data.iteritems():

            # Sanity checks
            if type(value) in types.StringTypes:
                continue

            if value is None:
                data[key] = None
                continue

            # Convert to float
            try:
                data[key] = float(value)
            except (TypeError, ValueError) as ex:
                log.warn(u'Measurement "{key}: {value}" float conversion failed: {ex}', key=key, value=value, ex=ex) 
Example 6
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 6 votes vote down vote up
def _setTarget(self, address, prefix=None, filters=None):
		"""Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget.
		    - address ((host, port) tuple): IP-address & UDP-port 
		    - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage
		  sent to this OSCTarget (optional)
		"""
		if address not in self.targets.keys():
			self.targets[address] = ["",{}]
		
		if prefix != None:
			if len(prefix):
				# make sure prefix starts with ONE '/', and does not end with '/'
				prefix = '/' + prefix.strip('/')
				
			self.targets[address][0] = prefix
		
		if filters != None:
			if type(filters) in types.StringTypes:
				(_, filters) = parseFilterStr(filters)
			elif type(filters) != types.DictType:
				raise TypeError("'filters' argument must be a dict with {addr:bool} entries")
		
			self._updateFilters(self.targets[address][1], filters) 
Example 7
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 6 votes vote down vote up
def setOSCTarget(self, address, prefix=None, filters=None):
		"""Add (i.e. subscribe) a new OSCTarget, or change the prefix for an existing OSCTarget.
		  the 'address' argument can be a ((host, port) tuple) : The target server address & UDP-port
		    or a 'host' (string) : The host will be looked-up 
		  - prefix (string): The OSC-address prefix prepended to the address of each OSCMessage
		  sent to this OSCTarget (optional)
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address)
				
		elif (type(address) == types.TupleType):
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except:
				pass
				
			address = (host, port)
		else:
			raise TypeError("'address' argument must be a (host, port) tuple or a 'host' string")
		
		self._setTarget(address, prefix, filters) 
Example 8
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 6 votes vote down vote up
def delOSCTarget(self, address, prefix=None):
		"""Delete the specified OSCTarget from the Client's dict.
		the 'address' argument can be a ((host, port) tuple), or a hostname.
		If the 'prefix' argument is given, the Target is only deleted if the address and prefix match.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if type(address) == types.TupleType:
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
			
			self._delTarget(address, prefix) 
Example 9
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 6 votes vote down vote up
def getOSCTarget(self, address):
		"""Returns the OSCTarget matching the given address as a ((host, port), [prefix, filters]) tuple.
		'address' can be a (host, port) tuple, or a 'host' (string), in which case the first matching OSCTarget is returned
		Returns (None, ['',{}]) if address not found.
		"""
		if type(address) in types.StringTypes:
			address = self._searchHostAddr(address) 

		if (type(address) == types.TupleType): 
			(host, port) = address[:2]
			try:
				host = socket.gethostbyname(host)
			except socket.error:
				pass
			address = (host, port)
					
			if (address in self.targets.keys()):
				try:
					(host, _, _) = socket.gethostbyaddr(host)
				except socket.error:
					pass
	
				return ((host, port), self.targets[address])

		return (None, ['',{}]) 
Example 10
Project: sndlatr   Author: Schibum   File: util.py    Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example 11
Project: experts-app-backend   Author: GoogleDeveloperExperts   File: util.py    Apache License 2.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example 12
Project: mekong-ssc-gae   Author: KMarkert   File: util.py    GNU General Public License v3.0 6 votes vote down vote up
def scopes_to_string(scopes):
  """Converts scope value to a string.

  If scopes is a string then it is simply passed through. If scopes is an
  iterable then a string is returned that is all the individual scopes
  concatenated with spaces.

  Args:
    scopes: string or iterable of strings, the scopes.

  Returns:
    The scopes formatted as a single string.
  """
  if isinstance(scopes, types.StringTypes):
    return scopes
  else:
    return ' '.join(scopes) 
Example 13
Project: tom-bot   Author: maartenberg   File: registry.py    MIT License 5 votes vote down vote up
def __call__(self, func):
        if hasattr(self.eventname, '__iter__'):
            if isinstance(self.eventname, types.StringTypes):
                # String
                EVENT_HANDLERS[self.eventname].add(func)
                return func

            # Iterable
            for name in self.eventname:
                EVENT_HANDLERS[name].add(func)
            return func

        # Something else
        EVENT_HANDLERS[self.eventname].add(func)
        return func 
Example 14
Project: tom-bot   Author: maartenberg   File: registry.py    MIT License 5 votes vote down vote up
def __call__(self, func):
        if isinstance(self.name, types.StringTypes):
            self.help_dict[self.category].append((self.name, None, func))
        else:
            self.help_dict[self.category].append((self.name[0], self.name[1:], func))
        return super(Command, self).__call__(func) 
Example 15
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def add_option(self, *args, **kwargs):
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
        if type(args[0]) in types.StringTypes:
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
                raise TypeError, "not an Option instance: %r" % option
        else:
            raise TypeError, "invalid arguments"

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
            elif option.dest not in self.defaults:
                self.defaults[option.dest] = None

        return option 
Example 16
Project: pyblish-win   Author: pyblish   File: inspect.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, types.StringTypes):
        return None
    return cleandoc(doc) 
Example 17
Project: neos-classic-electrum-server   Author: neoscoin   File: stratum_http.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_request(request):
    if not isinstance(request, types.DictType):
        return Fault(-32600, 'Request must be {}, not %s.' % type(request))
    rpcid = request.get('id', None)
    version = get_version(request)
    if not version:
        return Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid)
    request.setdefault('params', [])
    method = request.get('method', None)
    params = request.get('params')
    param_types = (types.ListType, types.DictType, types.TupleType)
    if not method or type(method) not in types.StringTypes or type(params) not in param_types:
        return Fault(-32600, 'Invalid request parameters or method.', rpcid=rpcid)
    return True 
Example 18
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def is_comment(node):
    return isinstance(node, types.StringTypes) 
Example 19
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 20
Project: link-prediction_with_deep-learning   Author: cambridgeltl   File: wvlib.py    MIT License 5 votes vote down vote up
def approximate_similarity(self, v1, v2, bits=None):
        """Return approximate cosine similarity of given words or vectors.

        Uses random hyperplane-based locality sensitive hashing (LSH)
        with given number of bits. If bits is None, estimate number of
        bits to use.

        LSH is initialized on the first invocation, which may take
        long for large numbers of word vectors. For a small number of
        invocations, similarity() may be more efficient.
        """

        if self._w2h_lsh is None or (bits is not None and bits != self._w2h_lsh.bits):
            if not with_gmpy:
                logging.warning('gmpy not available, approximate similarity '
                                'may be slow.')
            self._w2h_lsh = self._initialize_lsh(bits, fill=False)
            self._w2h_map = {}
            logging.info('init word-to-hash map: start')
            for w, v in self:
                self._w2h_map[w] = self._w2h_lsh.hash(v)
            logging.info('init word-to-hash map: done')            

        hashes = []
        for v in (v1, v2):
            if isinstance(v, StringTypes):
                h = self._w2h_map[v]
            else:
                h = self._w2h_lsh.hash(v)
            hashes.append(h)

        return self._w2h_lsh.hash_similarity(hashes[0], hashes[1]) 
Example 21
Project: link-prediction_with_deep-learning   Author: cambridgeltl   File: wvlib.py    MIT License 5 votes vote down vote up
def nearest(self, v, n=10, exclude=None, candidates=None):
        """Return nearest n words and similarities for given word or vector,
        excluding given words.

        If v is a string, look up the corresponding word vector.
        If exclude is None and v is a string, exclude v.
        If candidates is not None, only consider (word, vector)
        values from iterable candidates.
        Return value is a list of (word, similarity) pairs.
        """

        if isinstance(v, StringTypes):
            v, w = self.word_to_unit_vector(v), v
        else:
            v, w = v/numpy.linalg.norm(v), None
        if exclude is None:
            exclude = [] if w is None else set([w])
        if not self._normalized:
            sim = partial(self._item_similarity, v=v)
        else:
            sim = partial(self._item_similarity_normalized, v=v)
        if candidates is None:
            candidates = self.word_to_vector_mapping().iteritems()
        nearest = heapq.nlargest(n+len(exclude), candidates, sim)
        wordsim = [(p[0], sim(p)) for p in nearest if p[0] not in exclude]
        return wordsim[:n] 
Example 22
Project: nmap-tor-scanner   Author: BlackBox-CSP   File: nmap.py    MIT License 5 votes vote down vote up
def listscan(self, hosts='127.0.0.1'):
        """
        do not scan but interpret target hosts and return a list a hosts
        """
        assert type(hosts) in types.StringTypes, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts))

        self.scan(hosts, arguments='-sL')
        return self.all_hosts() 
Example 23
Project: nmap-tor-scanner   Author: BlackBox-CSP   File: nmap.py    MIT License 5 votes vote down vote up
def __getitem__(self, host):
        """
        returns a host detail
        """
        assert type(host) in types.StringTypes, 'Wrong type for [host], should be a string [was {0}]'.format(type(host))
        return self._scan_result['scan'][host] 
Example 24
Project: nmap-tor-scanner   Author: BlackBox-CSP   File: nmap.py    MIT License 5 votes vote down vote up
def has_host(self, host):
        """
        returns True if host has result, False otherwise
        """
        assert type(host) is types.StringTypes, 'Wrong type for [host], should be a string [was {0}]'.format(type(host))

        if host in self._scan_result['scan'].keys():
            return True

        return False




############################################################################ 
Example 25
Project: nmap-tor-scanner   Author: BlackBox-CSP   File: nmap.py    MIT License 5 votes vote down vote up
def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', callback=None):
        """
        Scan given hosts in a separate process and return host by host result using callback function

        PortScannerError exception from standard nmap is catched and you won't know about it

        hosts = string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
        ports = string for ports as nmap use it '22,53,110,143-4564'
        arguments = string of arguments for nmap '-sU -sX -sC'
        callback = callback function which takes (host, scan_data) as arguments
        """

        assert type(hosts) in types.StringTypes, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts))
        assert type(ports) in types.StringTypes+(types.NoneType,), 'Wrong type for [ports], should be a string [was {0}]'.format(type(ports))
        assert type(arguments) in types.StringTypes, 'Wrong type for [arguments], should be a string [was {0}]'.format(type(arguments))
        assert type(callback) in (types.FunctionType, types.NoneType), 'Wrong type for [callback], should be a function or None [was {0}]'.format(type(callback))

        def scan_progressive(self, hosts, ports, arguments, callback):
            for host in self._nm.listscan(hosts):
                try:
                    scan_data = self._nm.scan(host, ports, arguments)
                except PortScannerError:
                    pass
                if callback is not None and callable(callback):
                    callback(host, scan_data)
            return

        self._process = Process(
            target=scan_progressive,
            args=(self, hosts, ports, arguments, callback)
            )
        self._process.daemon = True
        self._process.start()
        return 
Example 26
Project: google-deployment-manager-influxdb-enterprise   Author: influxdata   File: software_status.py    MIT License 5 votes vote down vote up
def _WaiterDependsOn(context):
  """Returns the waiterDependsOn property or an empty list if unspecified."""
  depends_on = context.properties.get('waiterDependsOn', [])
  if not isinstance(depends_on, list):
    raise PropertyError('waiterDependsOn must be a list: {}'.format(depends_on))

  for item in depends_on:
    if not isinstance(item, types.StringTypes):
      raise PropertyError(
          'waiterDependsOn must be a list of strings: {}'.format(depends_on))

  return depends_on 
Example 27
Project: centreon-discovery   Author: Centreon-Community   File: nmap.py    GNU General Public License v2.0 5 votes vote down vote up
def listscan(self, hosts='127.0.0.1'):
        """
        do not scan but interpret target hosts and return a list a hosts
        """
        assert type(hosts) in types.StringTypes, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts))
        
        self.scan(hosts, arguments='-sL')
        return self.all_hosts() 
Example 28
Project: centreon-discovery   Author: Centreon-Community   File: nmap.py    GNU General Public License v2.0 5 votes vote down vote up
def __getitem__(self, host):
        """
        returns a host detail
        """
        assert type(host) in types.StringTypes, 'Wrong type for [host], should be a string [was {0}]'.format(type(host))
        return self._scan_result['scan'][host] 
Example 29
Project: centreon-discovery   Author: Centreon-Community   File: nmap.py    GNU General Public License v2.0 5 votes vote down vote up
def has_host(self, host):
        """
        returns True if host has result, False otherwise
        """
        assert type(host) is types.StringTypes, 'Wrong type for [host], should be a string [was {0}]'.format(type(host))

        if host in self._scan_result['scan'].keys():
            return True

        return False




############################################################################ 
Example 30
Project: centreon-discovery   Author: Centreon-Community   File: nmap.py    GNU General Public License v2.0 5 votes vote down vote up
def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', callback=None):
        """
        Scan given hosts in a separate process and return host by host result using callback function

        PortScannerError exception from standard nmap is catched and you won't know about it

        hosts = string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
        ports = string for ports as nmap use it '22,53,110,143-4564'
        arguments = string of arguments for nmap '-sU -sX -sC'
        callback = callback function which takes (host, scan_data) as arguments
        """

        assert type(hosts) in types.StringTypes, 'Wrong type for [hosts], should be a string [was {0}]'.format(type(hosts))
        assert type(ports) in types.StringTypes+(types.NoneType,), 'Wrong type for [ports], should be a string [was {0}]'.format(type(ports))
        assert type(arguments) in types.StringTypes, 'Wrong type for [arguments], should be a string [was {0}]'.format(type(arguments))
        assert type(callback) in (types.FunctionType, types.NoneType), 'Wrong type for [callback], should be a function or None [was {0}]'.format(type(callback))
        
        def scan_progressive(self, hosts, ports, arguments, callback):
            for host in self._nm.listscan(hosts):
                try:
                    scan_data = self._nm.scan(host, ports, arguments)
                except PortScannerError:
                    pass
                if callback is not None and callable(callback):
                    callback(host, scan_data)
            return

        self._process = Process(
            target=scan_progressive,
            args=(self, hosts, ports, arguments, callback)
            )
        self._process.daemon = True
        self._process.start()
        return 
Example 31
Project: fuzzkit   Author: VillanCh   File: core.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def feed(self, raw, tag, wraperable=False):
        """"""
        assert isinstance(raw, types.StringTypes)
        self._wraper_flag[tag] = wraperable
        
        if tag._type == 'ENUM':
            self._replace_table_with_enum[raw] = tag
            self._replace_keys_with_enum = self._replace_table_with_enum.keys()
        else:
            self._replace_table_without_enum[raw] = tag
            self._replace_keys_without_enum = self._replace_table_without_enum.keys()
            
        
    
    #---------------------------------------------------------------------- 
Example 32
Project: fuzzkit   Author: VillanCh   File: codecs_common.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def unicode_build_from_number(orig, hexable=True):
    """"""
    if isinstance(orig, int):
        return unichr(orig)
    elif isinstance(orig, types.StringTypes):
        if hexable:
            return unichr(eval('0x' + orig))
        else:
            return unichr(int(orig))

#---------------------------------------------------------------------- 
Example 33
Project: fuzzkit   Author: VillanCh   File: core.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def feed(self, raw, tag, wraperable=False):
        """"""
        assert isinstance(raw, types.StringTypes)
        self._wraper_flag[tag] = wraperable
        
        if tag._type == 'ENUM':
            self._replace_table_with_enum[raw] = tag
            self._replace_keys_with_enum = self._replace_table_with_enum.keys()
        else:
            self._replace_table_without_enum[raw] = tag
            self._replace_keys_without_enum = self._replace_table_without_enum.keys()
            
        
    
    #---------------------------------------------------------------------- 
Example 34
Project: fuzzkit   Author: VillanCh   File: codecs_common.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def unicode_build_from_number(orig, hexable=True):
    """"""
    if isinstance(orig, int):
        return unichr(orig)
    elif isinstance(orig, types.StringTypes):
        if hexable:
            return unichr(eval('0x' + orig))
        else:
            return unichr(int(orig))

#---------------------------------------------------------------------- 
Example 35
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def QNameTupleFactory(initValue):
    if isinstance(initValue, StringTypes):
        separatorIndex = string.find (initValue, ':')
        if separatorIndex != -1:
            initValue = (initValue[:separatorIndex], initValue[separatorIndex+1:])
        else:
           initValue = (EMPTY_PREFIX, initValue)
    return QNameTuple(initValue)


######################################################################
# class containing a tuple of namespace and localName
# 
Example 36
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def NsNameTupleFactory(initValue):
    if isinstance(initValue, StringTypes):
        initValue = splitClarkQName(initValue)
    elif initValue == None:
        initValue = (EMPTY_NAMESPACE, initValue)
    return NsNameTuple(initValue) 
Example 37
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def QNameTupleFactory(initValue):
    if isinstance(initValue, StringTypes):
        separatorIndex = string.find (initValue, ':')
        if separatorIndex != -1:
            initValue = (initValue[:separatorIndex], initValue[separatorIndex+1:])
        else:
           initValue = (EMPTY_PREFIX, initValue)
    return QNameTuple(initValue)


######################################################################
# class containing a tuple of namespace and localName
# 
Example 38
Project: SherpaHighLevel   Author: Shedino   File: xmlifUtils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def NsNameTupleFactory(initValue):
    if isinstance(initValue, StringTypes):
        initValue = splitClarkQName(initValue)
    elif initValue == None:
        initValue = (EMPTY_NAMESPACE, initValue)
    return NsNameTuple(initValue) 
Example 39
Project: Uwallet-server   Author: UlordChain   File: stratum_http.py    GNU General Public License v3.0 5 votes vote down vote up
def validate_request(request):
    if not isinstance(request, types.DictType):
        return Fault(-32600, 'Request must be {}, not %s.' % type(request))
    rpcid = request.get('id', None)
    version = get_version(request)
    if not version:
        return Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid)
    request.setdefault('params', [])
    method = request.get('method', None)
    params = request.get('params')
    param_types = (types.ListType, types.DictType, types.TupleType)
    if not method or type(method) not in types.StringTypes or type(params) not in param_types:
        return Fault(-32600, 'Invalid request parameters or method.', rpcid=rpcid)
    return True 
Example 40
Project: ironpython2   Author: IronLanguages   File: optparse.py    Apache License 2.0 5 votes vote down vote up
def add_option(self, *args, **kwargs):
        """add_option(Option)
           add_option(opt_str, ..., kwarg=val, ...)
        """
        if type(args[0]) in types.StringTypes:
            option = self.option_class(*args, **kwargs)
        elif len(args) == 1 and not kwargs:
            option = args[0]
            if not isinstance(option, Option):
                raise TypeError, "not an Option instance: %r" % option
        else:
            raise TypeError, "invalid arguments"

        self._check_conflict(option)

        self.option_list.append(option)
        option.container = self
        for opt in option._short_opts:
            self._short_opt[opt] = option
        for opt in option._long_opts:
            self._long_opt[opt] = option

        if option.dest is not None:     # option has a dest, we need a default
            if option.default is not NO_DEFAULT:
                self.defaults[option.dest] = option.default
            elif option.dest not in self.defaults:
                self.defaults[option.dest] = None

        return option 
Example 41
Project: ironpython2   Author: IronLanguages   File: inspect.py    Apache License 2.0 5 votes vote down vote up
def getdoc(object):
    """Get the documentation string for an object.

    All tabs are expanded to spaces.  To clean up docstrings that are
    indented to line up with blocks of code, any whitespace than can be
    uniformly removed from the second line onwards is removed."""
    try:
        doc = object.__doc__
    except AttributeError:
        return None
    if not isinstance(doc, types.StringTypes):
        return None
    return cleandoc(doc) 
Example 42
Project: zm-applet   Author: Tim-Craig   File: app_config.py    GNU General Public License v3.0 5 votes vote down vote up
def get_event_configs_assigned_to_input_labels(self, event_config_values):
        def set_in_set(set1, set2):
            for item in set1:
                if item not in set2:
                    return False
            return True

        def find_matching_string_value(value_to_find, list_of_values):
            return_val = None
            if '+' in value_to_find:
                values = value_to_find.split('+')
                if set_in_set(values, list_of_values):
                    return_val = values
            else:
                return_val = value_to_find if value_to_find in list_of_values else None
            return return_val

        def find_matching_values(target_value, possible_values):
            matches = []
            if isinstance(target_value, types.StringTypes):
                match = find_matching_string_value(target_value, possible_values)
                if match:
                    matches.append(match)
            else:
                for value in target_value:
                    match = find_matching_string_value(value, possible_values)
                    if match:
                        matches.append(match)
            return matches if len(matches) > 0 else None

        matching_config_map = {}
        for config_name in app_events.CONFIG_EVENT_TYPES:
            if config_name in self.config.keys():
                config_value = self.config[config_name]
                matched_values = find_matching_values(config_value, event_config_values)
                if matched_values:
                    matching_config_map[config_name] = matched_values
        return matching_config_map 
Example 43
Project: zm-applet   Author: Tim-Craig   File: input_handler.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, app_config, input_config_label_mapping):
        event_to_label_mapping = app_config.get_event_configs_assigned_to_input_labels(
            input_config_label_mapping.keys())
        self.single_input_events = {}
        self.multi_input_events = {}
        for event, label_values in event_to_label_mapping.iteritems():
            for label_value in label_values:
                if isinstance(label_value, types.StringTypes):
                    self.single_input_events[input_config_label_mapping[label_value]] = event
                else:
                    mapped_label_values = [input_config_label_mapping[label] for label in label_value]
                    self.multi_input_events[input_config_label_mapping[label_value[0]]] = (event, mapped_label_values) 
Example 44
Project: electrum-martexcoin-server   Author: martexcoin   File: stratum_http.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def validate_request(request):
    if not isinstance(request, types.DictType):
        return Fault(-32600, 'Request must be {}, not %s.' % type(request))
    rpcid = request.get('id', None)
    version = get_version(request)
    if not version:
        return Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid)
    request.setdefault('params', [])
    method = request.get('method', None)
    params = request.get('params')
    param_types = (types.ListType, types.DictType, types.TupleType)
    if not method or type(method) not in types.StringTypes or type(params) not in param_types:
        return Fault(-32600, 'Invalid request parameters or method.', rpcid=rpcid)
    return True 
Example 45
Project: code-inspector   Author: maxim5   File: 6ad4f63fd0366f96e58fc5a9c62fa761_algorithm.py    Apache License 2.0 5 votes vote down vote up
def OpenGraph(self, file_obj, fileName=None):
        """ Read in a graph from file and open the display """
        if type(file_obj) in types.StringTypes:
            self.graphFileName = file_obj
        elif type(file_obj)==types.FileType or issubclass(file_obj.__class__,StringIO.StringIO):
            self.graphFileName = fileName
        else:
            raise Exception("wrong types in argument list: expected string or file like object")
        self.cleanGraphCopy = OpenCATBoxGraph(file_obj)
        self.restoreGraph()
        self.GUI.graphDisplay.Show() # In case we are hidden
        self.GUI.graphDisplay.ShowGraph(self.graph, stripPath(self.graphFileName))
        self.GUI.graphDisplay.RegisterGraphInformer(WeightedGraphInformer(self.graph))
        self.GUI.graphDisplay.UpdateScrollRegion(auto=1) 
Example 46
Project: kotori   Author: daq-tools   File: common.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_skip_key(self, *args):
        key_parts = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                key_parts.append(arg)
            elif isinstance(arg, types.DictionaryType):
                key_parts.append(','.join(arg.keys()))
        skip_key = '-'.join(key_parts)
        return skip_key 
Example 47
Project: kotori   Author: daq-tools   File: util.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def handleFailure(f, request=None):
    """
    Handle failure in callback chain, log and respond with traceback.

    See also:
    https://twistedmatrix.com/documents/16.0.0/core/howto/defer.html#errbacks
    """
    if f.type is Error:
        if request:
            request.setResponseCode(int(f.value.status))

        if hasattr(f.value, 'with_traceback'):
            f.with_traceback = f.value.with_traceback

        msg = None
        if isinstance(f.value.response, Failure):
            msg = f.value.response.getErrorMessage()
        elif type(f.value.response) in types.StringTypes:
            msg = f.value.response
        request.messages.append({'type': 'error', 'message': msg})

    else:
        if request:
            request.setResponseCode(http.INTERNAL_SERVER_ERROR)
            request.setHeader('Content-Type', 'text/plain; charset=utf-8')
        f.with_traceback = True

    if hasattr(f, 'with_traceback') and f.with_traceback:

        traceback = f.getTraceback()
        log.error(traceback)
        #f.trap(RuntimeError)
        request.write(traceback.encode('utf-8')) 
Example 48
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 5 votes vote down vote up
def OSCBlob(next):
	"""Convert a string into an OSC Blob.
	An OSC-Blob is a binary encoded block of data, prepended by a 'size' (int32).
	The size is always a mutiple of 4 bytes. 
	The blob ends with 0 to 3 zero-bytes ('\x00') 
	"""

	if type(next) in types.StringTypes:
		OSCblobLength = math.ceil((len(next)) / 4.0) * 4
		binary = struct.pack(">i%ds" % (OSCblobLength), OSCblobLength, next)
	else:
		binary = ""

	return binary 
Example 49
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 5 votes vote down vote up
def parseFilterStr(args):
	"""Convert Message-Filter settings in '+<addr> -<addr> ...' format to a dict of the form
	{ '<addr>':True, '<addr>':False, ... } 
	Returns a list: ['<prefix>', filters]
	"""
	out = {}
	
	if type(args) in types.StringTypes:
		args = [args]
		
	prefix = None
	for arg in args:
		head = None
		for plus in arg.split('+'):
			minus = plus.split('-')
			plusfs = minus.pop(0).strip()
			if len(plusfs):
				plusfs = '/' + plusfs.strip('/')
			
			if (head == None) and (plusfs != "/*"):
				head = plusfs
			elif len(plusfs):
				if plusfs == '/*':
					out = { '/*':True }	# reset all previous filters
				else:
					out[plusfs] = True
				
			for minusfs in minus:
				minusfs = minusfs.strip()
				if len(minusfs):
					minusfs = '/' + minusfs.strip('/')
					if minusfs == '/*':
						out = { '/*':False }	# reset all previous filters
					else:
						out[minusfs] = False
				
		if prefix == None:
			prefix = head

	return [prefix, out] 
Example 50
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 5 votes vote down vote up
def _subscribe(self, data, client_address):
		"""Handle the actual subscription. the provided 'data' is concatenated together to form a
		'<host>:<port>[<prefix>] [<filter>] [...]' string, which is then passed to 
		parseUrlStr() & parseFilterStr() to actually retreive <host>, <port>, etc.
		
		This 'long way 'round' approach (almost) guarantees that the subscription works, 
		regardless of how the bits of the <url> are encoded in 'data'. 
		"""
		url = ""
		have_port = False
		for item in data:
			if (type(item) == types.IntType) and not have_port:
				url += ":%d" % item
				have_port = True
			elif type(item) in types.StringTypes:
				url += item

		(addr, tail) = parseUrlStr(url)
		(prefix, filters) = parseFilterStr(tail)
		
		if addr != None:
			(host, port) = addr
			if not host:
				host = client_address[0]
			if not port:
				port = client_address[1]
			addr = (host, port)
		else:
			addr = client_address
		
		self.client._setTarget(addr, prefix, filters)
	
		trg = self.client.getOSCTargetStr(addr)
		if trg[0] != None:
			reply = OSCMessage(self.info_prefix)
			reply.append(('target',) + trg)
			return reply