Example #1
1
        def _print_summrized_result(result):
            raw = result["data"]["raw"]
            table_cols = ["action", "min", "median", "90%ile", "95%ile", "max", "avg", "success", "count"]
            float_cols = ["min", "median", "90%ile", "95%ile", "max", "avg"]
            formatters = dict(zip(float_cols, [cliutils.pretty_float_formatter(col, 3) for col in float_cols]))
            table_rows = []

            actions_data = utils.get_atomic_actions_data(raw)
            for action in actions_data:
                durations = actions_data[action]
                if durations:
                    data = [
                        action,
                        round(min(durations), 3),
                        round(utils.median(durations), 3),
                        round(utils.percentile(durations, 0.90), 3),
                        round(utils.percentile(durations, 0.95), 3),
                        round(max(durations), 3),
                        round(utils.mean(durations), 3),
                        "%.1f%%" % (len(durations) * 100.0 / len(raw)),
                        len(raw),
                    ]
                else:
                    data = [action, None, None, None, None, None, None, "0.0%", len(raw)]
                table_rows.append(rutils.Struct(**dict(zip(table_cols, data))))

            cliutils.print_list(
                table_rows,
                fields=table_cols,
                formatters=formatters,
                table_label="Response Times (sec)",
                sortby_index=None,
            )
Example #2
1
    def __init__(self, session: Session, config, loop=None):
        self.logger = logging.getLogger(__name__)
        self.session = session
        self.config = config
        if loop is None:
            self._loop = asyncio.get_event_loop()
        else:
            self._loop = loop
        self._reader_task = None
        self._writer_task = None
        self._inflight_task = None
        self._reader_ready = asyncio.Event(loop=self._loop)
        self._writer_ready = asyncio.Event(loop=self._loop)
        self._inflight_ready = asyncio.Event(loop=self._loop)
        self._inflight_changed = asyncio.Condition(loop=self._loop)

        self._running = False

        self.session.local_address, self.session.local_port = self.session.writer.get_extra_info("sockname")

        self.incoming_queues = dict()
        for p in PacketType:
            self.incoming_queues[p] = asyncio.Queue()
        self.outgoing_queue = asyncio.Queue()
        self.inflight_messages = dict()
Example #3
1
    def drilldown_map(self):
        diseases = []
        disease_fixtures = FixtureDataItem.by_data_type(
            self.domain, FixtureDataType.by_domain_tag(self.domain, "diseases").one()
        )
        for d in disease_fixtures:
            disease = dict(
                val="%(name)s:%(uid)s" % {"name": d.fields["disease_id"], "uid": d.get_id},
                text=d.fields["disease_name"],
            )
            tests = []
            test_fixtures = FixtureDataItem.by_field_value(
                self.domain,
                FixtureDataType.by_domain_tag(self.domain, "test").one(),
                "disease_id",
                d.fields["disease_id"],
            )
            for t in test_fixtures:
                tests.append(
                    dict(
                        val="%(name)s:%(uid)s" % {"name": t.fields["test_name"], "uid": t.get_id},
                        text=t.fields["visible_test_name"],
                    )
                )
            disease["next"] = tests
            diseases.append(disease)

        return diseases
Example #4
1
File: core.py Project: jdmcbr/toolz
def merge_with(fn, *dicts):
    """ Merge dictionaries and apply function to combined values

    A key may occur in more than one dict, and all values mapped from the key
    will be passed to the function as a list, such as fn([val1, val2, ...]).

    >>> merge_with(sum, {1: 1, 2: 2}, {1: 10, 2: 20})
    {1: 11, 2: 22}

    >>> merge_with(first, {1: 1, 2: 2}, {2: 20, 3: 30})  # doctest: +SKIP
    {1: 1, 2: 2, 3: 30}

    See Also:
        merge
    """
    if len(dicts) == 1 and not isinstance(dicts[0], dict):
        dicts = dicts[0]

    result = dict()
    for d in dicts:
        for k, v in d.items():
            try:
                result[k].append(v)
            except:
                result[k] = [v]
    return dict((k, fn(v)) for k, v in result.items())
