Python types.DictType() Examples

The following are code examples for showing how to use types.DictType(). 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: pyblish-win   Author: pyblish   File: Switchboard.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, initfile):
        self.__initfile = initfile
        self.__colordb = None
        self.__optiondb = {}
        self.__views = []
        self.__red = 0
        self.__green = 0
        self.__blue = 0
        self.__canceled = 0
        # read the initialization file
        fp = None
        if initfile:
            try:
                try:
                    fp = open(initfile)
                    self.__optiondb = marshal.load(fp)
                    if not isinstance(self.__optiondb, DictType):
                        print >> sys.stderr, \
                              'Problem reading options from file:', initfile
                        self.__optiondb = {}
                except (IOError, EOFError, ValueError):
                    pass
            finally:
                if fp:
                    fp.close() 
Example 2
Project: pyomni   Author: taxpon   File: WebdavClient.py    MIT License 6 votes vote down vote up
def writeProperties(self, properties, lockToken=None):
        """
        Sets or updates the given properties.
        
        @param lockToken: if the resource has been locked this is the lock token.
        @type  lockToken: L{LockToken}
        @param properties: a map from property names to a String or
                           DOM element value for each property to add or update.
        """
        assert isinstance(properties, types.DictType)
        assert lockToken == None or isinstance(lockToken, LockToken), \
                "Invalid lockToken argument %s" % type(lockToken)
        header = {}
        if lockToken:
            header = lockToken.toHeader()
        body = createUpdateBody(properties, self.defaultNamespace)
        response = self.connection.proppatch(self.path, body, header)
        if response.msr.errorCount > 0:
            raise WebdavError("Request failed: " + response.msr.reason, response.msr.code) 
Example 3
Project: kay-template   Author: yosukesuzuki   File: media_compiler.py    MIT License 6 votes vote down vote up
def equal_object_(a, b):
  if type(a) == types.DictType and type(b) == types.DictType:
    if len(a.keys()) != len(b.keys()):
      return False
    for k, v in a.iteritems():
      if k not in b:
        return False
      if not equal_object_(v, b[k]):
        return False
    return True
  elif type(a) in [types.ListType, types.TupleType] and \
        type(b) in [types.ListType, types.TupleType]:
    if len(a) != len(b):
      return False
    ia = iter(a)
    ib = iter(b)
    try:
      while True:
        if not equal_object_(ia.next(), ib.next()):
          return False
    except:
      pass
    return True
  else:
    return a == b 
Example 4
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 6 votes vote down vote up
def append(self, argument, typehint = None):
		"""Appends data to the bundle, creating an OSCMessage to encapsulate
		the provided argument unless this is already an OSCMessage.
		Any newly created OSCMessage inherits the OSCBundle's address at the time of creation.
		If 'argument' is an iterable, its elements will be encapsuated by a single OSCMessage.
		Finally, 'argument' can be (or contain) a dict, which will be 'converted' to an OSCMessage;
		  - if 'addr' appears in the dict, its value overrides the OSCBundle's address
		  - if 'args' appears in the dict, its value(s) become the OSCMessage's arguments
		"""
		if isinstance(argument, OSCMessage):
			binary = OSCBlob(argument.getBinary())
		else:
			msg = OSCMessage(self.address)
			if type(argument) == types.DictType:
				if 'addr' in argument:
					msg.setAddress(argument['addr'])
				if 'args' in argument:
					msg.append(argument['args'], typehint)
			else:
				msg.append(argument, typehint)
			
			binary = OSCBlob(msg.getBinary())

		self.message += binary
		self.typetags += 'b' 
Example 5
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 6
Project: oss-ftp   Author: aliyun   File: Switchboard.py    MIT License 6 votes vote down vote up
def __init__(self, initfile):
        self.__initfile = initfile
        self.__colordb = None
        self.__optiondb = {}
        self.__views = []
        self.__red = 0
        self.__green = 0
        self.__blue = 0
        self.__canceled = 0
        # read the initialization file
        fp = None
        if initfile:
            try:
                try:
                    fp = open(initfile)
                    self.__optiondb = marshal.load(fp)
                    if not isinstance(self.__optiondb, DictType):
                        print >> sys.stderr, \
                              'Problem reading options from file:', initfile
                        self.__optiondb = {}
                except (IOError, EOFError, ValueError):
                    pass
            finally:
                if fp:
                    fp.close() 
Example 7
Project: dkodi   Author: dknlght   File: jsonrpc.py    GNU General Public License v2.0 6 votes vote down vote up
def isbatch(result):
    if type(result) not in (types.ListType, types.TupleType):
        return False
    if len(result) < 1:
        return False
    if type(result[0]) is not types.DictType:
        return False
    if 'jsonrpc' not in result[0].keys():
        return False
    try:
        version = float(result[0]['jsonrpc'])
    except ValueError:
        raise ProtocolError('"jsonrpc" key must be a float(able) value.')
    if version < 2:
        return False
    return True 
Example 8
Project: dkodi   Author: dknlght   File: SimpleJSONRPCServer.py    GNU General Public License v2.0 6 votes vote down vote up
def validate_request(request):
    if type(request) is not types.DictType:
        fault = Fault(
 -32600, 'Request must be {}, not %s.' % type(request)
        )
        return fault
    rpcid = request.get('id', None)
    version = get_version(request)
    if not version:
        fault = Fault(-32600, 'Request %s invalid.' % request, rpcid=rpcid)
        return fault        
    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:
        fault = Fault(
 -32600, 'Invalid request parameters or method.', rpcid=rpcid
        )
        return fault
    return True 
Example 9
Project: emulated-sdn-application   Author: tranlyvu   File: base.py    Apache License 2.0 6 votes vote down vote up
def _flatten(l, max_level=10):
    """Generator function going deep in tree-like structures
    (i.e. dicts in dicts or lists in lists etc.) and returning all elements as
    a flat list. It's flattening only lists and dicts which are subclasses of
    RdyToFlattenCollection. Regular lists and dicts are treated as a
    single items.

    :param l: some iterable to be flattened
    :return: flattened iterator
    """
    if max_level >= 0:
        _iter = l.values() if isinstance(l, types.DictType) else l
        for el in _iter:
            if isinstance(el, RdyToFlattenCollection):
                for sub in _flatten(el, max_level=max_level - 1):
                    yield sub
            else:
                yield el
    else:
        yield l 
Example 10
Project: ocs-bttrack   Author: stevenshiau   File: btformats.py    MIT License 6 votes vote down vote up
def check_message(message):
    if type(message) != DictType:
        raise ValueError
    check_info(message.get('info'))
    if not (message.has_key('announce') or message.has_key('announce-list')):
        raise ValueError, 'no announce'
    if type(message.get('announce', "")) != StringType:
        raise ValueError, 'bad announce'
    if message.has_key('announce-list'):
        try:
            ll = message.get('announce-list')
            assert type(ll) == ListType
            for l in ll:
                assert type(l) == ListType
                for s in l:
                    assert type(s) == StringType
        except:
            raise ValueError, 'bad announce-list' 
