def test_apply_history(self):
        """Tests the reapply history argument"""
        self.logTestName()

        a = 0.23
        r = 0.1

        def inspect():
            res = []
            print_fn = lambda x: res.append(x.__str__())
            self.eng.print_applied(print_fn)
            return res

        q = self.eng.register
        with self.eng:
            Dgate(a) | q[0]
            Sgate(r) | q[1]

        state1 = self.eng.run()
        expected = [
            'Run 0:', 'Dgate({}, 0) | (q[0])'.format(a),
            'Sgate({}, 0) | (q[1])'.format(r)
        ]
        self.assertEqual(inspect(), expected)

        # reset backend, but reapply history
        self.backend.reset(pure=self.kwargs["pure"])
        state2 = self.eng.run(backend=self.backend, apply_history=True)
        self.assertEqual(inspect(), expected)
        self.assertEqual(state1, state2)

        # append more commands to the same backend
        with self.eng:
            Rgate(r) | q[0]

        state3 = self.eng.run()
        expected = [
            'Run 0:',
            'Dgate({}, 0) | (q[0])'.format(a),
            'Sgate({}, 0) | (q[1])'.format(r),
            'Run 1:',
            'Rgate({}) | (q[0])'.format(r),
        ]
        self.assertEqual(inspect(), expected)
        self.assertNotEqual(state2, state3)

        # reset backend, but reapply history
        self.backend.reset(pure=self.kwargs["pure"])
        state4 = self.eng.run(backend=self.backend, apply_history=True)
        expected = [
            'Run 0:',
            'Dgate({}, 0) | (q[0])'.format(a),
            'Sgate({}, 0) | (q[1])'.format(r),
            'Rgate({}) | (q[0])'.format(r),
        ]
        self.assertEqual(inspect(), expected)
        self.assertEqual(state3, state4)
Beispiel #2
0
    def row_to_dict(row, ignore_properties: [] = None):
        d = {}

        if row is None:
            return None
        if isinstance(row, RowProxy):
            for column, value in row.items():
                # build up the dictionary
                d = {**d, **{column: value}}
        elif isinstance(row, dict):
            d = row
        elif not hasattr(row, '__dict__'):
            # is_primitive
            return row
        else:
            for c in inspect(row).attrs.keys():
                # build up the dictionary
                d = {**d, **{c: ObjectMapper.row_to_dict(getattr(row, c))}}

        if ignore_properties and len(ignore_properties):
            for prop in ignore_properties:
                removeproperty: [str] = prop.split('.')
                d = ObjectMapper.remove_property_from_dict_recursively(
                    d, removeproperty)
        return d
Beispiel #3
0
    def print(self, pipeline_name=None):
        if pipeline_name:
            nodes = list(
                nx.algorithms.dag.descendants(
                    self.meas_graph,
                    self.get_stream_selector(pipeline_name).hash_val)) + [
                        self.get_stream_selector(pipeline_name).hash_val
                    ]
        else:
            nodes = self.meas_graph.nodes()
        table_code = ""

        for node in nodes:
            if not isinstance(node, adb.StreamSelect):
                node = self.meas_graph.nodes[node]['node_obj']
            label = node.label if node.label else "Unlabeled"
            table_code += f"<tr><td><b>{node.node_type}</b> ({node.qubit_name})</td><td></td><td><i>{label}</i></td></td><td></tr>"
            inspr = inspect(node)
            for c in list(node.__mapper__.columns):
                if c.name not in ["id", "label", "qubit_name", "node_type"]:
                    hist = getattr(inspr.attrs, c.name).history
                    dirty = "Yes" if hist.has_changes() else ""
                    if c.name == "kernel_data":
                        table_code += f"<tr><td></td><td>{c.name}</td><td>Binary Data of length {len(node.kernel)}</td><td>{dirty}</td></tr>"
                    else:
                        table_code += f"<tr><td></td><td>{c.name}</td><td>{getattr(node,c.name)}</td><td>{dirty}</td></tr>"
        display(
            HTML(
                f"<table><tr><th>Name</th><th>Attribute</th><th>Value</th><th>Uncommitted Changes</th></tr><tr>{table_code}</tr></table>"
            ))
