Helper method to be used in the __call__ method to get a
        suitable plot or widget object and the appropriate format.
174835
def _validate(self, obj, fmt, **kwargs):
        
        if isinstance(obj, tuple(self.widgets.values())):
            return obj, 'html'
        plot = self.get_plot(obj, renderer=self, **kwargs)

        fig_formats = self.mode_formats['fig'][self.mode]
        holomap_formats = self.mode_formats['holomap'][self.mode]

        if fmt in ['auto', None]:
            if (((len(plot) == 1 and not plot.dynamic)
                or (len(plot) > 1 and self.holomap is None) or
                (plot.dynamic and len(plot.keys[0]) == 0)) or
                not unbound_dimensions(plot.streams, plot.dimensions, no_duplicates=False)):
                fmt = fig_formats[0] if self.fig=='auto' else self.fig
            else:
                fmt = holomap_formats[0] if self.holomap=='auto' else self.holomap

        if fmt in self.widgets:
            plot = self.get_widget(plot, fmt, display_options={'fps': self.fps})
            fmt = 'html'

        all_formats = set(fig_formats + holomap_formats)
        if fmt not in all_formats:
            raise Exception("Format %r not supported by mode %r. Allowed formats: %r"
                            % (fmt, self.mode, fig_formats + holomap_formats))
        self.last_plot = plot
        return plot, fmt
1048508
def info(cls, obj, ansi=True, backend='matplotlib', visualization=True,
             recursive=False, pattern=None, elements=[]):
        
        parameterized_object = isinstance(obj, param.Parameterized)
        parameterized_class = (isinstance(obj,type)
                               and  issubclass(obj,param.Parameterized))
        info = None
        if parameterized_object or parameterized_class:
            info = InfoPrinter.info(obj, ansi=ansi, backend=backend,
                                    visualization=visualization,
                                    pattern=pattern, elements=elements)

        if parameterized_object and recursive:
            hierarchy = obj.traverse(lambda x: type(x))
            listed = []
            for c in hierarchy[1:]:
                if c not in listed:
                    inner_info = InfoPrinter.info(c, ansi=ansi, backend=backend,
                                                  visualization=visualization,
                                                  pattern=pattern)
                    black = '\x1b[1;30m%s\x1b[0m' if ansi else '%s'
                    info +=  '\n\n' + (black % inner_info)
                    listed.append(c)
        return info
1200793
def _callable_func(self, func, axis, *args, **kwargs):
        

        def callable_apply_builder(df, axis=0):
            if not axis:
                df.index = index
                df.columns = pandas.RangeIndex(len(df.columns))
            else:
                df.columns = index
                df.index = pandas.RangeIndex(len(df.index))
            result = df.apply(func, axis=axis, *args, **kwargs)
            return result

        index = self.index if not axis else self.columns
        func_prepared = self._build_mapreduce_func(callable_apply_builder, axis=axis)
        result_data = self._map_across_full_axis(axis, func_prepared)
        return self._post_process_apply(result_data, axis)
1176867
def _output_format(cls, func, override=None):
        
        @wraps(func)
        def _format_wrapper(self, *args, **kwargs):
            call_response, data_key, meta_data_key = func(
                self, *args, **kwargs)
            if 'json' in self.output_format.lower() or 'pandas' \
                    in self.output_format.lower():
                data = call_response[data_key]
                if meta_data_key is not None:
                    meta_data = call_response[meta_data_key]
                else:
                    meta_data = None
                # Allow to override the output parameter in the call
                if override is None:
                    output_format = self.output_format.lower()
                elif 'json' or 'pandas' in override.lower():
                    output_format = override.lower()
                # Choose output format
                if output_format == 'json':
                    return data, meta_data
                elif output_format == 'pandas':
                    if isinstance(data, list):
                        # If the call returns a list, then we will append them
                        # in the resulting data frame. If in the future
                        # alphavantage decides to do more with returning arrays
                        # this might become buggy. For now will do the trick.
                        data_array = []
                        for val in data:
                            data_array.append([v for _, v in val.items()])
                        data_pandas = pandas.DataFrame(data_array, columns=[
                            k for k, _ in data[0].items()])
                    else:
                        data_pandas = pandas.DataFrame.from_dict(data,
                                                                 orient='index',
                                                                 dtype=float)
                    data_pandas.index.name = 'date'
                    if 'integer' in self.indexing_type:
                        # Set Date as an actual column so a new numerical index
                        # will be created, but only when specified by the user.
                        data_pandas.reset_index(level=0, inplace=True)
                    return data_pandas, meta_data
            elif 'csv' in self.output_format.lower():
                return call_response, None
            else:
                raise ValueError('Format: {} is not supported'.format(
                    self.output_format))
        return _format_wrapper
170430
def hist_calls_with_dims(**dims):
    
    def hist_wrapper(fn):
        @functools.wraps(fn)
        def fn_wrapper(*args, **kwargs):
            _histogram = histogram(
                "%s_calls" % pyformance.registry.get_qualname(fn), **dims)
            rtn = fn(*args, **kwargs)
            if type(rtn) in (int, float):
                _histogram.add(rtn)
            return rtn
        return fn_wrapper
    return hist_wrapper