Example 11
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 12
Project: pyblish-win   Author: pyblish   File: optparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 13
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 14
Project: spider   Author: LaveyD   File: select_result.py    GNU General Public License v3.0 5 votes vote down vote up
def strip_null(arg,null=None):
    """
        strip list,set,tuple,dict null item.

        @param:
            arg:the variable to strip null
            null:the null definition,if it is None,then use NULL as the null

        if arg is list,then strip the null item,return the new list
        if arg is tuple,then strip the null item,return the new tuple
        if arg is set,then strip the null item,return the new set
        if arg is dict,then strip the dict item which value is null.return the new dict
    """
    if null is None:
        null = NULL

    if type(arg) is types.ListType:
        return [i for i in arg if i not in null]
    elif type(arg) is types.TupleType:
        return tuple([i for i in arg if i not in null])
    elif type(arg) is type(set()):
        return arg.difference(set(null))
    elif type(arg) is types.DictType:
        return {key:value for key,value in arg.items() if value not in null}

    return arg 
Example 15
Project: vulscan   Author: vulscanteam   File: poc.py    MIT License 5 votes vote down vote up
def success(self, result):
        assert isinstance(result, types.DictType)
        self.status = OUTPUT_STATUS.SUCCESS
        self.result = result 
Example 16
Project: att   Author: Centre-Alt-Rendiment-Esportiu   File: c_spec.py    GNU General Public License v3.0 5 votes vote down vote up
def init_info(self):
        scxx_converter.init_info(self)
        self.type_name = 'dict'
        self.check_func = 'PyDict_Check'
        self.c_type = 'py::dict'
        self.return_type = 'py::dict'
        self.to_c_return = 'py::dict(py_obj)'
        self.matching_types = [types.DictType]
        # ref counting handled by py::dict
        self.use_ref_count = 0

#----------------------------------------------------------------------------
# Instance Converter
#---------------------------------------------------------------------------- 
Example 17
Project: SherpaHighLevel   Author: Shedino   File: xmlifODict.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update(self, dictOrTuple):
        if isinstance(dictOrTuple, DictType):
            itemList = dictOrTuple.items()
        else:
            itemList = dictOrTuple
        for key, val in itemList:
            self.__setitem__(key,val) 
Example 18
Project: SherpaHighLevel   Author: Shedino   File: xmlifODict.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def update(self, dictOrTuple):
        if isinstance(dictOrTuple, DictType):
            itemList = dictOrTuple.items()
        else:
            itemList = dictOrTuple
        for key, val in itemList:
            self.__setitem__(key,val) 
Example 19
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 20
Project: automatron   Author: madflojo   File: monitoring.py    Apache License 2.0 5 votes vote down vote up
def schedule(scheduler, runbook, target, config, dbc, logger):
    ''' Setup schedule for new runbooks and targets '''
    # Default schedule (every minute)
    task_schedule = {
        'second' : 0,
        'minute' : '*',
        'hour' : '*',
        'day' : '*',
        'month' : '*',
        'day_of_week' : '*'
    }
    # If schedule is present override default
    if 'schedule' in target['runbooks'][runbook].keys():
        if type(target['runbooks'][runbook]['schedule']) == types.DictType:
            for key in target['runbooks'][runbook]['schedule'].keys():
                task_schedule[key] = target['runbooks'][runbook]['schedule'][key]
        elif type(target['runbooks'][runbook]['schedule']) == types.StringType:
            breakdown = target['runbooks'][runbook]['schedule'].split(" ")
            task_schedule = {
                'second' : 0,
                'minute' : breakdown[0],
                'hour' : breakdown[1],
                'day' : breakdown[2],
                'month' :  breakdown[3],
                'day_of_week' : breakdown[4]
            }
    cron = CronTrigger(
        second=task_schedule['second'],
        minute=task_schedule['minute'],
        hour=task_schedule['hour'],
        day=task_schedule['day'],
        month=task_schedule['month'],
        day_of_week=task_schedule['day_of_week'],
    )
    return scheduler.add_job(
        monitor,
        trigger=cron,
        args=[runbook, target, config, dbc, logger]
    ) 
Example 21
Project: ironpython2   Author: IronLanguages   File: optparse.py    Apache License 2.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 22
Project: ironpython2   Author: IronLanguages   File: optparse.py    Apache License 2.0 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 23
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 24
Project: PyMoCap   Author: markkorput   File: OSC.py    MIT License 5 votes vote down vote up
def append(self, argument, typehint=None):
		"""Appends data to the message, updating the typetags based on
		the argument's type. If the argument is a blob (counted
		string) pass in 'b' as typehint.
		'argument' may also be a list or tuple, in which case its elements
		will get appended one-by-one, all using the provided typehint
		"""
		if type(argument) == types.DictType:
			argument = argument.items()
		elif isinstance(argument, OSCMessage):
			raise TypeError("Can only append 'OSCMessage' to 'OSCBundle'")
		
		if hasattr(argument, '__iter__'):
			for arg in argument:
				self.append(arg, typehint)
			
			return
		
		if typehint == 'b':
			binary = OSCBlob(argument)
			tag = 'b'
		elif typehint == 't':
			binary = OSCTimeTag(argument)
			tag = 't'
		else:
			tag, binary = OSCArgument(argument, typehint)

		self.typetags += tag
		self.message += binary 
Example 25
Project: IronHydra   Author: microdee   File: optparse.py    MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 26
Project: IronHydra   Author: microdee   File: optparse.py    MIT License 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 27
Project: air-quick-fix   Author: jamesward   File: __init__.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def addService(self, service, name=None, description=None,
        authenticator=None, expose_request=None, preprocessor=None):
        """
        Adds a service to the gateway.

        @param service: The service to add to the gateway.
        @type service: C{callable}, class instance, or a module
        @param name: The name of the service.
        @type name: C{str}
        @raise RemotingError: Service already exists.
        @raise TypeError: C{service} must be C{callable} or a module.
        """
        if isinstance(service, (int, long, float, basestring)):
            raise TypeError, "service cannot be a scalar value"

        allowed_types = (types.ModuleType, types.FunctionType, types.DictType,
            types.MethodType, types.InstanceType, types.ObjectType)

        if not callable(service) and not isinstance(service, allowed_types):
            raise TypeError, "service must be callable, a module, or an object"

        if name is None:
            # TODO: include the module in the name
            if isinstance(service, (type, types.ClassType)):
                name = service.__name__
            elif isinstance(service, types.FunctionType):
                name = service.func_name
            elif isinstance(service, types.ModuleType):
                name = service.__name__
            else:
                name = str(service)

        if name in self.services:
            raise remoting.RemotingError, "Service %s already exists" % name

        self.services[name] = ServiceWrapper(service, description,
            authenticator, expose_request, preprocessor) 