Beispiel #4
0
    def __init__(self, class_, includes=None, excludes=None, overrides=None, unknown='ignore', nested=False, type_overrides=None, relationship_overrides=None, automatic_relationships=False, **kw):
        """
        :param includes:
        :param overrides:
        :param unknown:
        :param type_overrides: callable(name, column, column_type)
        :param automatic_relationships: Only follow relationships if they are on include list
        :param kw:
        :return:
        """
        assert type_overrides, "Always provide type_overrides, otherwise this crap doesn't work when these nodes get nested"

        self.inspector = inspect(class_)
        kwargs = kw.copy()

        # Obtain configuration specific from the mapped class
        kwargs.update(getattr(self.inspector.class_, self.ca_class_key, {}))
        unknown = kwargs.pop('unknown', unknown)

        # The default type of this SchemaNode is Mapping.
        super(SQLAlchemySchemaNode, self).__init__(Mapping(unknown), **kwargs)
        self.class_ = class_
        self.includes = includes or {}
        self.excludes = excludes or {}
        self.overrides = overrides or {}
        self.unknown = unknown
        self.declarative_overrides = {}
        self.kwargs = kwargs or {}
        self.type_overrides = type_overrides
        self.relationship_overrides = relationship_overrides
        self.nested = nested
        self.automatic_relationships = automatic_relationships
        self.add_nodes(self.includes, self.excludes, self.overrides, nested)
Beispiel #5
0
 def get(self):
     from celery.task.control import inspect
     i = inspect()
     data = dict()
     if i.registered_tasks():
         for k, v in i.registered_tasks().iteritems():
             data[k] = v
     self.write(data)
Beispiel #6
0
    def inspect_modules(self, *modnames, referenced=0):
        """
        Imports and inspects modules.

        @param referenced
          Whether to inspect referenced modules.  If `False`, does not inspect
          referenced modules.  If 1, inspects only modules referenced directly
          by modules in `modnames`.  If `True`, inspects all directly and
          indirectly referenced modules.
        """
        # Mapping from modname to module objdoc.
        objdocs = {}

        # Set up an inspector for our modules.
        def inspect(modname):
            if modname not in objdocs:
                objdocs[modname] = self.inspect_module(modname)

        # Inspect modules.
        for modname in modnames:
            inspect(modname)

        if referenced:
            # Inspect referenced modules.
            remaining = self.referenced_modnames - set(objdocs)
            while len(remaining) > 0:
                for modname in remaining:
                    inspect(modname)
                if referenced == 1:
                    break

        # Parse and process docstrings.
        from . import docs
        docs.enrich_modules(objdocs)

        return {"modules": objdocs}
Beispiel #7
0
def is_instance_method(klazz, name):
    '''
    does this class have this method?
    '''
    return (inspect(klazz, name)[0] is INSTANCE_METHOD)