Example #5
1
    def fire_ready(cls):
        """Fires all direct subscriptions with notifications as well as
        all summary & digest subscriptions with notifications that are ready.
        Clears the mailbox queue.
        """
        now = datetime.utcnow()
        # Queries to find all matching subscription objects
        q_direct = dict(type="direct", queue_empty=False)
        if MAILBOX_QUIESCENT:
            q_direct["last_modified"] = {"$lt": now - MAILBOX_QUIESCENT}
        q_digest = dict(type={"$in": ["digest", "summary"]}, next_scheduled={"$lt": now})

        def find_and_modify_direct_mbox():
            return cls.query.find_and_modify(
                query=q_direct, update={"$set": dict(queue=[], queue_empty=True)}, new=False
            )

        for mbox in take_while_true(find_and_modify_direct_mbox):
            mbox.fire(now)

        for mbox in cls.query.find(q_digest):
            next_scheduled = now
            if mbox.frequency.unit == "day":
                next_scheduled += timedelta(days=mbox.frequency.n)
            elif mbox.frequency.unit == "week":
                next_scheduled += timedelta(days=7 * mbox.frequency.n)
            elif mbox.frequency.unit == "month":
                next_scheduled += timedelta(days=30 * mbox.frequency.n)
            mbox = cls.query.find_and_modify(
                query=dict(_id=mbox._id),
                update={"$set": dict(next_scheduled=next_scheduled, queue=[], queue_empty=True)},
                new=False,
            )
            mbox.fire(now)
Example #6
1
    def test_add_visible_admin_metadata_visible_key_only(self):
        admin_metadata = [
            {"key": "invisible_key", "value": "invisible_value"},
            {"key": "readonly", "value": "visible"},
            {"key": "attached_mode", "value": "visible"},
        ]
        metadata = [{"key": "key", "value": "value"}]
        volume = dict(volume_admin_metadata=admin_metadata, volume_metadata=metadata)
        admin_ctx = context.get_admin_context()
        self.controller._add_visible_admin_metadata(admin_ctx, volume)
        self.assertEqual(
            volume["volume_metadata"],
            [
                {"key": "key", "value": "value"},
                {"key": "readonly", "value": "visible"},
                {"key": "attached_mode", "value": "visible"},
            ],
        )

        admin_metadata = {"invisible_key": "invisible_value", "readonly": "visible", "attached_mode": "visible"}
        metadata = {"key": "value"}
        volume = dict(admin_metadata=admin_metadata, metadata=metadata)
        admin_ctx = context.get_admin_context()
        self.controller._add_visible_admin_metadata(admin_ctx, volume)
        self.assertEqual(volume["metadata"], {"key": "value", "attached_mode": "visible", "readonly": "visible"})
Example #7
1
    def to_orange_network(self):
        """Convert the current network to >>Orange<< NetworkX standard. To use
        :obj:`Orange.network` in Orange widgets, set node IDs to be range 
        [0, no_of_nodes - 1].
        
        """

        G = self.__class__()
        node_list = sorted(self.nodes())
        node_to_index = dict(zip(node_list, range(self.number_of_nodes())))
        index_to_node = dict(zip(range(self.number_of_nodes()), node_list))

        G.add_nodes_from(zip(range(self.number_of_nodes()), [copy.deepcopy(self.node[nid]) for nid in node_list]))
        G.add_edges_from(
            ((node_to_index[u], node_to_index[v], copy.deepcopy(self.edge[u][v])) for u, v in self.edges())
        )

        for id in G.node.keys():
            G.node[id]["old_id"] = index_to_node[id]

        if self.items():
            G.set_items(self.items())

        if self.links():
            G.set_links(self.links())

        return G
Example #8
1
    def dehydrate_members(self, bundle):
        rangesString = bundle.request.GET.get("ranges", None)
        fullRange = rangesString is None
        if not fullRange:
            ranges = map(
                lambda rangeString: [datetime.strptime(val, "%Y%m") if val else None for val in rangeString.split("-")],
                rangesString.split(","),
            )
            mks_values = dict(bundle.obj.get_mks_values(ranges))
        else:
            mks_values = dict(bundle.obj.get_mks_values())
        members = []
        for mk in Member.objects.filter(pk__in=mks_values.keys(), current_party__isnull=False).select_related(
            "current_party"
        ):
            # TODO: this sucks, performance wise
            current_party = mk.current_party
            mk_data = mks_values[mk.id]
            members.append(
                dict(
                    id=mk.id,
                    name=mk.name,
                    score=map(itemgetter("score"), mk_data) if type(mk_data) is not dict else mk_data["score"],
                    rank=map(itemgetter("rank"), mk_data) if type(mk_data) is not dict else mk_data["rank"],
                    volume=map(itemgetter("volume"), mk_data) if type(mk_data) is not dict else mk_data["volume"],
                    numvotes=map(itemgetter("numvotes"), mk_data) if type(mk_data) is not dict else mk_data["numvotes"],
                    absolute_url=mk.get_absolute_url(),
                    party=current_party.name,
                    party_url=current_party.get_absolute_url(),
                    party_id=current_party.pk,
                )
            )

        return members