Example 28
Project: lbryum-server   Author: lbryio   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 29
Project: aws-lambda-runtime-pypy   Author: uscheller   File: pygame_console.py    Apache License 2.0 5 votes vote down vote up
def get_event(self, block=1):
        """Return an Event instance.  Returns None if |block| is false
        and there is no event pending, otherwise waits for the
        completion of an event."""
        while 1:
            if self.event_queue:
                return self.event_queue.pop(0)
            elif block:
                pyg_event = pygame.event.wait()
            else:
                pyg_event = pygame.event.poll()
                if pyg_event.type == NOEVENT:
                    return

            if pyg_event.key in modcolors:
                continue

            k, c = self.tr_event(pyg_event)
            self.cmd_buf += c.encode('ascii', 'replace')
            self.k = k

            if not isinstance(k, types.DictType):
                e = Event(k, self.cmd_buf, [])
                self.k = self.keymap
                self.cmd_buf = ''
                return e 
Example 30
Project: Computable   Author: ktraunmueller   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        scxx_converter.init_info(self)
        self.type_name = 'dict'
        self.check_func = 'PyDict_Check'
        self.c_type = 'py::dict'
        self.return_type = 'py::dict'
        self.to_c_return = 'py::dict(py_obj)'
        self.matching_types = [types.DictType]
        # ref counting handled by py::dict
        self.use_ref_count = 0

#----------------------------------------------------------------------------
# Instance Converter
#---------------------------------------------------------------------------- 
Example 31
Project: Computable   Author: ktraunmueller   File: optparse.py    MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 32
Project: Computable   Author: ktraunmueller   File: optparse.py    MIT License 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 33
Project: oss-ftp   Author: aliyun   File: optparse.py    MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 34
Project: oss-ftp   Author: aliyun   File: optparse.py    MIT License 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 35
Project: poker   Author: surgebiswas   File: c_spec.py    MIT License 5 votes vote down vote up
def init_info(self):
        scxx_converter.init_info(self)
        self.type_name = 'dict'
        self.check_func = 'PyDict_Check'
        self.c_type = 'py::dict'
        self.return_type = 'py::dict'
        self.to_c_return = 'py::dict(py_obj)'
        self.matching_types = [types.DictType]
        # ref counting handled by py::dict
        self.use_ref_count = 0

#----------------------------------------------------------------------------
# Instance Converter
#---------------------------------------------------------------------------- 
Example 36
Project: Toontown-Source   Author: ksmit799   File: LevelSpec.py    MIT License 5 votes vote down vote up
def __init__(self, spec = None, scenario = 0):
        newSpec = 0
        if type(spec) is types.ModuleType:
            if __dev__:
                reload(spec)
            self.specDict = spec.levelSpec
            if __dev__:
                self.setFilename(spec.__file__)
        elif type(spec) is types.DictType:
            self.specDict = spec
        elif spec is None:
            if __dev__:
                newSpec = 1
                self.specDict = {'globalEntities': {},
                 'scenarios': [{}]}
        self.entId2specDict = {}
        self.entId2specDict.update(list2dict(self.getGlobalEntIds(), value=self.privGetGlobalEntityDict()))
        for i in range(self.getNumScenarios()):
            self.entId2specDict.update(list2dict(self.getScenarioEntIds(i), value=self.privGetScenarioEntityDict(i)))

        self.setScenario(scenario)
        if __dev__:
            if newSpec:
                import EntityTypes
                import EntityTypeRegistry
                etr = EntityTypeRegistry.EntityTypeRegistry(EntityTypes)
                self.setEntityTypeReg(etr)
                entId = LevelConstants.UberZoneEntId
                self.insertEntity(entId, 'zone')
                self.doSetAttrib(entId, 'name', 'UberZone')
                entId = LevelConstants.LevelMgrEntId
                self.insertEntity(entId, 'levelMgr')
                self.doSetAttrib(entId, 'name', 'LevelMgr')
                entId = LevelConstants.EditMgrEntId
                self.insertEntity(entId, 'editMgr')
                self.doSetAttrib(entId, 'name', 'EditMgr')
        return 
Example 37
Project: dkodi   Author: dknlght   File: jsonrpc.py    GNU General Public License v2.0 5 votes vote down vote up
def check_for_errors(result):
    if not result:
        # Notification
        return result
    if type(result) is not types.DictType:
        raise TypeError('Response is not a dict.')
    if 'jsonrpc' in result.keys() and float(result['jsonrpc']) > 2.0:
        raise NotImplementedError('JSON-RPC version not yet supported.')
    if 'result' not in result.keys() and 'error' not in result.keys():
        raise ValueError('Response does not have a result or error key.')
    if 'error' in result.keys() and result['error'] != None:
        code = result['error']['code']
        message = result['error']['message']
        raise ProtocolError((code, message))
    return result 
Example 38
Project: pykit   Author: bsc-s2   File: strutil.py    MIT License 5 votes vote down vote up
def _get_key_and_headers(keys, rows):

    if keys is None:

        if len(rows) == 0:
            keys = []
        else:
            r0 = rows[0]

            if type(r0) == types.DictType:
                keys = r0.keys()
                keys.sort()
            elif type(r0) in listtype:
                keys = [i for i in range(len(r0))]
            else:
                keys = ['']

    _keys = []
    column_headers = []

    for k in keys:

        if type(k) not in listtype:
            k = [k, k]

        _keys.append(k[0])
        column_headers.append(str(k[1]))

    return _keys, column_headers 
Example 39
Project: hacker-scripts   Author: restran   File: optparse.py    MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 40
Project: hacker-scripts   Author: restran   File: optparse.py    MIT License 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 41
Project: hacker-scripts   Author: restran   File: optparse.py    MIT License 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 42
Project: hacker-scripts   Author: restran   File: optparse.py    MIT License 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 43
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 44
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 45
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 46
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 47
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 48
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 49
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 50
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def _check_callback(self):
        if self.action == "callback":
            if not hasattr(self.callback, '__call__'):
                raise OptionError(
                    "callback not callable: %r" % self.callback, self)
            if (self.callback_args is not None and
                type(self.callback_args) is not types.TupleType):
                raise OptionError(
                    "callback_args, if supplied, must be a tuple: not %r"
                    % self.callback_args, self)
            if (self.callback_kwargs is not None and
                type(self.callback_kwargs) is not types.DictType):
                raise OptionError(
                    "callback_kwargs, if supplied, must be a dict: not %r"
                    % self.callback_kwargs, self)
        else:
            if self.callback is not None:
                raise OptionError(
                    "callback supplied (%r) for non-callback option"
                    % self.callback, self)
            if self.callback_args is not None:
                raise OptionError(
                    "callback_args supplied for non-callback option", self)
            if self.callback_kwargs is not None:
                raise OptionError(
                    "callback_kwargs supplied for non-callback option", self) 
