Create a tabular layer with the profiling.

    :param profiling: A dict containing benchmarking data.
    :type profiling: safe.messaging.message.Message

    :return: A tabular layer.
    :rtype: QgsVectorLayer
192659
def create_profile_layer(profiling):
    
    fields = [
        create_field_from_definition(profiling_function_field),
        create_field_from_definition(profiling_time_field)
    ]
    if setting(key='memory_profile', expected_type=bool):
        fields.append(create_field_from_definition(profiling_memory_field))
    tabular = create_memory_layer(
        'profiling',
        QgsWkbTypes.NullGeometry,
        fields=fields)

    # Generate profiling keywords
    tabular.keywords['layer_purpose'] = layer_purpose_profiling['key']
    tabular.keywords['title'] = layer_purpose_profiling['name']
    if qgis_version() >= 21800:
        tabular.setName(tabular.keywords['title'])
    else:
        tabular.setLayerName(tabular.keywords['title'])
    tabular.keywords['inasafe_fields'] = {
        profiling_function_field['key']:
            profiling_function_field['field_name'],
        profiling_time_field['key']:
            profiling_time_field['field_name'],
    }
    if setting(key='memory_profile', expected_type=bool):
        tabular.keywords['inasafe_fields'][
            profiling_memory_field['key']] = profiling_memory_field[
            'field_name']
    tabular.keywords[inasafe_keyword_version_key] = (
        inasafe_keyword_version)

    table = profiling.to_text().splitlines()[3:]
    tabular.startEditing()
    for line in table:
        feature = QgsFeature()
        items = line.split(', ')
        time = items[1].replace('-', '')
        if setting(key='memory_profile', expected_type=bool):
            memory = items[2].replace('-', '')
            feature.setAttributes([items[0], time, memory])
        else:
            feature.setAttributes([items[0], time])
        tabular.addFeature(feature)

    tabular.commitChanges()
    return tabular
408951
def profile(message=None, verbose=False):
    
    import functools
    from harrison.registered_timer import RegisteredTimer

    # Adjust the call stack index for RegisteredTimer so the call is Timer use
    # is properly attributed.
    class DecoratorTimer(RegisteredTimer):
        _CALLER_STACK_INDEX = 2

    def wrapper(fn):
        desc = message or fn.__name__

        @functools.wraps(fn)
        def wrapped_fn(*args, **kwargs):
            with DecoratorTimer(desc=desc, verbose=verbose):
                return fn(*args, **kwargs)
        return wrapped_fn

    return wrapper
1207518
def create_tables(name, runSetResults, rows, rowsDiff, outputPath, outputFilePattern, options):
    '''
    
    '''

    # get common folder of sourcefiles
    common_prefix = os.path.commonprefix([r.filename for r in rows]) # maybe with parts of filename
    common_prefix = common_prefix[: common_prefix.rfind('/') + 1] # only foldername
    for row in rows:
        Row.set_relative_path(row, common_prefix, outputPath)

    # compute nice name of each run set for displaying
    firstBenchmarkName = Util.prettylist(runSetResults[0].attributes['benchmarkname'])
    allBenchmarkNamesEqual = all(Util.prettylist(r.attributes['benchmarkname']) == firstBenchmarkName for r in runSetResults)
    for r in runSetResults:
        if not r.attributes['name']:
            r.attributes['niceName'] = r.attributes['benchmarkname']
        elif allBenchmarkNamesEqual:
            r.attributes['niceName'] = r.attributes['name']
        else:
            r.attributes['niceName'] = [Util.prettylist(r.attributes['benchmarkname']) + '.' + Util.prettylist(r.attributes['name'])]

    template_values = lambda: None # dummy object as dict replacement for simpler syntax
    template_values.head = get_table_head(runSetResults, common_prefix)
    template_values.run_sets = [runSetResult.attributes for runSetResult in runSetResults]
    template_values.columns = [[column for column in runSet.columns] for runSet in runSetResults]
    template_values.columnTitles =\
        [[column.format_title() for column in runSet.columns] for runSet in runSetResults]

    template_values.relevant_id_columns = select_relevant_id_columns(rows)
    template_values.count_id_columns = template_values.relevant_id_columns.count(True)

    template_values.lib_url = options.lib_url
    template_values.base_dir = outputPath
    template_values.href_base = os.path.dirname(options.xmltablefile) if options.xmltablefile else None
    template_values.version = __version__

    futures = []

    def write_table(table_type, title, rows, use_local_summary):
        # calculate statistics if necessary
        if not options.format == ['csv']:
            local_summary = get_summary(runSetResults) if use_local_summary else None
            stats, stats_columns = get_stats(rows, local_summary, options.correct_only)
        else:
            stats = stats_columns = None

        for template_format in (options.format or TEMPLATE_FORMATS):
            if outputFilePattern == '-':
                outfile = None
                logging.info('Writing %s to stdout...', template_format.upper().ljust(4))
            else:
                outfile = os.path.join(outputPath, outputFilePattern.format(name=name, type=table_type, ext=template_format))
                logging.info('Writing %s into %s ...', template_format.upper().ljust(4), outfile)

            this_template_values = dict(title=title, body=rows, foot=stats, foot_columns=stats_columns)
            this_template_values.update(template_values.__dict__)

            futures.append(parallel.submit(
                write_table_in_format,
                template_format, outfile, this_template_values,
                options.show_table and template_format == 'html',
                ))

    # write normal tables
    write_table("table", name, rows,
                use_local_summary=(not options.correct_only and not options.common))

    # write difference tables
    if rowsDiff:
        write_table("diff", name + " differences", rowsDiff, use_local_summary=False)

    return futures
