Python types.DictionaryType() Examples

The following are code examples for showing how to use types.DictionaryType(). 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: tintri-python-sdk   Author: Tintri   File: common.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _json_object_to_object(self, json_object, entity_class, context={}):
        if type(json_object) == types.DictionaryType:
            if hasattr(entity_class, '_is_paginated') and entity_class._is_paginated:
                try:
                    if hasattr(self, '_process_page'):
                        return self._process_page(json_object, entity_class, context)
                    else:
                        raise AttributeError('Class %s does not have _process_page() method' % entity_class.__name__)
                except ValueError:
                    return map_to_object(json_object, entity_class)
            else:
                return map_to_object(json_object, entity_class)
        elif type(json_object) == types.ListType:
            objects = []
            for obj in json_object:
                objects.append(map_to_object(obj, entity_class))

            # if auto_page is set, return a page with the items
            if 'typeId' in json_object and json_object['typeId'] == 'com.tintri.api.rest.v310.dto.Page' and self.__auto_page:
                return TintriPage(paginated=entity_class._is_paginated, items=objects, context=context)
            else:
                return objects
        else:
            return json_object # Return any other type as is, such as None, string, number, boolean 
Example 2
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _eval_params(self, model, params):
        args = []
        for i, param in enumerate(params):
            if isinstance(param, types.ListType):
                value = self._eval_params(model, param)
            elif is_ref(param):
                value = self.process_ref(param)
            elif is_eval(param):
                value = self.process_eval(param)
            elif isinstance(param, types.DictionaryType): # supports XML syntax
                param_model = self.get_model(param.get('model', model))
                if 'search' in param:
                    q = eval(param['search'], self.eval_context)
                    ids = param_model.search(self.cr, self.uid, q)
                    value = self._get_first_result(ids)
                elif 'eval' in param:
                    local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
                    local_context.update(self.id_map)
                    value = eval(param['eval'], self.eval_context, local_context)
                else:
                    raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
            else:
                value = param # scalar value
            args.append(value)
        return args 
Example 3
Project: kotori   Author: daq-tools   File: backend_ctypes.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def __init__(self, **kwargs):
        """
        Ctypes.Structure with integrated default values.
        https://stackoverflow.com/questions/7946519/default-values-in-a-ctypes-structure/25892189#25892189

        :param kwargs: values different to defaults
        :type kwargs: dict
        """

        # sanity checks
        defaults = type(self)._defaults_
        assert type(defaults) is types.DictionaryType

        # use defaults, but override with keyword arguments, if any
        values = defaults.copy()
        for (key, val) in kwargs.items():
            values[key] = val

        # appropriately initialize ctypes.Structure
        #super().__init__(**values)                     # Python 3 syntax
        return Structure.__init__(self, **values)       # Python 2 syntax

    # http://stackoverflow.com/questions/1825715/how-to-pack-and-unpack-using-ctypes-structure-str/1827666#1827666
    # https://wiki.python.org/moin/ctypes 
Example 4
Project: kotori   Author: daq-tools   File: influx.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def process_message(self, topic, payload, *args):

        log.debug('Bus receive: topic={topic}, payload={payload}', topic=topic, payload=payload)

        # TODO: filter by realm/topic

        # decode message
        if type(payload) is types.DictionaryType:
            message = payload.copy()
        elif type(payload) is types.ListType:
            message = OrderedDict(payload)
        else:
            raise TypeError('Unable to handle data type "{}" from bus'.format(type(payload)))

        # compute storage location from topic and message
        storage_location = self.storage_location(message)
        log.debug('Storage location: {storage_location}', storage_location=dict(storage_location))

        # store data
        self.store_message(storage_location, message) 
Example 5
Project: ndb-py   Author: node-db   File: node_travel.py    Apache License 2.0 6 votes vote down vote up
def travel(self, node, action):
        '''
        #遍历节点
        @param node: ndb节点
         
        @return 遍历结果
        '''
        if type(node) == types.ListType:
            for item in node:
                self.travel(item, action)
        elif type(node) == types.DictionaryType:
            for key in node:
                value = node.get(key)
                self.travel(value, action)
            action(node)
        
        return node 
Example 6
Project: ndb-py   Author: node-db   File: node_clean.py    Apache License 2.0 6 votes vote down vote up
def clean(self, node):
        '''
        #清理节点
        @param node: ndb节点
         
        @return 清理后的节点
        '''
        if type(node) == types.ListType:
            result = []
            for row in node:
                if row != None and len(row) > 0:
                    result.append(row)
        elif type(node) == types.DictionaryType:
            result = {}
            for key in node:
                value = node.get(key)
                cleaned_value = self.clean(value)
                if cleaned_value != None and len(cleaned_value) > 0:
                    result[key] = cleaned_value
        else:
            if node != None:
                result = node
            
        return result 