Beispiel #8
0
def countries(name):
    stmt = db.session.query(country).filter(country.Name == name).all()
    inst = inspect(country)
    MyDict = {}
    for result in stmt:
        MyDict['Name'] = result.Name
        MyDict['1960'] = result.one
        MyDict['1961'] = result.two
        MyDict['1962'] = result.three
        MyDict['1963'] = result.four
        MyDict['1964'] = result.five
        MyDict['1965'] = result.six
        MyDict['1966'] = result.seven
        MyDict['1967'] = result.eight
        MyDict['1968'] = result.nine
        MyDict['1969'] = result.ten
        MyDict['1970'] = result.eleven
        MyDict['1971'] = result.twelve
        MyDict['1972'] = result.thirteen
        MyDict['1973'] = result.fourteen
        MyDict['1974'] = result.fifteen
        MyDict['1975'] = result.sixteen
        MyDict['1976'] = result.seventeen
        MyDict['1977'] = result.eighteen
        MyDict['1978'] = result.nineteen
        MyDict['1979'] = result.twenty
        MyDict['1980'] = result.twentyone
        MyDict['1981'] = result.twentytwo
        MyDict['1982'] = result.twentythree
        MyDict['1983'] = result.twentyfour
        MyDict['1984'] = result.twentyfive
        MyDict['1985'] = result.twentysix
        MyDict['1986'] = result.twentyseven
        MyDict['1987'] = result.twentyeight
        MyDict['1988'] = result.twentynine
        MyDict['1989'] = result.thirty
        MyDict['1990'] = result.thirtyone
        MyDict['1991'] = result.thirtytwo
        MyDict['1992'] = result.thirtythree
        MyDict['1993'] = result.thirtyfour
        MyDict['1994'] = result.thirtyfive
        MyDict['1995'] = result.thirtysix
        MyDict['1996'] = result.thirtyseven
        MyDict['1997'] = result.thirtyeight
        MyDict['1998'] = result.thirtynine
        MyDict['1999'] = result.fourty
        MyDict['2000'] = result.fourtyone
        MyDict['2001'] = result.fourtytwo
        MyDict['2002'] = result.fourtythree
        MyDict['2003'] = result.fourtyfour
        MyDict['2004'] = result.fourtyfive
        MyDict['2005'] = result.fourtysix
        MyDict['2006'] = result.fourtyseven
        MyDict['2007'] = result.fourtyeight
        MyDict['2008'] = result.fourtynine
        MyDict['2009'] = result.fifty
        MyDict['2010'] = result.fiftyone
        MyDict['2011'] = result.fiftytwo
        MyDict['2012'] = result.fiftythree
        MyDict['2013'] = result.fiftyfour
        MyDict['2014'] = result.fiftyfive
        MyDict['2015'] = result.fiftysix
        MyDict['2016'] = result.fiftyseven
        MyDict['2017'] = result.fiftyeight
        MyDict['2018'] = result.fiftynine

    return jsonify(MyDict)
Beispiel #9
0
    def get_schema_from_relationship(self, prop, overrides):
        """Extended for property support."""

        # The name of the SchemaNode is the ColumnProperty key.
        name = prop.key
        kwargs = dict(name=name)
        declarative_overrides = prop.info.get(self.sqla_info_key, {}).copy()
        self.declarative_overrides[name] = declarative_overrides.copy()

        class_ = prop.mapper

        if declarative_overrides.pop('exclude', False):
            log.debug('Relationship %s skipped due to declarative overrides',
                      name)
            return None

        for key in ['name', 'typ']:
            self.check_overrides(name, key, {}, declarative_overrides,
                                 overrides)

        key = 'children'
        imperative_children = overrides.pop(key, None)
        declarative_children = declarative_overrides.pop(key, None)
        if imperative_children is not None:
            children = imperative_children
            msg = 'Relationship %s: %s overridden imperatively.'
            log.debug(msg, name, key)

        elif declarative_children is not None:
            children = declarative_children
            msg = 'Relationship %s: %s overridden via declarative.'
            log.debug(msg, name, key)

        else:
            children = None

        key = 'includes'
        imperative_includes = overrides.pop(key, None)
        declarative_includes = declarative_overrides.pop(key, None)
        if imperative_includes is not None:
            includes = imperative_includes
            msg = 'Relationship %s: %s overridden imperatively.'
            log.debug(msg, name, key)

        elif declarative_includes is not None:
            includes = declarative_includes
            msg = 'Relationship %s: %s overridden via declarative.'
            log.debug(msg, name, key)

        else:
            includes = None

        # TODO: Utmost piece of garbage here.. remove this
        if not self.automatic_relationships:
            if name not in (self.includes or ()):
                log.debug("Does not construct relationship for %s unless explicitly included", name)
                return None

        if self.relationship_overrides:

            result = self.relationship_overrides(self, name, prop, class_)
            if result == TypeOverridesHandling.drop:
                return None
            elif result == TypeOverridesHandling.unknown:
                pass
            else:
                assert isinstance(result, colander.SchemaNode)
                return result

        key = 'excludes'
        imperative_excludes = overrides.pop(key, None)
        declarative_excludes = declarative_overrides.pop(key, None)

        if imperative_excludes is not None:
            excludes = imperative_excludes
            msg = 'Relationship %s: %s overridden imperatively.'
            log.debug(msg, name, key)

        elif declarative_excludes is not None:
            excludes = declarative_excludes
            msg = 'Relationship %s: %s overridden via declarative.'
            log.debug(msg, name, key)

        else:
            excludes = None

        # see issue #25 in ColanderAlchemy for possible patch
        if includes is None and excludes is None:
            includes = [p.key for p in inspect(class_).column_attrs]

        key = 'overrides'
        imperative_rel_overrides = overrides.pop(key, None)
        declarative_rel_overrides = declarative_overrides.pop(key, None)

        if imperative_rel_overrides is not None:
            rel_overrides = imperative_rel_overrides
            msg = 'Relationship %s: %s overridden imperatively.'
            log.debug(msg, name, key)

        elif declarative_rel_overrides is not None:
            rel_overrides = declarative_rel_overrides
            msg = 'Relationship %s: %s overridden via declarative.'
            log.debug(msg, name, key)

        else:
            rel_overrides = None

        # Add default values for missing parameters.
        if prop.innerjoin:
            # Inner joined relationships imply it is mandatory
            missing = required
        else:
            # Any other join is thus optional
            missing = []
        kwargs['missing'] = missing

        kwargs.update(declarative_overrides)
        kwargs.update(overrides)

        if children is not None:
            if prop.uselist:
                # xToMany relationships.
                return SchemaNode(Sequence(), *children, **kwargs)
            else:
                # xToOne relationships.
                return SchemaNode(Mapping(), *children, **kwargs)

        node = PropertyAwareSQLAlchemySchemaNode(class_,
                                    name=name,
                                    includes=includes,
                                    excludes=excludes,
                                    overrides=rel_overrides,
                                    missing=missing,
                                    type_overrides=self.type_overrides,
                                    relationship_overrides=self.relationship_overrides)

        if prop.uselist:
            node = SchemaNode(Sequence(), node, **kwargs)

        node.name = name

        return node