Example 51
Project: godot-zeronet-plugin   Author: zam-org   File: optparse.py    GNU General Public License v2.0 5 votes vote down vote up
def __cmp__(self, other):
        if isinstance(other, Values):
            return cmp(self.__dict__, other.__dict__)
        elif isinstance(other, types.DictType):
            return cmp(self.__dict__, other)
        else:
            return -1 
Example 52
Project: qgis-wps4server   Author: 3liz   File: InAndOutputs.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, identifier, title, abstract=None,
                 metadata=[], minOccurs=1, maxOccurs=1,
                 maxmegabites=None, formats=[{"mimeType": None}]):
        """Class constructor"""

        Input.__init__(self, identifier, title, abstract=abstract,
                       metadata=metadata, minOccurs=minOccurs, maxOccurs=maxOccurs, type="ComplexValue")
        # If maxmegabites not present, then it will be set in
        # consolidateInputs()
        if maxmegabites:
            self.maxFileSize = float(maxmegabites) * 1024 * 1024
        else:
            self.maxFileSize = None

        if type(formats) == types.StringType:
            formats = [{"mimeType": formats, "encoding": None, "schema": None}]
        elif type(formats) == types.DictType:
            formats = [formats]

        for format in formats:
            if not "encoding" in format.keys():
                format["encoding"] = None
            if not "schema" in format.keys():
                format["schema"] = None

        self.formats = formats
        self.format = {}
        try:
            self.ms = magic.open(magic.MAGIC_MIME)
            self.ms.load()
        except:
            pass

        return 
Example 53
Project: qgis-wps4server   Author: 3liz   File: InAndOutputs.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, identifier, title, abstract=None,
                 metadata=[], formats=[{"mimeType": None}],
                 asReference=False, projection=None, bbox=None,
                 useMapscript=False, useQgisServer=False):
        """Class constructor"""
        Output.__init__(self, identifier, title, abstract=abstract,
                        metadata=metadata, type="ComplexValue", asReference=asReference)

        if type(formats) == types.StringType:
            formats = [{"mimeType": formats, "encoding": None, "schema": None}]
        elif type(formats) == types.DictType:
            formats = [formats]

        for format in formats:
            if not "encoding" in format.keys():
                format["encoding"] = None
            if not "schema" in format.keys():
                format["schema"] = None

        self.formats = formats
        self.format = {}

        self.projection = projection
        self.bbox = bbox
        self.useMapscript = useMapscript
        self.useQgisServer = useQgisServer
        try:
            self.ms = magic.open(magic.MAGIC_MIME)
            self.ms.load()
        except:
            pass

        return 
Example 54
Project: PokemonGo-SlackBot   Author: rubenmak   File: pokeslack.py    MIT License 5 votes vote down vote up
def merge(x,y):
    # store a copy of x, but overwrite with y's values where applicable
    merged = dict(x,**y)

    xkeys = x.keys()

    # if the value of merged[key] was overwritten with y[key]'s value
    # then we need to put back any missing x[key] values
    for key in xkeys:
        # if this key is a dictionary, recurse
        if type(x[key]) is types.DictType and y.has_key(key):
            merged[key] = merge(x[key],y[key])

    return merged 
Example 55
Project: scanomatic   Author: Scan-o-Matic   File: data_api.py    GNU General Public License v3.0 5 votes vote down vote up
def json_data(data):

    if data is None:
        return None
    elif hasattr(data, "tolist"):
        return json_data(data.tolist())
    elif isinstance(data, ListType):
        return [json_data(d) for d in data]
    elif isinstance(data, DictType):
        return {json_data(k): json_data(data[k]) for k in data}
    elif isinstance(data, Enum):
        return data.name
    else:
        return data 
Example 56
Project: scanomatic   Author: Scan-o-Matic   File: analysis_factories.py    GNU General Public License v3.0 5 votes vote down vote up
def deep_to_dict(cls, model_or_data):

        if isinstance(model_or_data, cls.MODEL):
            return {
                k: cls.deep_to_dict(model_or_data[k]) for k in
                cls.to_dict(model_or_data)}
        elif isinstance(model_or_data, DictType):
            return {
                k: cls.deep_to_dict(model_or_data[k]) for k in model_or_data}
        elif isinstance(model_or_data, ListType):
            return [cls.deep_to_dict(v) for v in model_or_data]
        else:
            return model_or_data 
Example 57
Project: OpenXR-SDK-Source   Author: KhronosGroup   File: pyjsontestrunner.py    Apache License 2.0 5 votes vote down vote up
def valueTreeToString(fout, value, path = '.'):
    ty = type(value) 
    if ty  is types.DictType:
        fout.write('%s={}\n' % path)
        suffix = path[-1] != '.' and '.' or ''
        names = value.keys()
        names.sort()
        for name in names:
            valueTreeToString(fout, value[name], path + suffix + name)
    elif ty is types.ListType:
        fout.write('%s=[]\n' % path)
        for index, childValue in zip(xrange(0,len(value)), value):
            valueTreeToString(fout, childValue, path + '[%d]' % index)
    elif ty is types.StringType:
        fout.write('%s="%s"\n' % (path,value))
    elif ty is types.IntType:
        fout.write('%s=%d\n' % (path,value))
    elif ty is types.FloatType:
        fout.write('%s=%.16g\n' % (path,value))
    elif value is True:
        fout.write('%s=true\n' % path)
    elif value is False:
        fout.write('%s=false\n' % path)
    elif value is None:
        fout.write('%s=null\n' % path)
    else:
        assert False and "Unexpected value type" 
Example 58
Project: eve-metrics   Author: ccpgames   File: default.py    MIT License 5 votes vote down vote up
def TestLdap():
    # http://pypi.python.org/pypi/python-ldap/
    txt = ""


    name = request.vars.name or ""
    Base = "dc=ccp,dc=ad,dc=local"
    Scope = ldap.SCOPE_SUBTREE
    Filter = "(&(objectClass=user)(mailNickname=%s*))" % (name)
    attrs = ["displayname", "mail", "memberof", "name", "UserAccountControl", "thumbnailPhoto"]
    attrs = ["displayname", "mail", "url", "mailNickname", "uSNCreated"]
    attrs = ["mailNickname", "uSNCreated", "displayName"]
    #attrs = ["*"]

    r = l.search(Base, Scope, Filter, attrs)
    Type,user = l.result(r,60)
    allUsers = {}
    for u in user:
        lst = []
        try:
            for a in u[1].values():
                lst.append(a[0])
        except:
            continue
        uid = int(lst[1])
        if uid in allUsers:
            print "FUCK!", uid, lst[0], allUsers[uid]
        else:
            print "new guy", lst[0]
        allUsers[uid] = lst[0]
    Name,attrs = user[0]
    txt += "<img src=\"http://myccp/User Photos/Profile Pictures/ccp_%s_LThumb.jpg\">" % name
    if type(attrs) == types.DictType:
        for k, v in attrs.iteritems():
            if "url" in k and 0:
                txt += "<img src=\"%s\"><br>" % v[0]
            else:
                txt += "%s > %s<br><Br>" % (k, v[0][:128]) 
    return txt 