Example 7
Project: faircoop-market   Author: sarantapichos   File: yaml_import.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _eval_params(self, model, params):
        args = []
        for i, param in enumerate(params):
            if isinstance(param, types.ListType):
                value = self._eval_params(model, param)
            elif is_ref(param):
                value = self.process_ref(param)
            elif is_eval(param):
                value = self.process_eval(param)
            elif isinstance(param, types.DictionaryType): # supports XML syntax
                param_model = self.get_model(param.get('model', model))
                if 'search' in param:
                    q = eval(param['search'], self.eval_context)
                    ids = param_model.search(self.cr, self.uid, q)
                    value = self._get_first_result(ids)
                elif 'eval' in param:
                    local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
                    local_context.update(self.id_map)
                    value = eval(param['eval'], self.eval_context, local_context)
                else:
                    raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
            else:
                value = param # scalar value
            args.append(value)
        return args 
Example 8
Project: SUMO_dy_public   Author: DayuanTan   File: objpanel.py    GNU General Public License v3.0 6 votes vote down vote up
def define_widgetset(self):
        """
        Generates the widgets representing this attribute.
        """
        if type(self._attrconf.choices) in (OrderedDict, types.DictionaryType):
            self._choicevalues = self._attrconf.choices.values()
            self._choicenames = self._attrconf.choices.keys()
        else:
            self._choicevalues = list(self._attrconf.choices)
            self._choicenames = list(self._attrconf.choices)
        # if type(self._attrconf.choices) in
        # [types.ListType,types.TupleType,numpy.ndarray]:

        if self._attrconf.has_unit() & self._attrconf.is_writable():
            return [('name',    self.create_namewidget(),  wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
                    ('value',   self.create_valuewidget(), wx.EXPAND),
                    ('unit',   self.create_unitwidget(), wx.ALIGN_LEFT | wx.ALIGN_CENTER_VERTICAL), ]
        else:
            return [('name',    self.create_namewidget(),  wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL),
                    ('value',   self.create_valuewidget(), wx.EXPAND)] 
Example 9
Project: SUMO_dy_public   Author: DayuanTan   File: objpanel.py    GNU General Public License v3.0 6 votes vote down vote up
def get_valuewidget_read(self):
        """
        Return widget to read only numeric value of attribute
        This is effectively the parametrisation of the masked.NumCtrl widget.
        """
        value = self.get_value_obj()
        # print 'ChoiceWidgetContainer.get_valuewidget_read',value,type(value)
        # print '  choices',self._attrconf.choices

        if type(self._attrconf.choices) in (OrderedDict, types.DictionaryType):
            #value = self._attrconf.choices[value]
            value = self._choicenames[self._choicevalues.index(value)]
        # print '  value =',value
        widget = wx.TextCtrl(self.parent, -1, value, style=wx.ALIGN_RIGHT)
        widget.Enable(False)
        return widget 
Example 10
Project: server   Author: iw3hxn   File: yaml_import.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _eval_params(self, model, params):
        args = []
        for i, param in enumerate(params):
            if isinstance(param, types.ListType):
                value = self._eval_params(model, param)
            elif is_ref(param):
                value = self.process_ref(param)
            elif is_eval(param):
                value = self.process_eval(param)
            elif isinstance(param, types.DictionaryType): # supports XML syntax
                param_model = self.get_model(param.get('model', model))
                if 'search' in param:
                    q = eval(param['search'], self.eval_context)
                    ids = param_model.search(self.cr, self.uid, q)
                    value = self._get_first_result(ids)
                elif 'eval' in param:
                    local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
                    local_context.update(self.id_map)
                    value = eval(param['eval'], self.eval_context, local_context)
                else:
                    raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
            else:
                value = param # scalar value
            args.append(value)
        return args 
Example 11
Project: Ant   Author: dkodnik   File: yaml_import.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _eval_params(self, model, params):
        args = []
        for i, param in enumerate(params):
            if isinstance(param, types.ListType):
                value = self._eval_params(model, param)
            elif is_ref(param):
                value = self.process_ref(param)
            elif is_eval(param):
                value = self.process_eval(param)
            elif isinstance(param, types.DictionaryType): # supports XML syntax
                param_model = self.get_model(param.get('model', model))
                if 'search' in param:
                    q = eval(param['search'], self.eval_context)
                    ids = param_model.search(self.cr, self.uid, q)
                    value = self._get_first_result(ids)
                elif 'eval' in param:
                    local_context = {'obj': lambda x: param_model.browse(self.cr, self.uid, x, self.context)}
                    local_context.update(self.id_map)
                    value = eval(param['eval'], self.eval_context, local_context)
                else:
                    raise YamlImportException('You must provide either a !ref or at least a "eval" or a "search" to function parameter #%d.' % i)
            else:
                value = param # scalar value
            args.append(value)
        return args 
Example 12
Project: Project-Altis-Copyright-Proof-Source   Author: CodeAnGo   File: ToonPythonUtil.py    Apache License 2.0 6 votes vote down vote up
def lineage(obj, verbose=0, indent=0):
        """
        return instance or class name in as a multiline string.

        Usage: print lineage(foo)

        (Based on getClassLineage())
        """
        r=""
        if type(obj) == types.ListType:
            r+=(" "*indent)+"python list\n"
        elif type(obj) == types.DictionaryType:
            r+=(" "*indent)+"python dictionary\n"
        elif type(obj) == types.ModuleType:
            r+=(" "*indent)+str(obj)+"\n"
        elif type(obj) == types.InstanceType:
            r+=lineage(obj.__class__, verbose, indent)
        elif type(obj) == types.ClassType:
            r+=(" "*indent)
            if verbose:
                r+=obj.__module__+"."
            r+=obj.__name__+"\n"
            for c in obj.__bases__:
                r+=lineage(c, verbose, indent+2)
        return r 
Example 13
Project: Project-Altis-Copyright-Proof-Source   Author: CodeAnGo   File: ToonPythonUtil.py    Apache License 2.0 6 votes vote down vote up
def getClassLineage(obj):
    """
    print object inheritance list
    """
    if type(obj) == types.DictionaryType:
        # Just a dictionary, return dictionary
        return [obj]
    elif (type(obj) == types.InstanceType):
        # Instance, make a list with the instance and its class interitance
        return [obj] + getClassLineage(obj.__class__)
    elif ((type(obj) == types.ClassType) or
          (type(obj) == types.TypeType)):
        # Class or type, see what it derives from
        lineage = [obj]
        for c in obj.__bases__:
            lineage = lineage + getClassLineage(c)
        return lineage
    # New FFI objects are types that are not defined.
    # but they still act like classes
    elif hasattr(obj, '__class__'):
        # Instance, make a list with the instance and its class interitance
        return [obj] + getClassLineage(obj.__class__)
    else:
        # Not what I'm looking for
        return [] 
Example 14
Project: py-xml   Author: PinaeOS   File: xml_builder.py    Apache License 2.0 6 votes vote down vote up
def to_xml(self, node):
        if node == None or type(node) != types.DictionaryType:
            return None
        
        impl = xml.dom.minidom.getDOMImplementation()
        
        root_node_key = None
        for _node_key in node.keys():
            if _node_key != '':
                root_node_key = _node_key
                break
        
        if root_node_key != None:
            dom = impl.createDocument(None, root_node_key, None)
            root = dom.documentElement
        
            self.__fetch_element(dom, root, node.get(root_node_key))
            self.__indent(dom, dom.documentElement)
            return root.toxml()
        else:
            return None 
Example 15
Project: core   Author: lifemapper   File: jsonFormatter.py    GNU General Public License v3.0 5 votes vote down vote up
def _formatObject(obj):
    """Helper method to format an individual object based on its type
    """
    cherrypy.response.headers['Content-Type'] = LMFormat.JSON.getMimeType()
    if isinstance(obj, DictionaryType):
        return obj
    elif isinstance(obj, Atom):
        return formatAtom(obj)
    elif isinstance(obj, SDMProjection):
        return formatProjection(obj)
    elif isinstance(obj, OccurrenceLayer):
        return formatOccurrenceSet(obj)
    elif isinstance(obj, EnvLayer):
        return formatEnvLayer(obj)
    elif isinstance(obj, Scenario):
        return formatScenario(obj)
    elif isinstance(obj, ScenPackage):
        return formatScenarioPackage(obj)
    elif isinstance(obj, Raster):
        return formatRasterLayer(obj)
    elif isinstance(obj, Gridset):
        return formatGridset(obj)
    elif isinstance(obj, LMMatrix):
        return formatMatrix(obj)
    elif isinstance(obj, ShapeGrid):
        return formatShapegrid(obj)
    elif isinstance(obj, Tree):
        return formatTree(obj)
    elif isinstance(obj, Vector):
        return formatVector(obj)
    else:
        # TODO: Expand these and maybe fallback to a generic formatter of public
        #             attributes
        raise TypeError("Cannot format object of type: {}".format(type(obj)))

# ............................................................................. 
Example 16
Project: tintri-python-sdk   Author: Tintri   File: utils.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def map_to_object(m, cls):
    def __getobjecttype(cls, varname):
        from .__init__ import TintriObject
        if '_property_map' in dir(cls):
            if varname in cls._property_map.keys():
                return cls._property_map[varname]
        return TintriObject

    if type(m) == types.DictionaryType:
        o = cls()
        
        ignoresetattr = None
        if hasattr(o, '_ignoresetattr'):
            ignoresetattr = o._ignoresetattr
            o._ignoresetattr = True

        for k in m.keys():
            cls2 = __getobjecttype(cls, k)
            setattr(o, k, map_to_object(m[k], cls2))

        if ignoresetattr:
            o._ignoresetattr = ignoresetattr
            
        return o
    elif type(m) == types.ListType:
        objects = []
        for obj in m:
            objects.append(map_to_object(obj, cls))
        return objects
    else:
        return m 
Example 17
Project: tintri-python-sdk   Author: Tintri   File: common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _process_error(self, method, url, status_code, response_data):
        try:
            jsonError = json.loads(response_data)
        except ValueError as e:
            self.__logger.warning("Failed to decode result. url:%s status:%s error:%s data:%s" % (url, status_code, e, response_data))
            raise TintriServerError(status_code, cause=e, message="Failed to decode result. url:%s status:%s error:%s data:%s" % (url, status_code, e, response_data))
        except Exception as e:
            self.__logger.warning("HTTP request failed. URL:%s Status Code:%s Error:%s Text:%s" % (url, status_code, e, response_data))
            raise TintriServerError(status_code, None, cause=`e`, details=response_data)

        if type(jsonError) == types.DictionaryType:
            self.__logger.info('Server error. url:%s status:%s code:%s message:%s cause:%s' % (url, status_code, jsonError['code'], jsonError['message'], jsonError['causeDetails']))
            if status_code == 400:
                raise TintriBadRequestError(jsonError['code'], jsonError['message'], jsonError['causeDetails'])
            elif status_code == 401:
                raise TintriInvalidSessionError(jsonError['code'], jsonError['message'], jsonError['causeDetails'])
            elif status_code == 403:
                raise TintriAuthorizationError(jsonError['code'], jsonError['message'], jsonError['causeDetails'])
            elif status_code == 404:
                raise TintriAPINotFoundError(jsonError['code'], jsonError['message'], jsonError['causeDetails'])
            elif status_code == 500:
                raise TintriInternalError(jsonError['code'], jsonError['message'], jsonError['causeDetails'])
            else:
                raise TintriServerError(status_code, code=jsonError['code'], message=jsonError['message'], details=jsonError['causeDetails'])
        else:
            self.__logger.info('Server error. url:%s status:%s Unknown error:%s' % (url, status_code, response_data))
            raise TintriServerError(status_code, code=None, message='Unknown error', details=response_data) 
Example 18
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_yaml_mapping(node, tag_constructor):
    value = isinstance(node, types.DictionaryType) \
        and len(node.keys()) == 1 \
        and isinstance(node.keys()[0], tag_constructor)
    return value 
Example 19
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _process_node(self, node):
        if is_comment(node):
            self.process_comment(node)
        elif is_assert(node):
            self.process_assert(node)
        elif is_record(node):
            self.process_record(node)
        elif is_python(node):
            self.process_python(node)
        elif is_menuitem(node):
            self.process_menuitem(node)
        elif is_delete(node):
            self.process_delete(node)
        elif is_url(node):
            self.process_url(node)
        elif is_context(node):
            self.process_context(node)
        elif is_ir_set(node):
            self.process_ir_set(node)
        elif is_act_window(node):
            self.process_act_window(node)
        elif is_report(node):
            self.process_report(node)
        elif is_workflow(node):
            if isinstance(node, types.DictionaryType):
                self.process_workflow(node)
            else:
                self.process_workflow({node: []})
        elif is_function(node):
            if isinstance(node, types.DictionaryType):
                self.process_function(node)
            else:
                self.process_function({node: []})
        elif node is None:
            self.process_none()
        else:
            raise YamlImportException("Can not process YAML block: %s" % node) 
Example 20
Project: ngo-addons-backport   Author: camptocamp   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _log_node(self, node, is_preceded_by_comment):
        if is_comment(node):
            is_preceded_by_comment = True
            self._log(node)
        elif not is_preceded_by_comment:
            if isinstance(node, types.DictionaryType):
                msg = "Creating %s\n with %s"
                args = node.items()[0]
                self._log(msg, *args)
            else:
                self._log(node)
        else:
            is_preceded_by_comment = False
        return is_preceded_by_comment 
Example 21
Project: kotori   Author: daq-tools   File: tasmota.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def decode_sensor_message(self, message):
        """
        {
          "Time": "2019-06-02T22:13:07",
          "SonoffSC": {
            "Temperature": 25,
            "Humidity": 15,
            "Light": 20,
            "Noise": 10,
            "AirQuality": 90
          },
          "TempUnit": "C"
        }

        {
          "Time": "2017-02-16T10:13:52",
          "DS18B20": {
            "Temperature": 20.6
          }
        }

        """
        data = OrderedDict()
        for key, value in message.items():
            if isinstance(value, types.DictionaryType):
                data.update(value)
        return data 
Example 22
Project: kotori   Author: daq-tools   File: common.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_skip_key(self, *args):
        key_parts = []
        for arg in args:
            if isinstance(arg, types.StringTypes):
                key_parts.append(arg)
            elif isinstance(arg, types.DictionaryType):
                key_parts.append(','.join(arg.keys()))
        skip_key = '-'.join(key_parts)
        return skip_key 
Example 23
Project: kotori   Author: daq-tools   File: influx.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def flatten(l):
    """
    Munge InfluxDB results.

    See also: https://stackoverflow.com/questions/21461140/flatten-an-irregular-list-of-lists-in-python-respecting-pandas-dataframes
    """
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (basestring, pandas.DataFrame, types.DictionaryType)):
            for sub in flatten(el):
                yield sub
        else:
            yield el 