Beispiel #10
0
import inspect
from collections import namedtuple
from geometry_msgs.msg import Transform


rotation = namedtuple("Rotation",["x","y","z"])
rotation.x=1
rotation.y=1
rotation.z=1
translation = namedtuple("Translation",["x","y","z","Theta"])
translation.x=0
translation.y=0
translation.z=0
translation.Theta=0

t1=Transform(rotation,translation)

print t1
print t1.rotation.x
print t1.rotation.y
print t1.rotation.z
print inspect(Transform.__init__)
Beispiel #11
0
 def object_as_dict(obj):
     return {
         c.key: getattr(obj, c.key)
         for c in inspect(obj).mapper.column_attrs
     }
Beispiel #12
0
    def _inspect_node(self):
        console = Console(self.shell.pty)

        def inspect():
            # Print full name
            yield termcolor.colored('  Node:    ', 'cyan') + \
                  termcolor.colored(Inspector(self.node).get_full_name(), 'yellow')

            # Print mro
            yield termcolor.colored('  Mro:', 'cyan')
            i = 1
            for m in self.node.__class__.__mro__:
                if m.__module__ != 'deployer.node' and m != object:
                    yield termcolor.colored('              %i ' % i, 'cyan') + \
                          termcolor.colored('%s.' % m.__module__, 'red') + \
                          termcolor.colored('%s' % m.__name__, 'yellow')
                    i += 1

            # File names
            yield termcolor.colored('  Files:', 'cyan')
            i = 1
            for m in self.node.__class__.__mro__:
                if m.__module__ != 'deployer.node' and m != object:
                    yield termcolor.colored('              %i ' % i, 'cyan') + \
                          termcolor.colored(getfile(m), 'red')
                    i += 1

            # Print host mappings
            yield termcolor.colored('  Hosts:', 'cyan')

            for role in sorted(self.node.hosts._hosts.keys()):
                items = self.node.hosts._hosts[role]
                yield termcolor.colored('         "%s"' % role, 'yellow')
                i = 1
                for host in sorted(items, key=lambda h:h.slug):
                    yield termcolor.colored('            %3i ' % i, 'cyan') + \
                          termcolor.colored('%-25s (%s)' % (host.slug, getattr(host, 'address', '')), 'red')
                    i += 1

            # Print the first docstring (look to the parents)
            for m in self.node.__class__.__mro__:
                if m.__module__ != 'deployer.node' and m != object and m.__doc__:
                    yield termcolor.colored('  Docstring:\n', 'cyan') + \
                          termcolor.colored(m.__doc__ or '<None>', 'red')
                    break

            # Actions
            yield termcolor.colored('  Actions:', 'cyan')

            def item_iterator():
                for a in Inspector(self.node).get_actions():
                    yield termcolor.colored(a.name, 'red'), len(a.name)

            for line in console.in_columns(item_iterator(), margin_left=13):
                yield line

            # Nodes
            yield termcolor.colored('  Sub nodes:', 'cyan')

                # Group by node group
            grouper = lambda c:Inspector(c).get_group()
            for group, nodes in groupby(sorted(Inspector(self.node).get_childnodes(), key=grouper), grouper):
                yield termcolor.colored('         "%s"' % group.name, 'yellow')

                # Create iterator for all the items in this group
                def item_iterator():
                    for n in nodes:
                        name = Inspector(n).get_name()

                        if n.parent == self.node:
                            text = termcolor.colored(name, type_of_node(n).color)
                            length = len(name)
                        else:
                            full_name = Inspector(n).get_full_name()
                            text = termcolor.colored('%s -> %s' % (name, full_name), type_of_node(n).color)
                            length = len('%s -> %s' % (name, full_name))
                        yield text, length

                # Show in columns
                for line in console.in_columns(item_iterator(), margin_left=13):
                    yield line

        console.lesspipe(inspect())
