当前位置: 首页>>代码示例>>Python>>正文


Python types.namespace函数代码示例

本文整理汇总了Python中types.namespace函数的典型用法代码示例。如果您正苦于以下问题:Python namespace函数的具体用法?Python namespace怎么用?Python namespace使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了namespace函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run

    def run(self):
        imgmeta = []
        filescanner = scan(self.startdir)
        patterns = ["*.{}".format(fmt.lower()) for fmt in self.formats]

        def fnmatch_any(fname, patterns):
            return any(fnmatch.fnmatch(fname.lower(), pattern)
                       for pattern in patterns)

        batch = []

        for path in filescanner:
            if fnmatch_any(path, patterns):
                imeta = image_meta_data(path)
                imgmeta.append(imeta)
                batch.append(imgmeta)

            if self.cancelled:
                return
                # raise UserInterruptError

            if len(batch) == 10 and self.report_progress is not None:
                self.report_progress(
                    namespace(count=len(imgmeta),
                              lastpath=imgmeta[-1].path,
                              batch=batch))
                batch = []

        if batch and self.report_progress is not None:
            self.report_progress(
                    namespace(count=len(imgmeta),
                              lastpath=imgmeta[-1].path,
                              batch=batch))

        return imgmeta
开发者ID:ajdapretnar,项目名称:orange3-imageanalytics,代码行数:35,代码来源:owimageimport.py

示例2: image_meta

    def image_meta(self, filescanner, patterns=('*', )):
        def fnmatch_any(fname, patterns):
            return any(fnmatch.fnmatch(fname.lower() if self.case_insensitive else fname, pattern)
                       for pattern in patterns)

        imgmeta = []
        batch = []

        for path in filescanner:
            if fnmatch_any(path, patterns):
                imeta = image_meta_data(path)
                imgmeta.append(imeta)
                batch.append(imgmeta)

            if self.cancelled:
                return
                # raise UserInterruptError

            if len(batch) == 10 and self.report_progress is not None:
                self.report_progress(
                    namespace(count=len(imgmeta),
                              lastpath=imgmeta[-1].path,
                              batch=batch))
                batch = []

        if batch and self.report_progress is not None:
            self.report_progress(
                    namespace(count=len(imgmeta),
                              lastpath=imgmeta[-1].path,
                              batch=batch))

        return imgmeta
开发者ID:biolab,项目名称:orange3-imageanalytics,代码行数:32,代码来源:import_images.py

示例3: run

    def run(self):
        text_data = []
        errors = []
        patterns = ["*.{}".format(fmt.lower()) for fmt in self.formats]
        paths = self.scan(self.startdir, include_patterns=patterns)
        n_paths = len(paths)
        batch = []

        for path in paths:
            if len(batch) == 1 and self._report_progress is not None:
                self._report_progress(
                    namespace(progress=len(text_data) / n_paths,
                              lastpath=path,
                              batch=batch))
                batch = []

            reader = Reader.get_reader(path)
            text, error = reader.read()
            if text is not None:
                text_data.append(text)
                batch.append(text_data)
            else:
                errors.append(error)

            if self.cancelled:
                return

        self._text_data = text_data
        return self._create_corpus(), errors
开发者ID:s-alexey,项目名称:orange3-text,代码行数:29,代码来源:import_documents.py

示例4: info

        def info(file_path):
            if file_path in allinforemote:
                info = allinforemote[file_path]
            else:
                info = allinfolocal[file_path]
            islocal = file_path in allinfolocal
            isremote = file_path in allinforemote
            outdated = islocal and isremote and (
                allinforemote[file_path].get('version', '') !=
                allinfolocal[file_path].get('version', ''))
            islocal &= not outdated
            prefix = os.path.join('', *file_path[:-1])
            filename = file_path[-1]

            return namespace(
                prefix=prefix, filename=filename,
                title=info.get("title", filename),
                datetime=info.get("datetime", None),
                description=info.get("description", None),
                references=info.get("references", []),
                seealso=info.get("seealso", []),
                source=info.get("source", None),
                year=info.get("year", None),
                instances=info.get("instances", None),
                variables=info.get("variables", None),
                target=info.get("target", None),
                missing=info.get("missing", None),
                tags=info.get("tags", []),
                size=info.get("size", None),
                islocal=islocal,
                outdated=outdated
            )