Example 24
Project: ip-navigator   Author: ip-tools   File: container.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def unique_sequence(seq):
    # https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-in-python-whilst-preserving-order/480227#480227
    seen = set()
    seen_add = seen.add
    unhashable_types = (types.ListType, types.DictionaryType)
    return [x for x in seq if type(x) in unhashable_types or not (x in seen or seen_add(x))] 
Example 25
Project: ip-navigator   Author: ip-tools   File: normalize.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def normalize_patent(number, as_dict=False, as_string=False, fix_kindcode=False, for_ops=True, provider=None):

    if provider is None and for_ops is True:
        provider = 'ops'

    # 1. handle patent dicts or convert (split) from string
    if isinstance(number, types.DictionaryType):
        patent = number
    else:
        patent = split_patent_number(number)

    # 2.a. normalize patent dict
    patent_normalized = patch_patent(patent, provider=provider)

    # 2.b. apply fixes
    if fix_kindcode:
        fix_patent_kindcode_ops(patent_normalized)

    # 3. result handling

    # 3.a) default mechanism: return what we've got
    if isinstance(number, types.DictionaryType):
        result = patent_normalized
    else:
        result = join_patent(patent_normalized)

    # 3.b) extended mechanism: return what we are requested for
    if as_dict:
        result = patent_normalized
    elif as_string:
        result = join_patent(patent_normalized)

    return result 