1130817
def create_gtk_grid(self, row_spacing=6, col_spacing=6, row_homogenous=False, col_homogenous=True):
        
        grid_lang = Gtk.Grid()
        grid_lang.set_column_spacing(row_spacing)
        grid_lang.set_row_spacing(col_spacing)
        grid_lang.set_border_width(12)
        grid_lang.set_row_homogeneous(row_homogenous)
        grid_lang.set_column_homogeneous(col_homogenous)
        return grid_lang
890554
public static ProfileSummaryBuilder getInstance(Context context,
            Profile profile, ProfileSummaryWriter profileWriter) {
        return new ProfileSummaryBuilder(context, profile, profileWriter);
    }
1115145
def _outputs(self):
        
        layers = OrderedDict()
        layers[layer_purpose_exposure_summary['key']] = (
            self._exposure_summary)
        layers[layer_purpose_aggregate_hazard_impacted['key']] = (
            self._aggregate_hazard_impacted)
        layers[layer_purpose_aggregation_summary['key']] = (
            self._aggregation_summary)
        layers[layer_purpose_analysis_impacted['key']] = (
            self._analysis_impacted)
        layers[layer_purpose_exposure_summary_table['key']] = (
            self._exposure_summary_table)
        layers[layer_purpose_profiling['key']] = self._profiling_table

        # Extra layers produced by pre-processing
        layers.update(self._preprocessors_layers)

        for expected_purpose, layer in list(layers.items()):
            if layer:
                purpose = layer.keywords.get('layer_purpose')
                if purpose != expected_purpose:
                    # ET 18/11/16
                    # I'm disabling this check. If an exception is raised in
                    # the IF, this exception might be raised and will hide the
                    # other one.
                    # raise Exception('Wrong layer purpose : %s != %s' % (
                    #     purpose, expected_purpose))
                    pass

        # Remove layers which are not set.
        layers = [layer for layer in list(layers.values()) if layer]
        return layers
566773
def profile(schemaname='sensordata', profiletype='pjs'):
    """"""

    db_log("Profiling ", schemaname)

    schema = schemastore[schemaname]['schema']

    db_log("Schema: ", schema, lvl=debug)

    testclass = None

    if profiletype == 'warmongo':
        db_log("Running Warmongo benchmark")
        testclass = warmongo.model_factory(schema)
    elif profiletype == 'pjs':
        db_log("Running PJS benchmark")
        try:
            import python_jsonschema_objects as pjs
        except ImportError:
            db_log("PJS benchmark selected but not available. Install "
                   "python_jsonschema_objects (PJS)")
            return

        db_log()
        builder = pjs.ObjectBuilder(schema)
        ns = builder.build_classes()
        pprint(ns)
        testclass = ns[schemaname]
        db_log("ns: ", ns, lvl=warn)

    if testclass is not None:
        db_log("Instantiating elements...")
        for i in range(100):
            testclass()
    else:
        db_log("No Profiletype available!")

    db_log("Profiling done")
13166
def create_data_table(self):
        """"""
        self.dataTable = DataFrameView(self, self.dataModel,
                                       self.table_header.horizontalHeader(),
                                       self.hscroll, self.vscroll)
        self.dataTable.verticalHeader().hide()
        self.dataTable.horizontalHeader().hide()
        self.dataTable.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.dataTable.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.dataTable.setHorizontalScrollMode(QTableView.ScrollPerPixel)
        self.dataTable.setVerticalScrollMode(QTableView.ScrollPerPixel)
        self.dataTable.setFrameStyle(QFrame.Plain)
        self.dataTable.setItemDelegate(QItemDelegate())
        self.layout.addWidget(self.dataTable, 1, 1)
        self.setFocusProxy(self.dataTable)
        self.dataTable.sig_sort_by_column.connect(self._sort_update)
        self.dataTable.sig_fetch_more_columns.connect(self._fetch_more_columns)
        self.dataTable.sig_fetch_more_rows.connect(self._fetch_more_rows)
1302689
def _createGsshaPyObjects(self, cell):
        
        # Initialize GSSHAPY GridPipeCell object
        gridCell = GridPipeCell(cellI=cell['i'],
                                cellJ=cell['j'],
                                numPipes=cell['numPipes'])

        # Associate GridPipeCell with GridPipeFile
        gridCell.gridPipeFile = self

        for spipe in cell['spipes']:
            # Create GSSHAPY GridPipeNode object
            gridNode = GridPipeNode(linkNumber=spipe['linkNumber'],
                                    nodeNumber=spipe['nodeNumber'],
                                    fractPipeLength=spipe['fraction'])

            # Associate GridPipeNode with GridPipeCell
            gridNode.gridPipeCell = gridCell