开发者ID:nikicc,项目名称:orange3,代码行数:32,代码来源:owdatasets.py

示例5: _new_plotdata

 def _new_plotdata(self):
     self.plotdata = namespace(
         valid_mask=None,
         embedding_coords=None,
         axisitems=[],
         axes=[],
         variables=[],
         data=None,
         hidecircle=None
     )
开发者ID:astaric,项目名称:orange3,代码行数:10,代码来源:owlinearprojection.py

示例6: _new_plotdata

 def _new_plotdata(self):
     self.plotdata = namespace(
         valid_mask=None,
         embedding_coords=None,
         points=None,
         arcarrows=[],
         point_labels=[],
         rand=None,
         data=None,
     )
开发者ID:astaric,项目名称:orange3,代码行数:10,代码来源:owradviz.py

示例7: _new_plotdata

 def _new_plotdata(self):
     self.plotdata = namespace(
         validmask=None,
         embedding_coords=None,
         anchors=[],
         anchoritem=[],
         X=None,
         Y=None,
         indicators=[],
         hidecircle=None,
         data=None,
         items=[],
         topattrs=None,
         rand=None,
         selection=None,  # np.array
     )
开发者ID:randxie,项目名称:orange3,代码行数:16,代码来源:owfreeviz.py

示例8: setScores

    def setScores(self, scores, labels, values, colors, rownames=None):
        """
        Set the silhouette scores/labels to for display.

        Arguments
        ---------
        scores : (N,) ndarray
            The silhouette scores.
        labels : (N,) ndarray
            A ndarray (dtype=int) of label/clusters indices.
        values : list of str
            A list of label/cluster names.
        colors : (N, 3) ndarray
            A ndarray of RGB values.
        rownames : list of str, optional
            A list (len == N) of row names.
        """
        scores = np.asarray(scores, dtype=float)
        labels = np.asarray(labels, dtype=int)
        if rownames is not None:
            rownames = np.asarray(rownames, dtype=object)

        if not scores.ndim == labels.ndim == 1:
            raise ValueError("scores and labels must be 1 dimensional")
        if scores.shape != labels.shape:
            raise ValueError("scores and labels must have the same shape")
        if rownames is not None and rownames.shape != scores.shape:
            raise ValueError("rownames must have the same size as scores")

        Ck = np.unique(labels)
        if not Ck[0] >= 0 and Ck[-1] < len(values):
            raise ValueError(
                "All indices in `labels` must be in `range(len(values))`")
        cluster_indices = [np.flatnonzero(labels == i)
                           for i in range(len(values))]
        cluster_indices = [indices[np.argsort(scores[indices])[::-1]]
                           for indices in cluster_indices]
        groups = [
            namespace(scores=scores[indices], indices=indices, label=label,
                      rownames=(rownames[indices] if rownames is not None
                                else None),
                      color=color)
            for indices, label, color in zip(cluster_indices, values, colors)
        ]
        self.clear()
        self.__groups = groups
        self.__setup()
开发者ID:PrimozGodec,项目名称:orange3,代码行数:47,代码来源:owsilhouetteplot.py

示例9: mousePressEvent

 def mousePressEvent(self, event):
     # Reimplemented
     if event.button() == Qt.LeftButton:
         if event.modifiers() & Qt.ControlModifier:
             saction = SelectAction.Toogle
         elif event.modifiers() & Qt.AltModifier:
             saction = SelectAction.Deselect
         elif event.modifiers() & Qt.ShiftModifier:
             saction = SelectAction.Select
         else:
             saction = SelectAction.Clear | SelectAction.Select
         self.__selstate = namespace(
             modifiers=event.modifiers(), selection=self.__selection, action=saction, rect=None
         )
         if saction & SelectAction.Clear:
             self.__selstate.selection = numpy.array([], dtype=int)
             self.setSelection(self.__selstate.selection)
         event.accept()