Example 26
Project: ip-navigator   Author: ip-tools   File: common.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def decode_patent_number(patent):
    if isinstance(patent, types.StringTypes):
        decoded = split_patent_number(patent)
    elif isinstance(patent, types.DictionaryType):
        decoded = patent
    else:
        raise TypeError(u'Document number "{patent}" of type "{type}" could not be decoded'.format(patent=patent, type=type(patent)))
    return decoded 
Example 27
Project: ip-navigator   Author: ip-tools   File: export.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def write_numberlist_sheets(self):
        sheets = OrderedDict()
        sheets['rated']     = self.data.get('collections', {}).get('rated')
        sheets['dismissed'] = self.data.get('collections', {}).get('dismissed')
        sheets['seen']      = self.data.get('collections', {}).get('seen')
        for sheet_name, entries in sheets.iteritems():

            #print 'entries:'; pprint(entries)

            if entries:
                first = entries[0]
            else:
                first = {}

            # Create pandas DataFrame
            if type(first) in types.StringTypes:
                df = pandas.DataFrame(entries, columns=['PN'])

            elif isinstance(first, (types.DictionaryType, Bunch)):
                df = pandas.DataFrame(entries, columns=['number', 'score', 'timestamp', 'url'])
                df.rename(columns={'number': 'document', 'url': 'display'}, inplace=True)

            # Export DataFrame to Excel
            df.to_excel(self.writer, sheet_name=sheet_name, index=False)

            # Set column widths
            wks = self.worksheet_set_column_widths(sheet_name, 25, 15, 30, 25, cell_format=self.format_wrap_top)
            wks.set_landscape()
            #wks.set_column('C:C', width=19, cell_format=self.format_small_font)
            self.set_header_footer(wks) 
