Python types.DictType() Examples

The following are 30 code examples of types.DictType(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module types , or try the search function .
Example #1
Source File: Switchboard.py    From oss-ftp with MIT License 7 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
Source File: monitoring.py    From automatron with Apache License 2.0 6 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 #3
Source File: bartercast.py    From p2ptv-pi with MIT License 6 votes vote down vote up
def validBarterCastMsg(self, bartercast_data):
        if not type(bartercast_data) == DictType:
            raise RuntimeError, 'bartercast: received data is not a dictionary'
            return False
        if not bartercast_data.has_key('data'):
            raise RuntimeError, "bartercast: 'data' key doesn't exist"
            return False
        if not type(bartercast_data['data']) == DictType:
            raise RuntimeError, "bartercast: 'data' value is not dictionary"
            return False
        for permid in bartercast_data['data'].keys():
            if not bartercast_data['data'][permid].has_key('u') or not bartercast_data['data'][permid].has_key('d'):
                raise RuntimeError, "bartercast: datafield doesn't contain 'u' or 'd' keys"
                return False

        return True 
Example #4
Source File: ut_pex.py    From p2ptv-pi with MIT License 6 votes vote down vote up
def check_ut_pex(d):
    if type(d) != DictType:
        raise ValueError('ut_pex: not a dict')
    same_apeers = []
    apeers = check_ut_pex_peerlist(d, 'added')
    dpeers = check_ut_pex_peerlist(d, 'dropped')
    if 'added.f' in d:
        addedf = d['added.f']
        if type(addedf) != StringType:
            raise ValueError('ut_pex: added.f: not string')
        if len(addedf) != len(apeers) and not len(addedf) == 0:
            raise ValueError('ut_pex: added.f: more flags than peers')
        addedf = map(ord, addedf)
        for i in range(min(len(apeers), len(addedf)) - 1, -1, -1):
            if addedf[i] & 4:
                same_apeers.append(apeers.pop(i))
                addedf.pop(i)

    if DEBUG:
        print >> sys.stderr, 'ut_pex: Got', apeers
    return (same_apeers, apeers, dpeers) 
Example #5
Source File: recipe-302742.py    From code with MIT License 6 votes vote down vote up
def _CheckSequence(self, newseq, oldseq, checklen=True):
        """ Scan sequence comparing new and old values of individual items
            return True when the first difference is found.
            Compare sequence lengths if checklen is True. It is False on first 
            call because self.__dict__ has _snapshot as an extra entry 
        """
        if checklen and len(newseq) <> len(oldseq):
            return True
        if type(newseq) is types.DictType:
            for key in newseq:
                if key == '_snapshot':
                    continue
                if key not in oldseq:
                    return True
                if self._CheckItem(newseq[key], oldseq[key]):
                    return True
        else:
            for k in range(len(newseq)):
                if self._CheckItem(newseq[k], oldseq[k]):
                    return True
        return 0 
Example #6
Source File: queue_manager.py    From GloboNetworkAPI with Apache License 2.0 6 votes vote down vote up
def append(self, dict_obj):
        """
            Appended in list object a dictionary that represents
            the body of the message that will be sent to queue.

            :param dict_obj: Dict object

        """

        try:

            if not isinstance(dict_obj, types.DictType):
                raise ValueError(
                    u'QueueManagerError - The type must be a instance of Dict')

            self._msgs.append(dict_obj)
            self.log.debug('dict_obj:%s', dict_obj)

        except Exception, e:
            self.log.error(
                u'QueueManagerError - Error on appending objects to queue.')
            self.log.error(e)
            raise Exception(
                'QueueManagerError - Error on appending objects to queue.') 
Example #7
Source File: table.py    From girlfriend with MIT License 6 votes vote down vote up
def _get_table_type(self, data):
        # 自动推断应该使用的table类型
        if self._table_type is not None:
            return self._table_type

        # 空列表
        if data is None or len(data) == 0:
            return ListTable

        # 默认取第一行进行推断
        row = data[0]
        if isinstance(row, SequenceCollectionType):
            return ListTable
        elif isinstance(row, types.DictType):
            return DictTable
        else:
            return ObjectTable 
Example #8
Source File: exception.py    From girlfriend with MIT License 6 votes vote down vote up
def __init__(self, msg):
        """
            :param msg 可以是一个字符串,也可以是一个key为locale的字典
        """
        if isinstance(msg, types.DictType):
            country_code, _ = locale.getlocale(locale.LC_ALL)
            msg = msg[country_code]

        if isinstance(msg, unicode):
            super(GirlFriendException, self).__init__(msg.encode("utf-8"))
            self.msg = msg
        elif isinstance(msg, str):
            super(GirlFriendException, self).__init__(msg)
            self.msg = msg.decode("utf-8")
        else:
            raise TypeError 
Example #9
Source File: Switchboard.py    From datafari with Apache License 2.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 #10
Source File: utilities.py    From timeseries with MIT License 6 votes vote down vote up
def table_output(data):
    '''Get a table representation of a dictionary.'''
    if type(data) == DictType:
        data = data.items()
    headings = [ item[0] for item in data ]
    rows = [ item[1] for item in data ]
    columns = zip(*rows)
    if len(columns):
        widths = [ max([ len(str(y)) for y in row ]) for row in rows ]
    else:
        widths = [ 0 for c in headings ]
    for c, heading in enumerate(headings):
        widths[c] = max(widths[c], len(heading))
    column_count = range(len(rows))
    table = [ ' '.join([ headings[c].ljust(widths[c]) for c in column_count ]) ]
    table.append(' '.join([ '=' * widths[c] for c in column_count ]))
    for column in columns:
        table.append(' '.join([ str(column[c]).ljust(widths[c]) for c in column_count ]))
    return '\n'.join(table) 
Example #11
Source File: sstruct.py    From stdm with GNU General Public License v2.0 6 votes vote down vote up
def unpack(format, data, object=None):
	if object is None:
		object = {}
	formatstring, names, fixes = getformat(format)
	if type(object) is types.DictType:
		dict = object
	else:
		dict = object.__dict__
	elements = struct.unpack(formatstring, data)
	for i in range(len(names)):
		name = names[i]
		value = elements[i]
		if fixes.has_key(name):
			# fixed point conversion
			value = value / fixes[name]
		dict[name] = value
	return object 
Example #12
Source File: coverage.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def restore(self):
        global c
        c = {}
        self.cexecuted = {}
        if not os.path.exists(self.cache):
            return
        try:
            cache = open(self.cache, 'rb')
            import marshal
            cexecuted = marshal.load(cache)
            cache.close()
            if isinstance(cexecuted, types.DictType):
                self.cexecuted = cexecuted
        except:
            pass

    # canonical_filename(filename).  Return a canonical filename for the
    # file (that is, an absolute path with no redundant components and
    # normalized case).  See [GDR 2001-12-04b, 3.3]. 
Example #13
Source File: poc.py    From vulscan with 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 #14
Source File: optparse.py    From meddle with 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 #15
Source File: optparse.py    From meddle with 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 #16
Source File: optparse.py    From ironpython2 with 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 #17
Source File: optparse.py    From ironpython2 with 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 #18
Source File: optparse.py    From BinderFilter with 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 #19
Source File: optparse.py    From BinderFilter with 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 #20
Source File: c_spec.py    From Computable with 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 #21
Source File: optparse.py    From Computable with 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 #22
Source File: optparse.py    From Computable with 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 #23
Source File: optparse.py    From oss-ftp with 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 #24
Source File: optparse.py    From oss-ftp with 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 #25
Source File: strutil.py    From pykit with 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 #26
Source File: optparse.py    From hacker-scripts with 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 #27
Source File: optparse.py    From hacker-scripts with 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 #28
Source File: optparse.py    From hacker-scripts with 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 #29
Source File: optparse.py    From hacker-scripts with 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 #30
Source File: ldap_auth.py    From kansha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def toUTF8(v):
    if isinstance(v, unicode):
        return v.encode('utf-8')
    elif isinstance(v, (types.TupleType, types.ListType)):
        return [toUTF8(e) for e in v]
    elif isinstance(v, types.DictType):
        return dict([(toUTF8(k), toUTF8(v_)) for k, v_ in v.items()])
    else:
        return v