开发者ID:VesnaT,项目名称:orange3-prototypes,代码行数:18,代码来源:owsilhouetteplot.py

示例10: mock_service

def mock_service():
    s = namespace(
        list=namespace(
            organism=namespace(get=lambda: list_organism),
            pathway=lambda org: {
                "hsa": namespace(get=lambda: list_pathway_hsa)
            }[org],
        ),
        info=lambda db:
            {"pathway": namespace(get=lambda: info_pathway)}[db],
        get=lambda key: {
            "genome:T01001": namespace(get=lambda: genome_T01001)
        }[key],
    )
    return s
开发者ID:JakaKokosar,项目名称:orange-bio,代码行数:15,代码来源:test_api.py

示例11: _setup_plot

    def _setup_plot(self):
        """Setup the plot with new curve data."""
        assert self.data is not None

        data, domain = self.data, self.data.domain
        if is_discrete(domain.class_var):
            class_col_data, _ = data.get_column_view(domain.class_var)

            group_indices = [np.flatnonzero(class_col_data == i)
                             for i in range(len(domain.class_var.values))]
        else:
            group_indices = [np.arange(len(data))]

        X = np.arange(1, len(domain.attributes)+1)
        groups = []

        for i, indices in enumerate(group_indices):
            if self.classes:
                color = self.class_colors[i]
            else:
                color = QColor(Qt.darkGray)
            group_data = data[indices, :]
            plot_x, plot_y, connect = disconnected_curve_data(group_data.X, x=X)

            color.setAlpha(200)
            lightcolor = QColor(color.lighter(factor=150))
            lightcolor.setAlpha(150)
            pen = QPen(color, 2)
            pen.setCosmetic(True)

            lightpen = QPen(lightcolor, 1)
            lightpen.setCosmetic(True)
            hoverpen = QPen(pen)
            hoverpen.setWidth(2)

            curve = pg.PlotCurveItem(
                x=plot_x, y=plot_y, connect=connect,
                pen=lightpen, symbolSize=2, antialias=True,
            )
            self.graph.addItem(curve)

            hovercurves = []
            for index, profile in zip(indices, group_data.X):
                hcurve = HoverCurve(x=X, y=profile, pen=hoverpen,
                                    antialias=True)
                hcurve.setToolTip('{}'.format(index))
                hcurve._data_index = index
                hovercurves.append(hcurve)
                self.graph.addItem(hcurve)

            mean = np.nanmean(group_data.X, axis=0)

            meancurve = pg.PlotDataItem(
                x=X, y=mean, pen=pen, size=5, symbol="o", pxMode=True,
                symbolSize=5, antialias=True
            )
            hoverpen = QPen(hoverpen)
            hoverpen.setWidth(5)

            hc = HoverCurve(x=X, y=mean, pen=hoverpen, antialias=True)
            hc.setFlag(QGraphicsItem.ItemIsSelectable, False)
            self.graph.addItem(hc)

            self.graph.addItem(meancurve)
            self.legend_items.append(meancurve)
            q1, q2, q3 = np.nanpercentile(group_data.X, [25, 50, 75], axis=0)
            # TODO: implement and use a box plot item
            errorbar = pg.ErrorBarItem(
                x=X, y=mean,
                bottom=np.clip(mean - q1, 0, mean - q1),
                top=np.clip(q3 - mean, 0, q3 - mean),
                beam=0.5
            )
            self.graph.addItem(errorbar)
            groups.append(
                namespace(
                    data=group_data, indices=indices, profiles=curve,
                    hovercurves=hovercurves, mean=meancurve, boxplot=errorbar)
            )

        self.__groups = groups
        self.__update_visibility()
        self.__update_tooltips()
开发者ID:JakaKokosar,项目名称:orange-bio,代码行数:83,代码来源:OWDisplayProfiles.py