261547
def run(self):
        '''
        
        '''
        profiling_enabled = self.opts.get('profiling_enabled', False)
        try:
            pr = salt.utils.profile.activate_profile(profiling_enabled)
            try:
                ret = self.call()
            finally:
                salt.utils.profile.output_profile(
                    pr,
                    stats_path=self.opts.get('profiling_path', '/tmp/stats'),
                    stop=True)
            out = ret.get('out', 'nested')
            if self.opts['print_metadata']:
                print_ret = ret
                out = 'nested'
            else:
                print_ret = ret.get('return', {})
            salt.output.display_output(
                    {'local': print_ret},
                    out=out,
                    opts=self.opts,
                    _retcode=ret.get('retcode', 0))
            # _retcode will be available in the kwargs of the outputter function
            if self.opts.get('retcode_passthrough', False):
                sys.exit(ret['retcode'])
            elif ret['retcode'] != salt.defaults.exitcodes.EX_OK:
                sys.exit(salt.defaults.exitcodes.EX_GENERIC)
        except SaltInvocationError as err:
            raise SystemExit(err)
146321
def ListProfilers(self):
    """"""
    table_view = views.ViewsFactory.GetTableView(
        self._views_format_type, column_names=['Name', 'Description'],
        title='Profilers')

    profilers_information = sorted(
        profiling.ProfilingArgumentsHelper.PROFILERS_INFORMATION.items())
    for name, description in profilers_information:
      table_view.AddRow([name, description])
    table_view.Write(self._output_writer)
920852
def __profile_definition(self, pipeline_name):
        
        pipe = self.flsh.Operations[pipeline_name]
        x_st = pipe.GetUserVariable(PROFILE_LENGTH_ST).Variable()
        x_non_st = pipe.GetUserVariable(PROFILE_LENGTH_NON_ST).Variable()
        timesteps = pipe.GetUserVariable(PROFILE_TIME).Variable()
        self.pipes[pipeline_name] = {'grid': x_st,
                                     'non_st_grid': x_non_st,
                                     'timesteps': timesteps,
                                     'data': {}
                                    }
        return pipe
239047
def create_benchmark(name, log_file, level=logging.INFO):
    
    handler = logging.FileHandler(log_file)
    rtf_handler = RotatingFileHandler(log_file, maxBytes=30000, backupCount=0)
    formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
    handler.setFormatter(formatter)
    logger = logging.getLogger(name)
    logger.setLevel(level)
    logger.addHandler(handler)
    logger.addHandler(rtf_handler)
    return logger
698623
def _profile_table(self, batch_id):
        
        # TODO(rkn): This method should support limiting the number of log
        # events and should also support returning a window of events.
        message = self._execute_command(batch_id, "RAY.TABLE_LOOKUP",
                                        ray.gcs_utils.TablePrefix.PROFILE, "",
                                        batch_id.binary())

        if message is None:
            return []

        gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(
            message, 0)

        profile_events = []
        for i in range(gcs_entries.EntriesLength()):
            profile_table_message = (
                ray.gcs_utils.ProfileTableData.GetRootAsProfileTableData(
                    gcs_entries.Entries(i), 0))

            component_type = decode(profile_table_message.ComponentType())
            component_id = binary_to_hex(profile_table_message.ComponentId())
            node_ip_address = decode(
                profile_table_message.NodeIpAddress(), allow_none=True)

            for j in range(profile_table_message.ProfileEventsLength()):
                profile_event_message = profile_table_message.ProfileEvents(j)

                profile_event = {
                    "event_type": decode(profile_event_message.EventType()),
                    "component_id": component_id,
                    "node_ip_address": node_ip_address,
                    "component_type": component_type,
                    "start_time": profile_event_message.StartTime(),
                    "end_time": profile_event_message.EndTime(),
                    "extra_data": json.loads(
                        decode(profile_event_message.ExtraData())),
                }

                profile_events.append(profile_event)

        return profile_events
1257386
def _build_table(self) -> Dict[State, Tuple[Multiplex, ...]]:
        
        result: Dict[State, Tuple[Multiplex, ...]] = {}
        for state in self.influence_graph.all_states():
            result[state] = tuple(multiplex for multiplex in self.influence_graph.multiplexes 
                                  if multiplex.is_active(state))
        return result
1070270
def convexhull(data, col, fill=True, point_size=4):
    
    from geoplotlib.layers import ConvexHullLayer
    _global_config.layers.append(ConvexHullLayer(data, col, fill, point_size))
539544
def build_scandata_table(self):
        
        shape = self._norm_vals.shape
        col_norm = Column(name="norm", dtype=float)
        col_normv = Column(name="norm_scan", dtype=float,
                           shape=shape)
        col_dll = Column(name="dloglike_scan", dtype=float,
                         shape=shape)
        tab = Table(data=[col_norm, col_normv, col_dll])
        tab.add_row({"norm": 1.,
                     "norm_scan": self._norm_vals,
                     "dloglike_scan": -1 * self._nll_vals})
        return tab