Example 28
Project: ndb-py   Author: node-db   File: node_travel_test.py    Apache License 2.0 5 votes vote down vote up
def test_travel(self):
        def action(node):
            if type(node) == types.DictionaryType:
                if node.has_key('age'):
                    today = datetime.datetime.now()
                    node['birthday'] = str(today.year - int(node.get('age')))
        
        node = test_data.node
        
        result = operate.travel(node, action)
        select_result = operate.select(result, 'root->group-1->birthday:[1991, 1995]')
        self.assertEqual(len(select_result), 2) 
Example 29
Project: ndb-py   Author: node-db   File: node_update.py    Apache License 2.0 5 votes vote down vote up
def update(self, node, path, value, action):
        if type(value) == types.StringType or type(value) == types.UnicodeType:
            self.update_value = super(NodeUpdate, self)._convert_value_map(value)
        elif type(value) == types.DictionaryType:
            self.update_value = value
            
        self.action = action
        
        super(NodeUpdate, self).locate(node, path);
        
        return node_clean.NodeClean().clean(node) 
Example 30
Project: ndb-py   Author: node-db   File: node_update.py    Apache License 2.0 5 votes vote down vote up
def do_action(self, node):
        if self.action != None:
            self.action(node)
        else:
            if self.update_value != None and type(node) == types.DictionaryType and self.update_value != None:
                for key in self.update_value:
                    node[key] = self.update_value.get(key) 
Example 31
Project: ndb-py   Author: node-db   File: node_insert.py    Apache License 2.0 5 votes vote down vote up
def insert(self, node, path, value, action):
        if type(value) == types.StringType or type(value) == types.UnicodeType:
            self.insert_value = super(NodeInsert, self)._convert_value_map(value)
        elif type(value) == types.DictionaryType:
            self.insert_value = value
        
        self.action = action
        
        super(NodeInsert, self).locate(node, path, True);
        
        return node_clean.NodeClean().clean(node) 
Example 32
Project: ndb-py   Author: node-db   File: node_insert.py    Apache License 2.0 5 votes vote down vote up
def do_action(self, node):
        if self.action != None:
            self.action(node)
        else:
            if node != None and type(node) == types.DictionaryType and self.insert_value != None:
                for key in self.insert_value:
                    node[key] = self.insert_value.get(key) 
Example 33
Project: ndb-py   Author: node-db   File: node_redirect.py    Apache License 2.0 5 votes vote down vote up
def redirect(self, target, ndb):
        writer = node_writer.NodeWriter()
        
        if type(ndb) != types.DictionaryType:
            ndb = {'result' : ndb}
        
        if str(target).upper() == 'PRINT':
            print writer.print_node(None, ndb, '\t');
        else:
            writer.write_node(target, None, ndb, '\t') 
Example 34
Project: Excel2Json   Author: YinGuiWang   File: excel2json.py    GNU General Public License v2.0 5 votes vote down vote up
def AnalyticalDispatch(self,resultObject, tbKey, tbValue, primaryKey):

        #if type(tbValue) is types.DictionaryType:
        if isinstance(tbValue, OrderedDict):
            self.AnalyticalDic(resultObject, tbKey, tbValue, primaryKey)
        elif type(tbValue) is types.ListType:
            self.AnalyticaList(resultObject, tbKey, tbValue, primaryKey)


    #List 