示例12: update_scores

    def update_scores(self):
        """Compute the scores and update the histogram.
        """
        self.__cancel_pending()
        self.clear_plot()
        self.scores = None
        self.nulldist = None
        self.error(0)

        grp, split_selection = self.selected_split()

        if not self.data or grp is None:
            return

        _, side, test_type, score_func = self.Scores[self.score_index]

        def compute_scores(X, group_indices):
            arrays = [X[ind] for ind in group_indices]
            return score_func(*arrays, axis=0)

        def permute_indices(group_indices, random_state=None):
            assert all(ind.dtype.kind == "i" for ind in group_indices)
            assert all(ind.ndim == 1 for ind in group_indices)
            if random_state is None:
                random_state = np.random
            joined = np.hstack(group_indices)
            random_state.shuffle(joined)
            split_ind = np.cumsum([len(ind) for ind in group_indices])
            return np.split(joined, split_ind[:-1])

        if isinstance(grp, grouputils.RowGroup):
            axis = 0
        else:
            axis = 1

        if test_type == OWFeatureSelection.TwoSampleTest:
            G1 = grouputils.group_selection_mask(
                self.data, grp, split_selection)
            G2 = ~G1
            indices = [np.flatnonzero(G1), np.flatnonzero(G2)]
        elif test_type == self.VarSampleTest:
            indices = [grouputils.group_selection_mask(self.data, grp, [i])
                       for i in range(len(grp.values))]
            indices = [np.flatnonzero(ind) for ind in indices]
        else:
            assert False

        if not all(np.count_nonzero(ind) > 0 for ind in indices):
            self.error(0, "Target labels most exclude/include at least one "
                          "value.")
            self.scores = None
            self.nulldist = None
            self.update_data_info_label()
            return

        X = self.data.X
        if axis == 1:
            X = X.T

        # TODO: Check that each label has more than one measurement,
        # raise warning otherwise.

        def compute_scores_with_perm(X, indices, nperm=0, rstate=None,
                                     progress_advance=None):
            scores = compute_scores(X, indices, )

            if progress_advance is not None:
                progress_advance()
            null_scores = []
            if nperm > 0:
                if rstate is None:
                    rstate = np.random.RandomState(0)

                for i in range(nperm):
                    p_indices = permute_indices(indices, rstate)
                    assert all(pind.shape == ind.shape
                               for pind, ind in zip(indices, p_indices))
                    pscore = compute_scores(X, p_indices)
                    assert pscore.shape == scores.shape
                    null_scores.append(pscore)
                    if progress_advance is not None:
                        progress_advance()

            return scores, null_scores

        p_advance = concurrent.methodinvoke(
            self, "progressBarAdvance", (float,))
        state = namespace(cancelled=False, advance=p_advance)

        def progress():
            if state.cancelled:
                raise concurrent.CancelledError
            else:
                state.advance(100 / (nperm + 1))

        self.progressBarInit()
        set_scores = concurrent.methodinvoke(
            self, "__set_score_results", (concurrent.Future,))

        nperm = self.permutations_count if self.compute_null else 0
#.........这里部分代码省略.........
开发者ID:tmzl,项目名称:orange-bio,代码行数:101,代码来源:OWFeatureSelection.py