def accounts(request):
    """
    Provides the ``authentication`` dictionary context variable containing
    details about the current authentication method used by the currently
    logged in user.

    Details about the ``authentication`` dictionary:

    If the user is logged in, this context variable is dictionary with the
    following keys:

    * ``method`` - Authentication method used to log in. Set to '``twitter``' for
      Twitter, '``facebook``' for Facebook or '``django.contrib.auth``' if user logs in via
      Django's default authentication mechanism.

    * ``name`` - Display name of the currently logged in user. Set to '``@twitterid``'
      for Twitter, '``first_name``' for Facebook, or '``request.user.username``' for
      Django.contrib.auth.

    If the user is not logged in, this context variable is ``None``. 

    """

    authentication = request.session.get("authentication")
    if authentication is None and request.user.is_authenticated():
        authentication = dict(method="django.contrib.auth", name=request.user.username)

    return dict(authentication=authentication)
Example #10
0
    def test_sysmeta_replaced_by_PUT(self):
        path = "/v1/a/c/o"

        env = {"REQUEST_METHOD": "PUT"}
        hdrs = dict(self.original_sysmeta_headers_1)
        hdrs.update(self.original_sysmeta_headers_2)
        hdrs.update(self.original_meta_headers_1)
        hdrs.update(self.original_meta_headers_2)
        req = Request.blank(path, environ=env, headers=hdrs, body="x")
        resp = req.get_response(self.app)
        self._assertStatus(resp, 201)

        env = {"REQUEST_METHOD": "PUT"}
        hdrs = dict(self.changed_sysmeta_headers)
        hdrs.update(self.new_sysmeta_headers)
        hdrs.update(self.changed_meta_headers)
        hdrs.update(self.new_meta_headers)
        hdrs.update(self.bad_headers)
        req = Request.blank(path, environ=env, headers=hdrs, body="x")
        resp = req.get_response(self.app)
        self._assertStatus(resp, 201)

        req = Request.blank(path, environ={})
        resp = req.get_response(self.app)
        self._assertStatus(resp, 200)
        self._assertInHeaders(resp, self.changed_sysmeta_headers)
        self._assertInHeaders(resp, self.new_sysmeta_headers)
        self._assertNotInHeaders(resp, self.original_sysmeta_headers_2)
        self._assertInHeaders(resp, self.changed_meta_headers)
        self._assertInHeaders(resp, self.new_meta_headers)
        self._assertNotInHeaders(resp, self.original_meta_headers_2)
Example #11
0
    def __init__(self, imageLink, position=(0, 0), size=(100, 100), id=None):
        """
        @type  imageLink: str
        @param imageLink: URI of image associated with the element.
        
        @type  position: (float, float)
        @param position: A position of a left upper corner of an image underlay.
                         See L{barSlideBackgorundElement.position} property for
                         details.
        
        @type  size: (float, float)
        @param size: Size of the given image underlay in SVG coordinates. See
                     L{barSlideBackgorundElement.size} property description for
                     details.
        
        @type  id: str
        @param id: Identifier of an instance. If not provided, it is assigned
                   automatically
        
        """
        self._attributes = dict(CONF_DEFAULT_BACKGROUND_ATTRIBUTES)
        self._attributesNS = dict(CONF_DEFAULT_BACKGROUND_ATTRIBUTES_NS)

        if id == None:
            id = str(uuid.uuid4())

        self.id = id
        self.position = position
        self.imageLink = imageLink
        self.position = position
        self.size = size
        self.opacity = 1