Example 59
Project: ttk   Author: tarsqi   File: FSA-org.py    Apache License 2.0 5 votes vote down vote up
def labelMatches(label, input):
        #log( "\n\nLABEL MATCHES:"+label+"  "+ str(input)+"?")
        #print "LABEL MATCHES:"+label+"  "+ str(input)+"?"
        if (type(label) is StringType and (label[0] == '{' or label[-1] == '}')):
                """Pattern expression has been given in a Python dictionary format """
                label = labelDict(label)
                #print "LABEL in FSA (1): "+str(label)
                #log("\tMATCH (0.1), STRING:"+str(input))
                #print "\t\tINPUT class name: "+str(input.__class__.__name__)
                if (type(input) is InstanceType and
                    input.__class__.__name__ in ['Constituent', 'Chunk', 'NounChunk',
                                                 'VerbChunk', 'Token', 'AdjectiveToken',
                                                 'EventTag', 'TimexTag']):
                        """Specific for Evita"""
                        #print "EVITA: LABEL in FSA (2): "+str(label)
                        return input._matchChunk(label)
                elif type(input) is DictType:
                        """ Open to other dictionary-based object matching applications"""
                        #print "NON-EVITA: LABEL in FSA (2): "+str(label)
                        return matchDict(label, input)
                else:
                        #print "LABEL:", label, "\nINPUT:", input.nodeType
                        raise "ERROR: possibly label is in dict format, but not the input"
        elif type(label) == InstanceType and hasattr(label, 'matches'):
                #debugFile.write("\n\tMATCH (1)")
                #print "\n\tMATCH (1)"
                return label.matches(input)
        else:
                #debugFile.write("\n\tMATCH (2)")
                #print "\n\tMATCH (2)"
                return label == input 
Example 60
Project: ttk   Author: tarsqi   File: FSA.py    Apache License 2.0 5 votes vote down vote up
def labelMatches(label, input):
        #log( "\n\nLABEL MATCHES:"+label+"  "+ str(input)+"?")
        #print "LABEL MATCHES: "+label+"  "+ str(input)+"?"
        #logger.out('label =', label)
        #logger.out('input =', input.__class__.__name__)
        if (type(label) is StringType and (label[0] == '{' or label[-1] == '}')):
                """Pattern expression has been given in a Python dictionary format """
                #print ">>> LABEL %s is string with curly brackets" % label
                label = labelDict(label)
                #print "LABEL in FSA (1): "+str(label)
                #log("\tMATCH (0.1), STRING:"+str(input))
                #print "\t\tINPUT class name: "+str(input.__class__.__name__)
                if (type(input) is InstanceType and
                    input.__class__.__name__ in ['Constituent', 'Chunk', 'NounChunk',
                                                 'VerbChunk', 'Token', 'AdjectiveToken',
                                                 'EventTag', 'TimexTag']):
                        """Specific for Evita"""
                        #print ">>> input is InstanceType and class is in Constituent...."
                        #print "EVITA: LABEL in FSA (2): "+str(label)
                        #print ">>> input is ", input
                        #logger.out('forwarding to input.matchConstituent')
                        return input.matchConstituent(label)
                elif type(input) is DictType:
                        """ Open to other dictionary-based object matching applications"""
                        #print "NON-EVITA: LABEL in FSA (2): "+str(label)
                        #logger.out('forwarding to _matchDict')
                        return matchDict(label, input)
                else:
                        #print "LABEL:", label, "\nINPUT:", input.nodeType
                        raise "ERROR: possibly label is in dict format, but not the input"
        elif type(label) == InstanceType and hasattr(label, 'matches'):
                #debugFile.write("\n\tMATCH (1)")
                #print "\n\tMATCH (1)"
                #logger.out('MATCH (1)')
                return label.matches(input)
        else:
                #debugFile.write("\n\tMATCH (2)")
                #print "\n\tMATCH (2)"
                #logger.out('MATCH (2)')
                return label == input 
Example 61
Project: libesocial   Author: qualitaocupacional   File: xml.py    Apache License 2.0 5 votes vote down vote up
def recursive_add_element(root, element, nsmap_default={}):
    for ele_k in element:
        if isinstance(element[ele_k], types.ListType):
            child = add_element(root, None, ele_k, ns=nsmap_default)
            for ele_i in element[ele_k]:
                recursive_add_element(child, ele_i, nsmap_default=nsmap_default)
        elif isinstance(element[ele_k], types.DictType):
            attrs, nsmap, value_attr = _check_attrs(element[ele_k])
            if value_attr:
                add_element(root, None, ele_k, text=value_attr, ns=nsmap or nsmap_default, **attrs if attrs else {})
            else:
                child = add_element(root, None, ele_k, ns=nsmap or nsmap_default, **attrs if attrs else {})
                recursive_add_element(child, element[ele_k], nsmap_default=nsmap_default)
        else:
            add_element(root, None, ele_k, text=element[ele_k], ns=nsmap_default) 
Example 62
Project: ocs-bttrack   Author: stevenshiau   File: btformats.py    MIT License 5 votes vote down vote up
def check_peers(message):
    if type(message) != DictType:
        raise ValueError
    if message.has_key('failure reason'):
        if type(message['failure reason']) != StringType:
            raise ValueError
        return
    peers = message.get('peers')
    if type(peers) == ListType:
        for p in peers:
            if type(p) != DictType:
                raise ValueError
            if type(p.get('ip')) != StringType:
                raise ValueError
            port = p.get('port')
            if type(port) not in ints or p <= 0:
                raise ValueError
            if p.has_key('peer id'):
                id = p['peer id']
                if type(id) != StringType or len(id) != 20:
                    raise ValueError
    elif type(peers) != StringType or len(peers) % 6 != 0:
        raise ValueError
    interval = message.get('interval', 1)
    if type(interval) not in ints or interval <= 0:
        raise ValueError
    minint = message.get('min interval', 1)
    if type(minint) not in ints or minint <= 0:
        raise ValueError
    if type(message.get('tracker id', '')) != StringType:
        raise ValueError
    npeers = message.get('num peers', 0)
    if type(npeers) not in ints or npeers < 0:
        raise ValueError
    dpeers = message.get('done peers', 0)
    if type(dpeers) not in ints or dpeers < 0:
        raise ValueError
    last = message.get('last', 0)
    if type(last) not in ints or last < 0:
        raise ValueError 