示例13: start

    def start(self):
        """
        Start/execute the image indexing operation
        """
        self.error()

        self.__invalidated = False
        if self.currentPath is None:
            return

        if self.__state == State.Processing:
            assert self.__pendingTask is not None
            log.info("Starting a new task while one is in progress. "
                     "Cancel the existing task (dir:'{}')"
                     .format(self.__pendingTask.startdir))
            self.cancel()

        startdir = self.currentPath

        self.__setRuntimeState(State.Processing)

        report_progress = methodinvoke(
            self, "__onReportProgress", (object,))

        task = ImageScan(startdir, report_progress=report_progress)

        # collect the task state in one convenient place
        self.__pendingTask = taskstate = namespace(
            task=task,
            startdir=startdir,
            future=None,
            watcher=None,
            cancelled=False,
            cancel=None,
        )

        def cancel():
            # Cancel the task and disconnect
            if taskstate.future.cancel():
                pass
            else:
                taskstate.task.cancelled = True
                taskstate.cancelled = True
                try:
                    taskstate.future.result(timeout=3)
                except UserInterruptError:
                    pass
                except TimeoutError:
                    log.info("The task did not stop in in a timely manner")
            taskstate.watcher.finished.disconnect(self.__onRunFinished)

        taskstate.cancel = cancel

        def run_image_scan_task_interupt():
            try:
                return task.run()
            except UserInterruptError:
                # Suppress interrupt errors, so they are not logged
                return

        taskstate.future = self.__executor.submit(run_image_scan_task_interupt)
        taskstate.watcher = FutureWatcher(taskstate.future)
        taskstate.watcher.finished.connect(self.__onRunFinished)
开发者ID:ajdapretnar,项目名称:orange3-imageanalytics,代码行数:63,代码来源:owimageimport.py

示例14: __init__


#.........这里部分代码省略.........
        gui.auto_commit(self.controlArea, self, "auto_commit", "Commit")

        # Main area plot
        self.view = pg.GraphicsView(background="w")
        self.view.setRenderHint(QtGui.QPainter.Antialiasing, True)
        self.view.setFrameStyle(QtGui.QFrame.StyledPanel)
        self.viewbox = pg.ViewBox(enableMouse=True, enableMenu=False)
        self.viewbox.grabGesture(Qt.PinchGesture)
        self.view.setCentralItem(self.viewbox)

        self.mainArea.layout().addWidget(self.view)

        self.selection = PlotSelectionTool(
            self, selectionMode=PlotSelectionTool.Lasso)
        self.selection.setViewBox(self.viewbox)
        self.selection.selectionFinished.connect(self._selection_finish)

        self.zoomtool = PlotZoomTool(self)
        self.pantool = PlotPanTool(self)
        self.pinchtool = PlotPinchZoomTool(self)
        self.pinchtool.setViewBox(self.viewbox)

        self.continuous_palette = colorpalette.ContinuousPaletteGenerator(
            QtGui.QColor(220, 220, 220),
            QtGui.QColor(0, 0, 0),
            False
        )
        self.discrete_palette = colorpalette.ColorPaletteGenerator(13)

        def icon(name):
            path = "icons/Dlg_{}.png".format(name)
            path = pkg_resources.resource_filename(widget.__name__, path)
            return QtGui.QIcon(path)

        actions = namespace(
            zoomtofit=QAction(
                "Zoom to fit", self, icon=icon("zoom_reset"),
                shortcut=QKeySequence(Qt.ControlModifier | Qt.Key_0),
                triggered=lambda:
                    self.viewbox.setRange(QRectF(-1.05, -1.05, 2.1, 2.1))),
            zoomin=QAction(
                "Zoom in", self,
                shortcut=QKeySequence(QKeySequence.ZoomIn),
                triggered=lambda: self.viewbox.scaleBy((1 / 1.25, 1 / 1.25))),
            zoomout=QAction(
                "Zoom out", self,
                shortcut=QKeySequence(QKeySequence.ZoomOut),
                triggered=lambda: self.viewbox.scaleBy((1.25, 1.25))),
            select=QAction(
                "Select", self, checkable=True, icon=icon("arrow"),
                shortcut=QKeySequence(Qt.ControlModifier + Qt.Key_1)),
            zoom=QAction(
                "Zoom", self, checkable=True, icon=icon("zoom"),
                shortcut=QKeySequence(Qt.ControlModifier + Qt.Key_2)),
            pan=QAction(
                "Pan", self, checkable=True, icon=icon("pan_hand"),
                shortcut=QKeySequence(Qt.ControlModifier + Qt.Key_3)),
        )
        self.addActions([actions.zoomtofit, actions.zoomin, actions.zoomout])

        group = QtGui.QActionGroup(self, exclusive=True)
        group.addAction(actions.select)
        group.addAction(actions.zoom)
        group.addAction(actions.pan)

        actions.select.setChecked(True)

        currenttool = self.selection
        self.selection.setViewBox(None)

        def activated(action):
            nonlocal currenttool
            if action is actions.select:
                tool, cursor = self.selection, Qt.ArrowCursor
            elif action is actions.zoom:
                tool, cursor = self.zoomtool, Qt.ArrowCursor
            elif action is actions.pan:
                tool, cursor = self.pantool, Qt.OpenHandCursor
            else:
                assert False
            currenttool.setViewBox(None)
            tool.setViewBox(self.viewbox)
            self.viewbox.setCursor(QtGui.QCursor(cursor))
            currenttool = tool

        group.triggered[QAction].connect(activated)

        def button(action):
            b = QtGui.QToolButton()
            b.setDefaultAction(action)
            return b

        toollayout.addWidget(button(actions.select))
        toollayout.addWidget(button(actions.zoom))
        toollayout.addWidget(button(actions.pan))

        toollayout.addSpacing(4)
        toollayout.addWidget(button(actions.zoomtofit))
        toollayout.addStretch()
        toolbox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)