Example #12
0
    def __init__(self, id=None, elements=None):
        """
        C{barSlideBackgroundList} constructor. Use this constructor to initialize
        empty/blank C{barSlideBackgroundList} object. If you parsing a slide and you
        want to recreate C{barSlideBackgroundList} from CAF slide's image layer, use 
        L{barSlideBackgroundList.fromXML} method.
        
        @type  id: str
        @param id: Identifier you want to assign to the object. If no ID is
                   provided, it is generated automatically.
        
        @type  elements: [L{barSlideBackgorundElement},...]
        @param elements: Iterable of background images to be used as a content of
                         the object
        """
        self._attributes = dict(CONF_DEFAULT_BACKGROUND_LIST)
        self._attributesNS = dict(CONF_DEFAULT_BACKGROUND_LIST_NS)

        # Initialize empty elements list. This list will hold all image elements
        self._elements = []
        if id == None:
            id = str(uuid.uuid4())
        self.id = str(id)

        # Add elements to the list. Extend the list if another list
        # is provided or just append the given element.
        if getattr(elements, "__iter__", False):
            self.extend(elements)
        elif elements != None:
            self.append(elements)
Example #13
0
 def update(
     self,
     card_id_or_shortlink,
     name=None,
     desc=None,
     closed=None,
     idAttachmentCover=None,
     idList=None,
     pos=None,
     due=None,
     subscribed=None,
 ):
     resp = requests.put(
         "https://trello.com/1/cards/%s" % (card_id_or_shortlink),
         params=dict(key=self._apikey, token=self._token),
         data=dict(
             name=name,
             desc=desc,
             closed=closed,
             idAttachmentCover=idAttachmentCover,
             idList=idList,
             pos=pos,
             due=due,
             subscribed=subscribed,
         ),
     )
     resp.raise_for_status()
     return resp.json()
Example #14
0
    def test_delete(self):

        resp = yield from aiohttp.post(
            self.full_url(self.app.reverse("fruit_index")), data=json.dumps(dict(name="grape", colors=["purple"]))
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(self.full_url(self.app.reverse("fruit_item", id="grape")))

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()

        self.assertEqual(jr["body"], dict(colors=["purple"]))
        resp.close()

        resp = yield from aiohttp.delete(self.full_url(self.app.reverse("fruit_item", id="grape")))

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(self.full_url(self.app.reverse("fruit_item", id="grape")))

        self.assertEqual(resp.status, 404)
        resp.close()
Example #15
0
    def test_update(self):

        resp = yield from aiohttp.post(
            self.full_url(self.app.reverse("fruit_index")), data=json.dumps(dict(name="pear", colors=["green"]))
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(self.full_url(self.app.reverse("fruit_item", id="pear")))

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()
        self.assertEqual(jr["body"], dict(colors=["green"]))
        resp.close()

        resp = yield from aiohttp.put(
            self.full_url(self.app.reverse("fruit_item", id="pear")), data=json.dumps(dict(colors=["green", "yellow"]))
        )

        self.assertEqual(resp.status, 200)
        resp.close()

        resp = yield from aiohttp.get(self.full_url(self.app.reverse("fruit_item", id="pear")))

        self.assertEqual(resp.status, 200)
        jr = yield from resp.json()
        self.assertEqual(jr["body"], dict(colors=["green", "yellow"]))
        resp.close()
Example #16
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            zk_host=dict(required=True, type="str"),
            zk_port=dict(required=True, type="str"),
            path=dict(required=True, type="str"),
            value=dict(required=False, default=None, type="str"),
        )
    )

    try:
        zk_host = module.params.pop("zk_host")
        zk_port = module.params.pop("zk_port")
        path = module.params.pop("path")
        value = module.params.pop("value")

        changed = False
        with zk_connection(zk_host, zk_port) as zk:
            try:
                zk.get(path)
            except kazoo.exceptions.NoNodeError:
                if value is None:
                    zk.create(path, makepath=True)
                else:
                    zk.create(path, value=value.encode(), makepath=True)
                changed = True

        module.exit_json(changed=changed)
    except Exception as e:
        module.exit_json(failed=True, changed=True, msg=e)
Example #17
0
    def test_volume_create_with_type(self):
        vol_type = CONF.default_volume_type
        db.volume_type_create(context.get_admin_context(), dict(name=vol_type, extra_specs={}))
        db_vol_type = db.volume_type_get_by_name(context.get_admin_context(), vol_type)

        vol = {
            "size": 100,
            "display_name": "Volume Test Name",
            "display_description": "Volume Test Desc",
            "availability_zone": "zone1:host1",
            "volume_type": "FakeTypeName",
        }
        body = {"volume": vol}
        req = fakes.HTTPRequest.blank("/v1/volumes")
        # Raise 404 when type name isn't valid
        self.assertRaises(webob.exc.HTTPNotFound, self.controller.create, req, body)
        # Use correct volume type name
        vol.update(dict(volume_type=CONF.default_volume_type))
        body.update(dict(volume=vol))
        res_dict = self.controller.create(req, body)
        volume_id = res_dict["volume"]["id"]
        self.assertEqual(len(res_dict), 1)
        self.assertEqual(res_dict["volume"]["volume_type"], db_vol_type["name"])

        # Use correct volume type id
        vol.update(dict(volume_type=db_vol_type["id"]))
        body.update(dict(volume=vol))
        res_dict = self.controller.create(req, body)
        volume_id = res_dict["volume"]["id"]
        self.assertEqual(len(res_dict), 1)
        self.assertEqual(res_dict["volume"]["volume_type"], db_vol_type["name"])