Example 35
Project: faircoop-market   Author: sarantapichos   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_yaml_mapping(node, tag_constructor):
    value = isinstance(node, types.DictionaryType) \
        and len(node.keys()) == 1 \
        and isinstance(node.keys()[0], tag_constructor)
    return value 
Example 36
Project: faircoop-market   Author: sarantapichos   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _process_node(self, node):
        if is_comment(node):
            self.process_comment(node)
        elif is_assert(node):
            self.process_assert(node)
        elif is_record(node):
            self.process_record(node)
        elif is_python(node):
            self.process_python(node)
        elif is_menuitem(node):
            self.process_menuitem(node)
        elif is_delete(node):
            self.process_delete(node)
        elif is_url(node):
            self.process_url(node)
        elif is_context(node):
            self.process_context(node)
        elif is_ir_set(node):
            self.process_ir_set(node)
        elif is_act_window(node):
            self.process_act_window(node)
        elif is_report(node):
            self.process_report(node)
        elif is_workflow(node):
            if isinstance(node, types.DictionaryType):
                self.process_workflow(node)
            else:
                self.process_workflow({node: []})
        elif is_function(node):
            if isinstance(node, types.DictionaryType):
                self.process_function(node)
            else:
                self.process_function({node: []})
        elif node is None:
            self.process_none()
        else:
            raise YamlImportException("Can not process YAML block: %s" % node) 
Example 37
Project: faircoop-market   Author: sarantapichos   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _log_node(self, node, is_preceded_by_comment):
        if is_comment(node):
            is_preceded_by_comment = True
            self._log(node)
        elif not is_preceded_by_comment:
            if isinstance(node, types.DictionaryType):
                msg = "Creating %s\n with %s"
                args = node.items()[0]
                self._log(msg, *args)
            else:
                self._log(node)
        else:
            is_preceded_by_comment = False
        return is_preceded_by_comment 
Example 38
Project: SUMO_dy_public   Author: DayuanTan   File: objpanel.py    GNU General Public License v3.0 5 votes vote down vote up
def get_valuewidget_write_choice(self):
        """
        Return widget to edit numeric value of attribute
        """
        return self.get_valuewidget_read()

    # def get_valuewidget_write_choice(self):
    #    """
    #    Return widget to edit numeric value of attribute
    #    """
    #    objdata = self.get_value_obj()
    #    print 'ObjWidgetContainer.get_valuewidget_write',obj.name
    #    # Here just the plain static text widget is returned
    #    #self.config_attr
    #
    #    if hasattr(objdata, '__iter__'):
    #        obj, _id = objdata
    #        text = obj.format_ident_row(_id)
    #    else:
    #        text = obj.format_ident()
    #
    #    print '  text',text
    #    if type(self._attrconf.choices) in (OrderedDict, types.DictionaryType):
    #        self._choices =  self._attrconf.choices.keys()
    #        widget = wx.Choice(self.parent, -1, (100, 50), choices = self._attrconf.choices.keys())
    #        ind = self._attrconf.choices.keys().index(value)
    #        widget.SetSelection(ind)
    #    else:
    #        self._choices =  self._attrconf.choices
    #        widget = wx.Choice(self.parent, -1, (100, 50), choices = self._attrconf.choices)
    #
    #    if self._choices.count(text)>0:
    #        ind = self._choices.index(text)
    #        widget.SetSelection(ind)
    #        if self.immediate_apply:
    #            self.parent.Bind(wx.EVT_CHOICE, self.on_apply_immediate, widget)

        # print 'create_valuewidget: '+value,self.attr

        return widget 
Example 39
Project: server   Author: iw3hxn   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_yaml_mapping(node, tag_constructor):
    value = isinstance(node, types.DictionaryType) \
        and len(node.keys()) == 1 \
        and isinstance(node.keys()[0], tag_constructor)
    return value 
Example 40
Project: server   Author: iw3hxn   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _process_node(self, node):
        if is_comment(node):
            self.process_comment(node)
        elif is_assert(node):
            self.process_assert(node)
        elif is_record(node):
            self.process_record(node)
        elif is_python(node):
            self.process_python(node)
        elif is_menuitem(node):
            self.process_menuitem(node)
        elif is_delete(node):
            self.process_delete(node)
        elif is_url(node):
            self.process_url(node)
        elif is_context(node):
            self.process_context(node)
        elif is_ir_set(node):
            self.process_ir_set(node)
        elif is_act_window(node):
            self.process_act_window(node)
        elif is_report(node):
            self.process_report(node)
        elif is_workflow(node):
            if isinstance(node, types.DictionaryType):
                self.process_workflow(node)
            else:
                self.process_workflow({node: []})
        elif is_function(node):
            if isinstance(node, types.DictionaryType):
                self.process_function(node)
            else:
                self.process_function({node: []})
        elif node is None:
            self.process_none()
        else:
            raise YamlImportException("Can not process YAML block: %s" % node) 