602810
def _call(self, x):
        """"""
        if self.impl == 'pywt':
            coeffs = pywt.wavedecn(
                x, wavelet=self.pywt_wavelet, level=self.nlevels,
                mode=self.pywt_pad_mode, axes=self.axes)
            return pywt.ravel_coeffs(coeffs, axes=self.axes)[0]
        else:
            raise RuntimeError("bad `impl` '{}'".format(self.impl))
785903
def get_plot(self, width=8, height=8):
        
        plt = pretty_plot(width, height)
        for label, electrode in self._electrodes.items():
            (x, y) = self.get_plot_data(electrode)
            plt.plot(x, y, '-', linewidth=2, label=label)

        plt.legend()
        if self.xaxis == "capacity":
            plt.xlabel('Capacity (mAh/g)')
        else:
            plt.xlabel('Fraction')
        plt.ylabel('Voltage (V)')
        plt.tight_layout()
        return plt
785310
def _call(self, x):
        """"""
        y = np.bincount(self._indices_flat, weights=x,
                        minlength=self.range.size)

        out = y.reshape(self.range.shape)

        if self.variant == 'dirac':
            weights = getattr(self.range, 'cell_volume', 1.0)
        elif self.variant == 'char_fun':
            weights = 1.0
        else:
            raise RuntimeError('The variant "{!r}" is not yet supported'
                               ''.format(self.variant))

        if weights != 1.0:
            out /= weights

        return out
1060775
def plotER(self,*args,**kwargs):
        
        if kwargs.pop('normed',False):
            kwargs['d2']= 'ERnorm'
        else:
            kwargs['d2']= 'ER'
        return self.plot(*args,**kwargs)
530896
def _plt_handle_figure(plot):
    """

    # Preserve documentation of plot.
    @functools.wraps(plot)

    def inner(obj, **kwargs):

        # Create a figure and an axis if none were passed.
        if kwargs['ax'] is None:
            _, plt, _ = _import_plt()
            fig = plt.figure()
            global _plt_figures
            _plt_figures.append(fig)

            if (hasattr(obj, 'coords') and obj.coords.ndim == 2 and
                    obj.coords.shape[1] == 3):
                kwargs['ax'] = fig.add_subplot(111, projection='3d')
            else:
                kwargs['ax'] = fig.add_subplot(111)

        title = kwargs.pop('title')

        plot(obj, **kwargs)

        kwargs['ax'].set_title(title)

        try:
            fig.show(warn=False)
        except NameError:
            # No figure created, an axis was passed.
            pass

        return kwargs['ax'].figure, kwargs['ax']

    return inner
451262
def _call_scope(self, scope, *args, **kwargs):
        
        result = getattr(self._model, scope)(self, *args, **kwargs)

        return result or self
45914
def show(self, obj):
        
        if self.interactive:
            if isinstance(obj, list):
                return [self.get_plot(o) for o in obj]
            return self.get_plot(obj)

        from .plot import MPLPlot
        MPLPlot._close_figures = False
        try:
            plots = []
            objects = obj if isinstance(obj, list) else [obj]
            for o in objects:
                plots.append(self.get_plot(o))
            plt.show()
        except:
            raise
        finally:
            MPLPlot._close_figures = True
        return plots[0] if len(plots) == 1 else plots
445591
def get_calls_from_dict(self, file_dict, from_name, settings={}):
        '''
        
        '''

        calls = []
        call_settings = dict(settings)

        # Include all possible sections
        # The way to draw them is defined in call graph
        special_sections = {'builders', 'publishers', 'wrappers'}

        # Trigger flags
        triggers = {'trigger-builds', 'trigger-parameterized-builds'}

        if isinstance(file_dict, dict):
            for key in file_dict:

                if key in special_sections:
                    call_settings['section'] = key

                if key in triggers:
                    calls.extend(self.extract_call(file_dict[key], from_name, settings=call_settings))
                else:
                    calls.extend(self.get_calls_from_dict(file_dict[key], from_name, settings=call_settings))
        elif type(file_dict) == list:
            for value in file_dict:
                calls.extend(self.get_calls_from_dict(value, from_name, settings=call_settings))

        return calls
157173
def callgraph(func):
    ''' 
    '''
    import pycallgraph
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        pycallgraph.start_trace()
        func(*args, **kwargs)
        pycallgraph.save_dot('callgraph.log')
        pycallgraph.make_dot_graph('callgraph.png')
        #pycallgraph.make_dot_graph('callgraph.jpg', format='jpg', tool='neato')
    return wrapper
1310434
def hist_calls(fn):
    
    @functools.wraps(fn)
    def wrapper(*args, **kwargs):
        _histogram = histogram(
            "%s_calls" % pyformance.registry.get_qualname(fn))
        rtn = fn(*args, **kwargs)
        if type(rtn) in (int, float):
            _histogram.add(rtn)
        return rtn
    return wrapper
1268014
def get_chart(self, id, **kwargs):
        "
        resp = self._get_object_by_name(self._CHART_ENDPOINT_SUFFIX, id,
                                        **kwargs)
        return resp
291312
def apply(self, func, axis, *args, **kwargs):
        
        if callable(func):
            return self._callable_func(func, axis, *args, **kwargs)
        elif isinstance(func, dict):
            return self._dict_func(func, axis, *args, **kwargs)
        elif is_list_like(func):
            return self._list_like_func(func, axis, *args, **kwargs)
        else:
            pass