Example #18
0
    def test_snapshot_index_detail_serializer(self):
        serializer = snapshots.SnapshotsTemplate()
        raw_snapshots = [
            dict(
                id="snap1_id",
                status="snap1_status",
                size=1024,
                createdAt=datetime.datetime.now(),
                displayName="snap1_name",
                displayDescription="snap1_desc",
                volumeId="vol1_id",
            ),
            dict(
                id="snap2_id",
                status="snap2_status",
                size=1024,
                createdAt=datetime.datetime.now(),
                displayName="snap2_name",
                displayDescription="snap2_desc",
                volumeId="vol2_id",
            ),
        ]
        text = serializer.serialize(dict(snapshots=raw_snapshots))

        print text
        tree = etree.fromstring(text)

        self.assertEqual("snapshots", tree.tag)
        self.assertEqual(len(raw_snapshots), len(tree))
        for idx, child in enumerate(tree):
            self._verify_snapshot(raw_snapshots[idx], child)
Example #19
0
    def test(self):
        arr = cv.LoadImage("../samples/c/lena.jpg", 0)
        original = cv.CloneImage(arr)
        size = cv.GetSize(arr)
        eig_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
        temp_image = cv.CreateImage(size, cv.IPL_DEPTH_32F, 1)
        threshes = [x / 100.0 for x in range(1, 10)]

        results = dict(
            [(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris=1)) for t in threshes]
        )

        # Check that GoodFeaturesToTrack has not modified input image
        self.assert_(arr.tostring() == original.tostring())

        # Check for repeatability
        for i in range(10):
            results2 = dict(
                [(t, cv.GoodFeaturesToTrack(arr, eig_image, temp_image, 20000, t, 2, use_harris=1)) for t in threshes]
            )
            self.assert_(results == results2)

        for t0, t1 in zip(threshes, threshes[1:]):
            r0 = results[t0]
            r1 = results[t1]

            # Increasing thresh should make result list shorter
            self.assert_(len(r0) > len(r1))

            # Increasing thresh should monly truncate result list
            self.assert_(r0[: len(r1)] == r1)
Example #20
0
    def message_update(self, cr, uid, ids, msg, vals={}, default_act="pending", context=None):
        if isinstance(ids, (str, int, long)):
            ids = [ids]

        res_id = super(crm_claim, self).message_update(cr, uid, ids, msg, context=context)

        if msg.get("priority") in dict(crm.AVAILABLE_PRIORITIES):
            vals["priority"] = msg.get("priority")

        maps = {"cost": "planned_cost", "revenue": "planned_revenue", "probability": "probability"}
        vls = {}
        for line in msg["body_text"].split("\n"):
            line = line.strip()
            res = tools.misc.command_re.match(line)
            if res and maps.get(res.group(1).lower()):
                key = maps.get(res.group(1).lower())
                vls[key] = res.group(2).lower()
        vals.update(vls)

        # Unfortunately the API is based on lists
        # but we want to update the state based on the
        # previous state, so we have to loop:
        for case in self.browse(cr, uid, ids, context=context):
            values = dict(vals)
            if case.state in CRM_CLAIM_PENDING_STATES:
                values.update(state=crm.AVAILABLE_STATES[1][0])  # re-open
            res = self.write(cr, uid, [case.id], values, context=context)
        return res