Example 63
Project: SLiPy   Author: glentner   File: mwrfits.py    GNU General Public License v2.0 4 votes vote down vote up
def mwrfits(filename, arraylist, namelist=None, header=None):
	""" 
	Writes the list of numpy.arrays arraylist as a FITS table filename
	using namelist as list of names. 
	Arraylist can be dictionary with arrays as values and names as keys. 
	Also Arraylist can be numpy-record-array.
	Example:
	mwrfits('/tmp/xx.fits',[arr,arr1],['X','Y'])
	Or :
	mwrfits('test.fits',{'X':arr,'Y':arr1})
	Or:
	data = numpy.zeros((4,),dtype=[('run','i4'),('rerun','f8'),('zz','b')])
	mwfits('test1.fits',data)
	
	Keep in mind that when you used a dictionary, the order of columns in the
	fits file is not guaranteed
	"""
	tmplist=[]
	if isinstance(arraylist,numpy.ndarray):
		if arraylist.dtype.type is numpy.void:
			iter=itertools.izip(arraylist.dtype.names, itertools.imap (arraylist.__getitem__ , arraylist.dtype.names))
	else:
		if isinstance(arraylist,types.ListType):
			iter= zip(namelist, arraylist)
		elif isinstance(arraylist,types.DictType):
			iter= arraylist.iteritems()

	for name, arr in iter:
		if arr.dtype.type==numpy.int8:
			format='I'
		elif arr.dtype.type==numpy.int16:
			format='I'
		elif arr.dtype.type==numpy.int32:
			format='J'
		elif arr.dtype.type==numpy.int64:
			format='K'
		elif arr.dtype.type==numpy.float32:
			format='E'
		elif arr.dtype.type==numpy.float64:
			format='D'
		elif arr.dtype.type==numpy.string_:
			format='%dA'%arr.dtype.itemsize
		else:
			raise Exception("Oops unknown datatype %s"%arr.dtype)
		tmplist.append(pyfits.Column(name=name, array=arr, format=format))
	hdu = pyfits.new_table(tmplist)
	hdu.writeto(filename,clobber=True) 
Example 64
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 65
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 66
Project: stock_monitor   Author: icemoon1987   File: myjson.py    GNU General Public License v2.0 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 67
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 68
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 69
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 70
Project: talklog   Author: gashero   File: json.py    MIT License 4 votes vote down vote up
def _write(self, obj):
        ty = type(obj)
        if ty is types.DictType:
            n = len(obj)
            self._append("{")
            for k, v in obj.items():
                self._write(k)
                self._append(":")
                self._write(v)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("}")
        elif ty is types.ListType or ty is types.TupleType:
            n = len(obj)
            self._append("[")
            for item in obj:
                self._write(item)
                n = n - 1
                if n > 0:
                    self._append(",")
            self._append("]")
        elif ty is types.StringType or ty is types.UnicodeType:
            self._append('"')
	    obj = obj.replace('\\', r'\\')
            if self._escaped_forward_slash:
                obj = obj.replace('/', r'\/')
	    obj = obj.replace('"', r'\"')
	    obj = obj.replace('\b', r'\b')
	    obj = obj.replace('\f', r'\f')
	    obj = obj.replace('\n', r'\n')
	    obj = obj.replace('\r', r'\r')
	    obj = obj.replace('\t', r'\t')
            self._append(obj)
            self._append('"')
        elif ty is types.IntType or ty is types.LongType:
            self._append(str(obj))
        elif ty is types.FloatType:
            self._append("%f" % obj)
        elif obj is True:
            self._append("true")
        elif obj is False:
            self._append("false")
        elif obj is None:
            self._append("null")
        else:
            raise WriteException, "Cannot write in JSON: %s" % repr(obj) 
Example 71
Project: Tinychat-Bot--Discontinued   Author: Tinychat   File: __init__.py    MIT License 4 votes vote down vote up
def addService(self, service, name=None, description=None,
                   authenticator=None, expose_request=None, preprocessor=None):
        """
        Adds a service to the gateway.

        @param service: The service to add to the gateway.
        @type service: C{callable}, class instance, or a module
        @param name: The name of the service.
        @type name: C{str}
        @raise pyamf.remoting.RemotingError: Service already exists.
        @raise TypeError: C{service} cannot be a scalar value.
        @raise TypeError: C{service} must be C{callable} or a module.
        """
        if isinstance(service, (int, long, float, basestring)):
            raise TypeError("Service cannot be a scalar value")

        allowed_types = (
            types.ModuleType,
            types.FunctionType,
            types.DictType,
            types.MethodType,
            types.InstanceType,
            types.ObjectType,
        )

        if not python.callable(service) and \
                not isinstance(service, allowed_types):
            raise TypeError("Service must be a callable, module, or an object")

        if name is None:
            # TODO: include the module in the name
            if isinstance(service, (type, types.ClassType)):
                name = service.__name__
            elif isinstance(service, types.FunctionType):
                name = service.func_name
            elif isinstance(service, types.ModuleType):
                name = service.__name__
            else:
                name = str(service)

        if name in self.services:
            raise remoting.RemotingError("Service %s already exists" % name)

        self.services[name] = ServiceWrapper(
            service,
            description,
            authenticator,
            expose_request,
            preprocessor
        ) 
Example 72
Project: weevely3-stealth   Author: edibledinos   File: prettify.py    GNU General Public License v3.0 4 votes vote down vote up
def tablify(data, table_border = True):

    # TODO: Check that is prettytable-0.7.2 that supports the
    # dynamic table columns number setting. Version 0.5 does not.

    output = ''

    # Empty outputs. False is probably a good output value
    if data and not data:
        output = ''
    else:

        table = prettytable.PrettyTable()

        # List outputs.
        if isinstance(data, (types.ListType, types.TupleType)):

            if len(data) > 0:

                columns_num = 1
                if isinstance(data[0], (types.ListType, types.TupleType)):
                    columns_num = len(data[0])

                for row in data:
                    if not row:
                        continue
                        
                    if isinstance(row, (types.ListType, types.TupleType)):
                        table.add_row(row)
                    else:
                        table.add_row([row])

        # Dict outputs are display as tables
        elif isinstance(data, types.DictType) and data:

            # Populate the rows
            randomitem = next(data.itervalues())
            if isinstance(randomitem, (types.ListType, types.TupleType)):
                for field in data:
                    table.add_row([field] + data[field])
            else:
                for field in data:
                    table.add_row([field, str(data[field])])

        # Else, try to stringify
        else:
            output = str(data)

        if not output:
            table.header = False
            table.align = 'l'
            table.border = table_border
            output = table.get_string()

    return output 
Example 73
Project: dkodi   Author: dknlght   File: jsonrpc.py    GNU General Public License v2.0 4 votes vote down vote up
def dumps(params=[], methodname=None, methodresponse=None, 
        encoding=None, rpcid=None, version=None, notify=None):
    """
    This differs from the Python implementation in that it implements 
    the rpcid argument since the 2.0 spec requires it for responses.
    """
    if not version:
        version = config.version
    valid_params = (types.TupleType, types.ListType, types.DictType)
    if methodname in types.StringTypes and \
            type(params) not in valid_params and \
            not isinstance(params, Fault):
        """ 
        If a method, and params are not in a listish or a Fault,
        error out.
        """
        raise TypeError('Params must be a dict, list, tuple or Fault ' +
                        'instance.')
    # Begin parsing object
    payload = Payload(rpcid=rpcid, version=version)
    if not encoding:
        encoding = 'utf-8'
    if type(params) is Fault:
        response = payload.error(params.faultCode, params.faultString)
        return jdumps(response, encoding=encoding)
    if type(methodname) not in types.StringTypes and methodresponse != True:
        raise ValueError('Method name must be a string, or methodresponse '+
                         'must be set to True.')
    if config.use_jsonclass == True:
        from jsonrpclib import jsonclass
        params = jsonclass.dump(params)
    if methodresponse is True:
        if rpcid is None:
            raise ValueError('A method response must have an rpcid.')
        response = payload.response(params)
        return jdumps(response, encoding=encoding)
    request = None
    if notify == True:
        request = payload.notify(methodname, params)
    else:
        request = payload.request(methodname, params)
    return jdumps(request, encoding=encoding) 