开发者ID:fdion,项目名称:orange3,代码行数:101,代码来源:owlinearprojection.py

示例15: commit

    def commit(self):
        if self._task is not None:
            self.cancel()

        if self._image_embedder is None:
            self._set_server_info(connected=False)
            return

        if not self._image_attributes or self._input_data is None:
            self.Outputs.embeddings.send(None)
            self.Outputs.skipped_images.send(None)
            return

        self._set_server_info(connected=True)
        self.cancel_button.setDisabled(False)
        self.cb_image_attr.setDisabled(True)
        self.cb_embedder.setDisabled(True)

        file_paths_attr = self._image_attributes[self.cb_image_attr_current_id]
        file_paths = self._input_data[:, file_paths_attr].metas.flatten()
        origin = file_paths_attr.attributes.get("origin", "")
        if urlparse(origin).scheme in ("http", "https", "ftp", "data") and \
                origin[-1] != "/":
            origin += "/"

        assert file_paths_attr.is_string
        assert file_paths.dtype == np.dtype('O')

        file_paths_mask = file_paths == file_paths_attr.Unknown
        file_paths_valid = file_paths[~file_paths_mask]
        for i, a in enumerate(file_paths_valid):
            urlparts = urlparse(a)
            if urlparts.scheme not in ("http", "https", "ftp", "data"):
                if urlparse(origin).scheme in ("http", "https", "ftp", "data"):
                    file_paths_valid[i] = urljoin(origin, a)
                else:
                    file_paths_valid[i] = os.path.join(origin, a)

        ticks = iter(np.linspace(0.0, 100.0, file_paths_valid.size))
        set_progress = qconcurrent.methodinvoke(
            self, "__progress_set", (float,))

        def advance(success=True):
            if success:
                set_progress(next(ticks))

        def cancel():
            task.future.cancel()
            task.cancelled = True
            task.embedder.set_canceled(True)

        embedder = self._image_embedder

        def run_embedding(paths):
            return embedder(
                file_paths=paths, image_processed_callback=advance)

        self.auto_commit_widget.setDisabled(True)
        self.progressBarInit(processEvents=None)
        self.progressBarSet(0.0, processEvents=None)
        self.setBlocking(True)

        f = self._executor.submit(run_embedding, file_paths_valid)
        f.add_done_callback(
            qconcurrent.methodinvoke(self, "__set_results", (object,)))

        task = self._task = namespace(
            file_paths_mask=file_paths_mask,
            file_paths_valid=file_paths_valid,
            file_paths=file_paths,
            embedder=embedder,
            cancelled=False,
            cancel=cancel,
            future=f,
        )
        self._log.debug("Starting embedding task for %i images",
                        file_paths.size)
        return
开发者ID:biolab,项目名称:orange3-imageanalytics,代码行数:78,代码来源:owimageembedding.py


注:本文中的types.namespace函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。