Example #21
0
File: tests.py Project: rvs/hue
def test_recursive_walk():
    def f(_):
        f.leafs += 1

    f.leafs = 0

    # Test that we apply the function the right number of times
    recursive_walk(f, [0, 1, 2])
    assert_equal(3, f.leafs)
    f.leafs = 0

    recursive_walk(f, 1)
    assert_equal(1, f.leafs)
    f.leafs = 0

    D = dict(a=2, b=3, c=dict(d=4, e=5))
    Dorig = copy.deepcopy(D)
    recursive_walk(f, D)
    assert_equal(4, f.leafs)
    assert_equal(Dorig, D, "Object unexpectedly modified.")

    # Test application and replacement
    def square(x):
        return x * x

    assert_equal(dict(a=4, b=9, c=dict(d=16, e=25)), recursive_walk(square, D))
Example #22
0
    def _get_cpu_info(self):
        """Get the CPU information.
        :returns: A dictionary containing the main properties
        of the central processor in the hypervisor.
        """
        cpu_info = dict()
        processor = self._conn_cimv2.query("SELECT * FROM Win32_Processor WHERE ProcessorType = 3")

        cpu_info["arch"] = constants.WMI_WIN32_PROCESSOR_ARCHITECTURE.get(processor[0].Architecture, "Unknown")
        cpu_info["model"] = processor[0].Name
        cpu_info["vendor"] = processor[0].Manufacturer

        topology = dict()
        topology["sockets"] = len(processor)
        topology["cores"] = processor[0].NumberOfCores
        topology["threads"] = processor[0].NumberOfLogicalProcessors / processor[0].NumberOfCores
        cpu_info["topology"] = topology

        features = list()
        for fkey, fname in constants.PROCESSOR_FEATURE.items():
            if ctypes.windll.kernel32.IsProcessorFeaturePresent(fkey):
                features.append(fname)
        cpu_info["features"] = features

        return jsonutils.dumps(cpu_info)
Example #23
0
def user():
    if MULTI_USER_MODE:
        if not db(db.auth_user).count():
            auth.settings.registration_requires_approval = False
        return dict(form=auth())
    else:
        return dict(form=T("Disabled"))
Example #24
0
 def createProtocolParametersList(self, protocol):
     json_list = []
     parameters = protocol["Study Protocol Parameters Name"]
     parametersURIs = protocol["Study Protocol Parameters Name Term Accession Number"]
     index = 0
     if len(parameters) > 0:
         for parameter in parameters.split(";"):
             json_item = dict(
                 [
                     ("name", dict([("_value", parameter)])),
                     (
                         "description",
                         (
                             dict(
                                 [
                                     (
                                         "_value",
                                         parametersURIs[index] if (len(parametersURIs) == len(parameters)) else "",
                                     )
                                 ]
                             )
                         ),
                     ),
                 ]
             )
             index = index + 1
             json_list.append(json_item)
     return json_list
Example #25
0
def sow_dev_load(pr_id, header_id):
    u = user_check_project_access(pr_id)
    check_project_stage(pr_id, 4)
    header = Header.get(Header.id == header_id)
    res = []
    for i in Ticket.select().where(Ticket.hid == header_id).order_by(Ticket.add_time.asc()):
        comments = []
        for j in Comment.select().where(Comment.tid == i.id).order_by(Comment.add_time.asc()):
            cur = dict(
                id=j.id,
                nick=str(j.nick),
                tid=j.tid,
                msg=md2html_line(fix_string(str(j.msg))),
                add_time=str(j.add_time),
                edit_time=str(j.edit_time),
                pid=str(j.pid),
            )
            comments.append(cur)
        cur = dict(
            id=i.id,
            name=md2html_line(fix_string(str(i.name))),
            content=md2html_line(fix_string(str(i.content))),
            add_time=i.add_time,
            hid=i.hid,
            category=i.category,
            closed=str(i.closed).lower(),
            close_time=i.close_time,
            nickname=i.nickname,
            pid=i.pid,
            comments=comments,
        )
        res.append(cur)
    my_priv = check_user_rights(u.id, pr_id, "w")
    data = {"ro": str(not my_priv), "html": header.html, "tickets": res}
    return str(data).replace("'", '"')
Example #26
0
def get_tags(stream_info):
    "gets all tags and their values from stream info"
    taglist = stream_info.get_tags()
    if not taglist:
        return {}
    tags = []
    taglist.foreach(lambda list, tag: tags.append((tag, list.get_value_index(tag, 0))))
    tags = dict(tags)

    # date/datetime should be converted from GDate/GDateTime to strings
    if "date" in tags:
        date = tags["date"]
        tags["date"] = "%s-%s-%s" % (date.year, date.month, date.day)

    if "datetime" in tags:
        # TODO: handle timezone info; gst.get_time_zone_offset +
        # python's tzinfo should help
        dt = tags["datetime"]
        tags["datetime"] = datetime.datetime(
            dt.get_year(),
            dt.get_month(),
            dt.get_day(),
            dt.get_hour(),
            dt.get_minute(),
            dt.get_second(),
            dt.get_microsecond(),
        ).isoformat()
    for k, v in tags.items():
        # types below are accepted by json; others must not present
        if not isinstance(v, (dict, list, six.string_types, int, float, bool, type(None))):
            del tags[k]
    return dict(tags)