Example 41
Project: server   Author: iw3hxn   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _log(self, node, is_preceded_by_comment):
        if is_comment(node):
            is_preceded_by_comment = True
            _logger.log(logging.TEST, node)
        elif not is_preceded_by_comment:
            if isinstance(node, types.DictionaryType):
                msg = "Creating %s\n with %s"
                args = node.items()[0]
                _logger.log(logging.TEST, msg, *args)
            else:
                _logger.log(logging.TEST, node)
        else:
            is_preceded_by_comment = False
        return is_preceded_by_comment 
Example 42
Project: Ant   Author: dkodnik   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _is_yaml_mapping(node, tag_constructor):
    value = isinstance(node, types.DictionaryType) \
        and len(node.keys()) == 1 \
        and isinstance(node.keys()[0], tag_constructor)
    return value 
Example 43
Project: Ant   Author: dkodnik   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _process_node(self, node):
        if is_comment(node):
            self.process_comment(node)
        elif is_assert(node):
            self.process_assert(node)
        elif is_record(node):
            self.process_record(node)
        elif is_python(node):
            self.process_python(node)
        elif is_menuitem(node):
            self.process_menuitem(node)
        elif is_delete(node):
            self.process_delete(node)
        elif is_url(node):
            self.process_url(node)
        elif is_context(node):
            self.process_context(node)
        elif is_ir_set(node):
            self.process_ir_set(node)
        elif is_act_window(node):
            self.process_act_window(node)
        elif is_report(node):
            self.process_report(node)
        elif is_workflow(node):
            if isinstance(node, types.DictionaryType):
                self.process_workflow(node)
            else:
                self.process_workflow({node: []})
        elif is_function(node):
            if isinstance(node, types.DictionaryType):
                self.process_function(node)
            else:
                self.process_function({node: []})
        elif node is None:
            self.process_none()
        else:
            raise YamlImportException("Can not process YAML block: %s" % node) 
Example 44
Project: Ant   Author: dkodnik   File: yaml_import.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _log_node(self, node, is_preceded_by_comment):
        if is_comment(node):
            is_preceded_by_comment = True
            self._log(node)
        elif not is_preceded_by_comment:
            if isinstance(node, types.DictionaryType):
                msg = "Creating %s\n with %s"
                args = node.items()[0]
                self._log(msg, *args)
            else:
                self._log(node)
        else:
            is_preceded_by_comment = False
        return is_preceded_by_comment 
Example 45
Project: py-xml   Author: PinaeOS   File: xml_builder.py    Apache License 2.0 5 votes vote down vote up
def __fetch_element(self, dom, pelement, node):
        if node != None:
            for node_name in node.keys():
                node_value = node.get(node_name)
                if type(node_value) == types.DictionaryType:
                    self.__create_element(dom, pelement, node_name, node_value)
                elif type(node_value) == types.ListType:
                    for node_item in node_value:
                        self.__create_element(dom, pelement, node_name, node_item) 
Example 46
Project: ndb-py   Author: node-db   File: node_writer.py    Apache License 2.0 4 votes vote down vote up
def __print_node(self, indent, node_name, node, indent_flag):
        '''
        #将节点数据内容输出为ndb格式的字符串
        
        @param indent: 缩进量
        @param node_name: 根节点名称
        @param node: 节点数据
        @param indent_flag: 缩进标识符, 默认\t 
        
        @return: 节点数据字符串
        '''
        if type(node) != types.DictionaryType:
            raise 'Node is NOT DictionaryType'
        
        result = []
        
        next_indent = indent + 1;
        
        if node_name != None and node_name != '':
            result.append(indent_flag * indent + node_name + '{\n')
        else:
            next_indent = indent
            
        for key in node.keys():
            value = node[key]
            if type(value) == types.ListType and len(value) != 0:
                for item in value:
                    if type(item) == types.DictionaryType:
                        result.append(self.__print_node(next_indent, key, item, indent_flag))
                    if type(item) == types.StringType:
                        result.append(indent_flag * next_indent + '{0}:{1}\n'.format(key, item))
                        
            if type(value) == types.DictionaryType and len(value.keys()) != 0:
                result.append(self.__print_node(next_indent, str(key), value, indent_flag))
                
            if (type(value) == types.StringType or type(value) == types.UnicodeType) and value != '':
                result.append(indent_flag * next_indent + '{0}:{1}\n'.format(key, value))
                
            if type(value) == types.IntType or type(value) == types.LongType or type(value) == types.BooleanType:
                result.append(indent_flag * next_indent + '{0}:{1}\n'.format(key, str(value)))
        
        if node_name != None and node_name != '':
            result.append(indent_flag * indent + indent_flag * indent + '}\n')
            
        return ''.join(result) 