Beispiel #13
0
def is_instance_method(object, name):
    """
    does this class have this method?
    """
    return inspect(object, name)[0] is INSTANCE_METHOD
Beispiel #14
0
def is_instance_method(object, name):
    '''
    does this class have this method?
    '''
    return (inspect(object, name)[0] is INSTANCE_METHOD)
Beispiel #15
0
def Inspect(self):
    """
    Inspection of the current service. Show host mappings and other information.
    """
    def inspect():
        # Print full name
        yield termcolor.colored('  Service:    ', 'cyan') + \
              termcolor.colored(self.service.__repr__(path_only=True), 'yellow')

        # Service class definition created on
        yield termcolor.colored('  Created on: ', 'cyan') + \
              termcolor.colored(self.service._creation_date, 'red')


        # Print mro
        yield termcolor.colored('  Mro:', 'cyan')
        i = 1
        for m in self.service.__class__.__mro__:
            if m.__module__ != 'deployer.service' and m != object:
                yield termcolor.colored('              %i ' % i, 'cyan') + \
                      termcolor.colored('%s.' % m.__module__, 'red') + \
                      termcolor.colored('%s' % m.__name__, 'yellow')
                i += 1

        # File names
        yield termcolor.colored('  Files:', 'cyan')
        i = 1
        for m in self.service.__class__.__mro__:
            if m.__module__ != 'deployer.service' and m != object:
                yield termcolor.colored('              %i ' % i, 'cyan') + \
                      termcolor.colored(getfile(m), 'red')
                i += 1

        # Print host mappings
        yield termcolor.colored('  Hosts:', 'cyan')

        for role in sorted(self.service.hosts._hosts.keys()):
            items = self.service.hosts._hosts[role]
            yield termcolor.colored('         "%s"' % role, 'yellow')
            i = 1
            for host in sorted(items, key=lambda h:h.slug):
                yield termcolor.colored('            %3i ' % i, 'cyan') + \
                      termcolor.colored('%-25s (%s)' % (host.slug, getattr(host, 'address', '')), 'red')
                i += 1

        # Print the first docstring (look to the parents)
        for m in self.service.__class__.__mro__:
            if m.__module__ != 'deployer.service' and m != object and m.__doc__:
                yield termcolor.colored('  Docstring:\n', 'cyan') + \
                      termcolor.colored(m.__doc__ or '<None>', 'red')
                break

        # Actions
        yield termcolor.colored('  Actions:', 'cyan')

        def item_iterator():
            for name, a in self.service.get_actions():
                yield termcolor.colored(name, 'red'), len(name)

        for line in in_columns(item_iterator(), self.shell.pty, margin_left=13):
            yield line

        # Services
        yield termcolor.colored('  Sub services:', 'cyan')

            # Group by service group
        grouper = lambda i:i[1].get_group()
        for group, services in groupby(sorted(self.service.get_subservices(), key=grouper), grouper):
            yield termcolor.colored('         "%s"' % group.__name__, 'yellow')

            # Create iterator for all the items in this group
            def item_iterator():
                for name, s in services:
                    if s.parent == self.service:
                        text = termcolor.colored(name, type_of_service(s).color)
                        length = len(name)
                    else:
                        text = termcolor.colored('%s -> %s' % (name, s.__repr__(path_only=True)), type_of_service(s).color)
                        length = len('%s -> %s' % (name, s.__repr__(path_only=True)))
                    yield text, length

            # Show in columns
            for line in in_columns(item_iterator(), self.shell.pty, margin_left=13):
                yield line

    lesspipe(inspect(), self.shell.pty)