Example #27
0
    def create_user(self):
        schema = AdminUserSchema()
        schema = schema.bind(request=self.request)
        form = HorusForm(schema)

        if self.request.method == "GET":
            if isinstance(self.request.context, RootFactory):
                return dict(form=form)
            else:
                return dict(form=form, appstruct=self.request.context.__json__())
        else:
            try:
                controls = self.request.POST.items()
                captured = form.validate(controls)
            except deform.ValidationFailure as e:
                return dict(form=e, errors=e.error.children)

            if isinstance(self.request.context, RootFactory):
                user = self.User(username=captured["username"], email=captured["email"])
            else:
                user = self.request.context

            if captured["password"]:
                user.password = captured["password"]

            self.db.add(user)

            FlashMessage(self.request, self.Str.admin_create_user_done, "success")

            return HTTPFound(location=self.request.route_url("admin_users_index"))
def list_available(unbreakablecoind):
    address_summary = dict()

    address_to_account = dict()
    for info in unbreakablecoind.listreceivedbyaddress(0):
        address_to_account[info["address"]] = info["account"]

    unspent = unbreakablecoind.listunspent(0)
    for output in unspent:
        # listunspent doesn't give addresses, so:
        rawtx = unbreakablecoind.getrawtransaction(output['txid'], 1)
        vout = rawtx["vout"][output['vout']]
        pk = vout["scriptPubKey"]

        # This code only deals with ordinary pay-to-bitcoin-address
        # or pay-to-script-hash outputs right now; anything exotic is ignored.
        if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
            continue
        
        address = pk["addresses"][0]
        if address in address_summary:
            address_summary[address]["total"] += vout["value"]
            address_summary[address]["outputs"].append(output)
        else:
            address_summary[address] = {
                "total" : vout["value"],
                "outputs" : [output],
                "account" : address_to_account.get(address, "")
                }

    return address_summary
Example #29
0
def get_entrypoints(filename):
    if not os.path.exists(filename):
        return {}, {}

    # This is done because you can pass a string to entry_points wrappers which
    # means that they may or may not be valid INI files. The attempt here is to
    # strip leading and trailing whitespace in order to make them valid INI
    # files.
    with open(filename) as fp:
        data = StringIO()
        for line in fp:
            data.write(line.strip())
            data.write("\n")
        data.seek(0)

    cp = configparser.RawConfigParser()
    cp.optionxform = lambda option: option
    cp.readfp(data)

    console = {}
    gui = {}
    if cp.has_section("console_scripts"):
        console = dict(cp.items("console_scripts"))
    if cp.has_section("gui_scripts"):
        gui = dict(cp.items("gui_scripts"))
    return console, gui
Example #30
0
 def _print_iterations_data(result):
     raw_data = result["data"]["raw"]
     headers = ["iteration", "full duration"]
     float_cols = ["full duration"]
     atomic_actions = []
     for row in raw_data:
         # find first non-error result to get atomic actions names
         if not row["error"] and "atomic_actions" in row:
             atomic_actions = row["atomic_actions"].keys()
     for row in raw_data:
         if row["atomic_actions"]:
             for (c, a) in enumerate(atomic_actions, 1):
                 action = "%(no)i. %(action)s" % {"no": c, "action": a}
                 headers.append(action)
                 float_cols.append(action)
             break
     table_rows = []
     formatters = dict(zip(float_cols, [cliutils.pretty_float_formatter(col, 3) for col in float_cols]))
     for (c, r) in enumerate(raw_data, 1):
         dlist = [c]
         dlist.append(r["duration"])
         if r["atomic_actions"]:
             for action in atomic_actions:
                 dlist.append(r["atomic_actions"].get(action) or 0)
         table_rows.append(rutils.Struct(**dict(zip(headers, dlist))))
     cliutils.print_list(table_rows, fields=headers, formatters=formatters)
     print()