Example 47
Project: ndb-py   Author: node-db   File: node_writer.py    Apache License 2.0 4 votes vote down vote up
def __print_xml(self, indent, node_name, node, indent_flag):
        '''
        #将节点数据内容输出为XML格式的字符串
        
        @param node_name: 根节点名称
        @param node: 节点数据
        
        @return: 节点数据XML字符串
        '''
        result = []
    
        next_indent = indent + 1;
        
        if node_name != None:
            node_name = str(node_name).split()
            
        if node_name != None and node_name != '':
            result.append(indent_flag * indent + '<{0}>\n'.format(node_name))
        else:
            next_indent = indent
            
        for key in node.keys():
            value = node[key]
            if type(value) == types.ListType and len(value) != 0:
                for item in value:
                    if type(item) == types.DictionaryType:
                        result.append(self.__print_xml(next_indent, key, item, indent_flag))
                    if type(item) == types.StringType:
                        result.append(indent_flag * next_indent + '<{0}>{1}</{0}>\n'.format(key, item))
                        
            if type(value) == types.DictionaryType and len(value.keys()) != 0:
                result.append(self.__print_xml(next_indent, key, value, indent_flag))
                
            if (type(value) == types.StringType or type(value) == types.UnicodeType) and value != '':
                result.append(indent_flag * next_indent + '<{0}>{1}</{0}>\n'.format(key, value))
                
            if type(value) == types.IntType or type(value) == types.LongType or type(value) == types.BooleanType:
                result.append(indent_flag * next_indent + '<{0}>{1}</{0}>\n'.format(key, str(value)))
                
        if node_name != None and node_name != '':   
            result.append('<{0}>\n'.format(node_name))
        
        return ''.join(result) 
Example 48
Project: panda-harvester   Author: PanDAWMS   File: direct_ssh_herder.py    Apache License 2.0 4 votes vote down vote up
def __call__(self, *args, **kwargs):
        tmpLog = core_utils.make_logger(_logger, method_name=self.function_name)
        tmpLog.debug('start')
        if self.conn is None:
            tmpLog.warning('connection is not alive; method {0} returns None'.format(self.function_name))
            return None
        params = {'plugin_config': self.plugin_config,
                  'function_name': self.function_name,
                  'args': pickle.dumps(args),
                  'kwargs': pickle.dumps(kwargs)}
        stdout, stderr = self.conn.communicate(input=json.dumps(params))
        if self.conn.returncode == 0:
            return_dict = json.loads(stdout)
            if 'exception' in return_dict:
                errMsg = pickle.loads(str(return_dict['dialog']))
                tmpLog.error('Exception from remote : ' + errMsg)
                raise pickle.loads(str(return_dict['exception']))
            # propagate changes in mutable args
            new_args = pickle.loads(str(return_dict['args']))
            for old_arg, new_arg in zip(args, new_args):
                if isinstance(old_arg, types.ListType):
                    del old_arg[:]
                    old_arg += new_arg
                elif isinstance(old_arg, types.DictionaryType):
                    old_arg.clear()
                    old_arg.update(new_arg)
                elif hasattr(old_arg, '__dict__'):
                    old_arg.__dict__ = new_arg.__dict__
            new_kwargs = pickle.loads(str(return_dict['kwargs']))
            for key in kwargs:
                old_kwarg = kwargs[key]
                new_kwarg = new_kwargs[key]
                if isinstance(old_kwarg, types.ListType):
                    del old_kwarg[:]
                    old_kwarg += new_kwarg
                elif isinstance(old_kwarg, types.DictionaryType):
                    old_kwarg.clear()
                    old_kwarg.update(new_kwarg)
                elif hasattr(old_kwarg, '__dict__'):
                    old_kwarg.__dict__ = new_kwarg.__dict__
            return pickle.loads(str(return_dict['return']))
        else:
            tmpLog.error('execution failed with {0}; method={1} returns None'.format(self.conn.returncode,
                                                                                     self.function_name))
            return None


# Direct SSH herder 
Example 49
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 50
Project: SUMO_dy_public   Author: DayuanTan   File: objpanel.py    GNU General Public License v3.0 4 votes vote down vote up
def SetValue(self, row, col, value):
        """
        Transfer of cell value to object.
        """
        id, attrconf = self.get_id_attrconf(row, col)
        if attrconf != None:
            if attrconf.is_writable():
                # print 'SetValue(%d, %d, "%s").\n' % (row, col, value)

                # print '    attrconf',id,attrconf.attrname, attrconf.is_writable(),hasattr(attrconf,'choices')
                # attr=self.attrs[col]
                tt = type(attrconf.get_default())
                if hasattr(attrconf, 'choices'):
                    # print '
                    # type(attrconf.choices)',type(attrconf.choices),type(attrconf.choices)
                    # in (OrderedDict, types.DictionaryType)
                    # (types.ListType, types.TupleType):
                    if type(attrconf.choices) in (OrderedDict, types.DictionaryType):
                        # print '  set choices[value]',attrconf.choices[value]
                        if attrconf.choices.has_key(value):
                            attrconf[id] = attrconf.choices[value]
                        else:
                            attrconf[id] = value

                    else:
                        # print '  set value',value
                        attrconf[id] = value

                if (tt in (types.BooleanType, types.FloatType, types.IntType, types.LongType, types.StringType, types.UnicodeType, types.ComplexType)):
                    # set only values of types that are allowed for the grid
                    # TODO: this grid types data must be organized more central
                    attrconf[id] = value
                else:
                    # TODO: for other types, like color or arrays, this must be
                    # done beforehand
                    print 'WARNING in SetValue: cannot write to this type:', tt
            else:
                # readonly
                pass
                # print 'SetValue(%d, %d, "%s") read only.\n' % (row, col,
                # value)

#--------------------------------------------------
    # Some optional methods

    # Called when the grid needs to display labels