Beispiel #16
0
def sql_alchemy_object_as_dict(obj):
    from sqlalchemy import inspect
    return {c.key: getattr(obj, c.key)
            for c in inspect(obj).mapper.column_attrs}
Beispiel #17
0
import inspect


class Foo(object):
    '''Foo doc'''
    def __init__(self, name):
        self.__name = name

    def getname(self):
        return self.__name


def show():
    print('hello')


print(inspect.getmembers(show, inspect.ismethod))
print(inspect.getsource(Foo))
obj = Foo('you')
print(inspect.isclass(Foo))
print(inspect())
Beispiel #18
0
# In[2]:

from datetime import datetime
result = tasks.add.apply_async(args=[1,2], eta=datetime(2014, 6, 12, 0, 0))
result = tasks.add.apply_async(args=[1,2], countdown=10)
r = tasks.add.delay()

r = tasks.add.apply_async(args=[2, 3], queues='email')

from celery.task.control import revoke
revoke(id)
revoke(id, terminate=True)

from celery.task.control import inspect
i = inspect()
i.scheduled()
i.active()
i.registered()


# task result
result = my_task.apply_async(args=[1,2])
result.ready()
result.state


# workers

celery -A apps.project.tasks worker -l info
Beispiel #19
0
    "first", ["rock", "paper"])
first_one_hot = feature_column.indicator_column(first)
feature_columns.append(first_one_hot)

second = feature_column.categorical_column_with_vocabulary_list(
    "second", ["rock", "paper"])
second_one_hot = feature_column.indicator_column(second)
feature_columns.append(second_one_hot)

crossed_feature = feature_column.crossed_column([first, second],
                                                hash_bucket_size=1000)
crossed_feature = feature_column.indicator_column(crossed_feature)

inspect.getargspec(crossed_feature.create_state)

inspect(crossed_feature.index)
dir(crossed_feature)

feature_columns.append(crossed_feature)

feature_layer = tf.keras.layers.DenseFeatures(feature_columns)