Example 74
Project: dkodi   Author: dknlght   File: jsonclass.py    GNU General Public License v2.0 4 votes vote down vote up
def load(obj):
    if type(obj) in string_types+numeric_types+value_types:
        return obj
    if type(obj) is types.ListType:
        return_list = []
        for entry in obj:
            return_list.append(load(entry))
        return return_list
    # Othewise, it's a dict type
    if '__jsonclass__' not in obj.keys():
        return_dict = {}
        for key, value in obj.iteritems():
            new_value = load(value)
            return_dict[key] = new_value
        return return_dict
    # It's a dict, and it's a __jsonclass__
    orig_module_name = obj['__jsonclass__'][0]
    params = obj['__jsonclass__'][1]
    if orig_module_name == '':
        raise TranslationError('Module name empty.')
    json_module_clean = re.sub(invalid_module_chars, '', orig_module_name)
    if json_module_clean != orig_module_name:
        raise TranslationError('Module name %s has invalid characters.' %
                               orig_module_name)
    json_module_parts = json_module_clean.split('.')
    json_class = None
    if len(json_module_parts) == 1:
        # Local class name -- probably means it won't work
        if json_module_parts[0] not in config.classes.keys():
            raise TranslationError('Unknown class or module %s.' %
                                   json_module_parts[0])
        json_class = config.classes[json_module_parts[0]]
    else:
        json_class_name = json_module_parts.pop()
        json_module_tree = '.'.join(json_module_parts)
        try:
            temp_module = __import__(json_module_tree)
        except ImportError:
            raise TranslationError('Could not import %s from module %s.' %
                                   (json_class_name, json_module_tree))
        json_class = getattr(temp_module, json_class_name)
    # Creating the object...
    new_obj = None
    if type(params) is types.ListType:
        new_obj = json_class(*params)
    elif type(params) is types.DictType:
        new_obj = json_class(**params)
    else:
        raise TranslationError('Constructor args must be a dict or list.')
    for key, value in obj.iteritems():
        if key == '__jsonclass__':
            continue
        setattr(new_obj, key, value)
    return new_obj 
Example 75
Project: pykit   Author: bsc-s2   File: humannum.py    MIT License 4 votes vote down vote up
def humannum(data, unit=None, include=None, exclude=None):

    if isinstance(data, types.DictType):

        data = data.copy()

        keys = set(data.keys())
        if include is not None:
            keys = keys & set(include)

        if exclude is not None:
            keys = keys - set(exclude)

        for k in keys:
            data[k] = humannum(data[k])

        return data

    elif isinstance(data, types.BooleanType):
        # We have to deal with bool because for historical reason bool is
        # subclass of int.
        # When bool is introduced into python 2.2 it is represented with int,
        # similar to C.
        return data

    elif isinstance(data, types.ListType):
        return [humannum(x) for x in data]

    elif isinstance(data, types.StringTypes):
        return data

    elif isinstance(data, integer_types):
        return humannum_int(data, unit=unit)

    elif isinstance(data, types.FloatType):
        if data > 999:
            return humannum_int(int(data), unit=unit)
        elif abs(data) < 0.0000000001:
            return '0'
        else:
            return '%.2f' % (data)

    else:
        return data 
Example 76
Project: ConfigNOW   Author: Integral-Technology-Solutions   File: pprint.py    MIT License 4 votes vote down vote up
def __format(self, object, stream, indent, allowance, context, level):
        level = level + 1
        if context.has_key(id(object)):
            object = _Recursion(object)
            self.__recursive = 1
        rep = self.__repr(object, context, level - 1)
        objid = id(object)
        context[objid] = 1
        typ = type(object)
        sepLines = len(rep) > (self.__width - 1 - indent - allowance)

        if sepLines and typ in (ListType, TupleType):
            #  Pretty-print the sequence.
            stream.write((typ is ListType) and '[' or '(')
            if self.__indent_per_level > 1:
                stream.write((self.__indent_per_level - 1) * ' ')
            length = len(object)
            if length:
                indent = indent + self.__indent_per_level
                self.__format(object[0], stream, indent, allowance + 1,
                              context, level)
                if length > 1:
                    for ent in object[1:]:
                        stream.write(',\n' + ' '*indent)
                        self.__format(ent, stream, indent,
                                      allowance + 1, context, level)
                indent = indent - self.__indent_per_level
            if typ is TupleType and length == 1:
                stream.write(',')
            stream.write(((typ is ListType) and ']') or ')')

        elif sepLines and typ is DictType:
            stream.write('{')
            if self.__indent_per_level > 1:
                stream.write((self.__indent_per_level - 1) * ' ')
            length = len(object)
            if length:
                indent = indent + self.__indent_per_level
                items  = object.items()
                items.sort()
                key, ent = items[0]
                rep = self.__repr(key, context, level) + ': '
                stream.write(rep)
                self.__format(ent, stream, indent + len(rep),
                              allowance + 1, context, level)
                if len(items) > 1:
                    for key, ent in items[1:]:
                        rep = self.__repr(key, context, level) + ': '
                        stream.write(',\n' + ' '*indent + rep)
                        self.__format(ent, stream, indent + len(rep),
                                      allowance + 1, context, level)
                indent = indent - self.__indent_per_level
            stream.write('}')

        else:
            stream.write(rep)

        del context[objid] 