model = tf.keras.Sequential([
    feature_layer,
    layers.Dense(32, activation='relu'),
    layers.Dense(16, activation='relu'),
    layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam',
              loss='binary_crossentropy',
import pickle
from link import *
from datetime import timedelta
import random


def inspect():
	# p: procedure
	p = raw_input("procedure:")	
	path = "/home/jelte/Scriptie/python/"+p+".p"
	list = pickle.load(open(path,"rb"))
	random.shuffle(list)
	engine = create_engine('mysql://*****:*****@localhost/zl_work')
	
	#q = "SELECT familyname as al, firstname as af, sex, mother_familyname as ml, mother_firstname as mf, familyname as fl, father_firstname as ff, ((birth_min_days+birth_max_days)/2) as bd, role, id_person as id FROM ps_working WHERE id_person="+str(3743176)+" or id_person="+str(4192882)
	#print sql.read_sql(q,engine).head(2)
	

	for m1,m2 in list:
		q = "SELECT familyname as al, firstname1 as af, sex, mother_familyname as ml, mother_firstname as mf, familyname as fl, father_firstname as ff, ((birth_min_days+birth_max_days)/2) as bd, role, id_person as id FROM ps_working WHERE id_person="+str(m1)+" or id_person="+str(m2)
		df = sql.read_sql(q,engine)
		print df.head(2)		
		raw_input("..") 

	

inspect()


	
Beispiel #21
0
    def _inspect_node(self):
        console = Console(self.shell.pty)

        def inspect():
            # Print full name
            yield termcolor.colored('  Node:    ', 'cyan') + \
                  termcolor.colored(Inspector(self.node).get_full_name(), 'yellow')

            # Print mro
            yield termcolor.colored('  Mro:', 'cyan')
            i = 1
            for m in self.node.__class__.__mro__:
                if m.__module__ != 'deployer.node' and m != object:
                    yield termcolor.colored('              %i ' % i, 'cyan') + \
                          termcolor.colored('%s.' % m.__module__, 'red') + \
                          termcolor.colored('%s' % m.__name__, 'yellow')
                    i += 1

            # File names
            yield termcolor.colored('  Files:', 'cyan')
            i = 1
            for m in self.node.__class__.__mro__:
                if m.__module__ != 'deployer.node' and m != object:
                    yield termcolor.colored('              %i ' % i, 'cyan') + \
                          termcolor.colored(getfile(m), 'red')
                    i += 1

            # Print host mappings
            yield termcolor.colored('  Hosts:', 'cyan')

            for role in sorted(self.node.hosts._hosts.keys()):
                items = self.node.hosts._hosts[role]
                yield termcolor.colored('         "%s"' % role, 'yellow')
                i = 1
                for host in sorted(items, key=lambda h: h.slug):
                    yield termcolor.colored('            %3i ' % i, 'cyan') + \
                          termcolor.colored('%-25s (%s)' % (host.slug, getattr(host, 'address', '')), 'red')
                    i += 1

            # Print the first docstring (look to the parents)
            for m in self.node.__class__.__mro__:
                if m.__module__ != 'deployer.node' and m != object and m.__doc__:
                    yield termcolor.colored('  Docstring:\n', 'cyan') + \
                          termcolor.colored(m.__doc__ or '<None>', 'red')
                    break

            # Actions
            yield termcolor.colored('  Actions:', 'cyan')

            def item_iterator():
                for a in Inspector(self.node).get_actions():
                    yield termcolor.colored(a.name, 'red'), len(a.name)

            for line in console.in_columns(item_iterator(), margin_left=13):
                yield line

            # Nodes
            yield termcolor.colored('  Sub nodes:', 'cyan')

            # Group by node group
            grouper = lambda c: Inspector(c).get_group()
            for group, nodes in groupby(
                    sorted(Inspector(self.node).get_childnodes(), key=grouper),
                    grouper):
                yield termcolor.colored('         "%s"' % group.name, 'yellow')

                # Create iterator for all the items in this group
                def item_iterator():
                    for n in nodes:
                        name = Inspector(n).get_name()

                        if n.parent == self.node:
                            text = termcolor.colored(name,
                                                     type_of_node(n).color)
                            length = len(name)
                        else:
                            full_name = Inspector(n).get_full_name()
                            text = termcolor.colored(
                                '%s -> %s' % (name, full_name),
                                type_of_node(n).color)
                            length = len('%s -> %s' % (name, full_name))
                        yield text, length

                # Show in columns
                for line in console.in_columns(item_iterator(),
                                               margin_left=13):
                    yield line

        console.lesspipe(inspect())
Beispiel #22
0
import inspect
from collections import namedtuple
from geometry_msgs.msg import Transform

rotation = namedtuple("Rotation", ["x", "y", "z"])
rotation.x = 1
rotation.y = 1
rotation.z = 1
translation = namedtuple("Translation", ["x", "y", "z", "Theta"])
translation.x = 0
translation.y = 0
translation.z = 0
translation.Theta = 0

t1 = Transform(rotation, translation)

print t1
print t1.rotation.x
print t1.rotation.y
print t1.rotation.z
print inspect(Transform.__init__)
def _inspect_mixin(self, *args, **kwargs):
    return inspect(self, *args, **kwargs)
Beispiel #24
0
 def get_row_dic(row):
     return {
         c.key: getattr(row, c.key)
         for c in inspect(row).mapper.column_attrs
     }