Example 77
Project: ConfigNOW   Author: Integral-Technology-Solutions   File: pprint.py    MIT License 4 votes vote down vote up
def _safe_repr(object, context, maxlevels=None, level=0):
    level = level + 1
    typ = type(object)
    if not (typ in (DictType, ListType, TupleType) and object):
        rep = `object`
        return rep, (rep and (rep[0] != '<'))
    if context.has_key(id(object)):
        return `_Recursion(object)`, 0
    objid = id(object)
    context[objid] = 1
    readable = 1
    if typ is DictType:
        if maxlevels and level >= maxlevels:
            s = "{...}"
            readable = 0
        else:
            items = object.items()
            k, v = items[0]
            krepr, kreadable = _safe_repr(k, context, maxlevels, level)
            vrepr, vreadable = _safe_repr(v, context, maxlevels, level)
            readable = readable and kreadable and vreadable
            s = "{%s: %s" % (krepr, vrepr)
            for k, v in items[1:]:
                krepr, kreadable = _safe_repr(k, context, maxlevels, level)
                vrepr, vreadable = _safe_repr(v, context, maxlevels, level)
                readable = readable and kreadable and vreadable
                s = "%s, %s: %s" % (s, krepr, vrepr)
            s = s + "}"
    else:
        s, term = (typ is ListType) and ('[', ']') or ('(', ')')
        if maxlevels and level >= maxlevels:
            s = s + "..."
            readable = 0
        else:
            subrepr, subreadable = _safe_repr(
                object[0], context, maxlevels, level)
            readable = readable and subreadable
            s = s + subrepr
            tail = object[1:]
            if not tail:
                if typ is TupleType:
                    s = s + ','
            for ent in tail:
                subrepr, subreadable = _safe_repr(
                    ent, context, maxlevels, level)
                readable = readable and subreadable
                s = "%s, %s" % (s, subrepr)
        s = s + term
    del context[objid]
    return s, readable 
Example 78
Project: SUMO_dy_public   Author: DayuanTan   File: base.py    GNU General Public License v3.0 4 votes vote down vote up
def get_type(obj, typelist=[]):
    """
    Returns a flat list of type-string(s) which correspond to the
    (nested) type(s) of  the object obj.

    The returned type(s)  are keys of the global TYPES dictionary.
    """

    typelist = copy(typelist)
    if type(obj) == ndarray:
        typelist.append(('ArrayType', obj.shape))
        # return typelist # let's assume homogenious array types
        if len(obj.ravel()) > 0:
            return get_type(obj.flat[0], typelist)
        else:
            return typelist

    elif hasattr(obj, 'dtype'):  # obj is an array element
        # attention this is not a string but maybe this should
        # also be changed for all other types
        typelist.append(obj.dtype.str)
        return typelist

    elif type(obj) in (types.ListType, types.TupleType):
        typelist.append('ListType')
        if obj:
            return get_type(obj[0], typelist)
        else:
            return typelist

    elif type(obj) in (types.DictType, types.DictionaryType):

        if obj:
            key = obj.keys()[0]
            keytype = get_type(key)
            if len(keytype) > 0:
                typelist.append(('DictType', keytype[0]))
            else:
                typelist.append(('DictType', ''))

            return get_type(obj[key], typelist)
        else:
            typelist.append(('DictType', ''))
            return typelist

    else:
        for typename in dir(types):
            if type(obj) == types.__dict__[typename]:
                typelist.append(typename)
                return typelist
                break
        typelist.append('')
        return typelist 
Example 79
Project: ocs-bttrack   Author: stevenshiau   File: track.py    MIT License 4 votes vote down vote up
def statefiletemplate(x):
    if type(x) != DictType:
        raise ValueError
    for cname, cinfo in x.items():
        if cname == 'peers':
            for y in cinfo.values():      # The 'peers' key is a dictionary of SHA hashes (torrent ids)
                if type(y) != DictType:   # ... for the active torrents, and each is a dictionary
                    raise ValueError
                for id, info in y.items(): # ... of client ids interested in that torrent
                    if (len(id) != 20):
                        raise ValueError
                    if type(info) != DictType:  # ... each of which is also a dictionary
                        raise ValueError # ... which has an IP, a Port, and a Bytes Left count for that client for that torrent
                    if type(info.get('ip', '')) != StringType:
                        raise ValueError
                    port = info.get('port')
                    if type(port) not in (IntType,LongType) or port < 0:
                        raise ValueError
                    left = info.get('left')
                    if type(left) not in (IntType,LongType) or left < 0:
                        raise ValueError
                    if type(info.get('supportcrypto')) not in (IntType,LongType):
                        raise ValueError
                    if type(info.get('requirecrypto')) not in (IntType,LongType):
                        raise ValueError
        elif cname == 'completed':
            if (type(cinfo) != DictType): # The 'completed' key is a dictionary of SHA hashes (torrent ids)
                raise ValueError          # ... for keeping track of the total completions per torrent
            for y in cinfo.values():      # ... each torrent has an integer value
                if type(y) not in (IntType,LongType):
                    raise ValueError      # ... for the number of reported completions for that torrent
        elif cname == 'allowed':
            if (type(cinfo) != DictType): # a list of info_hashes and included data
                raise ValueError
            if x.has_key('allowed_dir_files'):
                adlist = [z[1] for z in x['allowed_dir_files'].values()]
                for y in cinfo.keys():        # and each should have a corresponding key here
                    if not y in adlist:
                        raise ValueError
        elif cname == 'allowed_dir_files':
            if (type(cinfo) != DictType): # a list of files, their attributes and info hashes
                raise ValueError
            dirkeys = {}
            for y in cinfo.values():      # each entry should have a corresponding info_hash
                if not y[1]:
                    continue
                if not x['allowed'].has_key(y[1]):
                    raise ValueError
                if dirkeys.has_key(y[1]): # and each should have a unique info_hash
                    raise ValueError
                dirkeys[y[1]] = 1 
Example 80
Project: ocs-bttrack   Author: stevenshiau   File: btformats.py    MIT License 4 votes vote down vote up
def check_info(info):
    if type(info) != DictType:
        raise ValueError, 'bad metainfo - not a dictionary'
    pieces = info.get('pieces')
    if type(pieces) != StringType or len(pieces) % 20 != 0:
        raise ValueError, 'bad metainfo - bad pieces key'
    piecelength = info.get('piece length')
    if type(piecelength) not in ints or piecelength <= 0:
        raise ValueError, 'bad metainfo - illegal piece length'
    name = info.get('name')
    if type(name) != StringType:
        raise ValueError, 'bad metainfo - bad name'
    if not reg.match(name):
        raise ValueError, 'name %s disallowed for security reasons' % name
    if info.has_key('files') == info.has_key('length'):
        raise ValueError, 'single/multiple file mix'
    if info.has_key('length'):
        length = info.get('length')
        if type(length) not in ints or length < 0:
            raise ValueError, 'bad metainfo - bad length'
    else:
        files = info.get('files')
        if type(files) != ListType:
            raise ValueError
        for f in files:
            if type(f) != DictType:
                raise ValueError, 'bad metainfo - bad file value'
            length = f.get('length')
            if type(length) not in ints or length < 0:
                raise ValueError, 'bad metainfo - bad length'
            path = f.get('path')
            if type(path) != ListType or path == []:
                raise ValueError, 'bad metainfo - bad path'
            for p in path:
                if type(p) != StringType:
                    raise ValueError, 'bad metainfo - bad path dir'
                if p != '':
                  if not reg.match(p):
                    raise ValueError, 'path %s disallowed for security reasons' % p
        for i in xrange(len(files)):
            for j in xrange(i):
                if files[i]['path'] == files[j]['path']:
                    raise ValueError, 'bad metainfo - duplicate path'