def plotcdf(self, x=None, xmin=None, alpha=None, pointcolor='<STR_LIT:k>',<EOL>dolog=True, zoom=True, pointmarker='<STR_LIT:+>', **kwargs):

if x is None: x=self.data<EOL>if xmin is None: xmin=self._xmin<EOL>if alpha is None: alpha=self._alpha<EOL>x=np.sort(x)<EOL>n=len(x)<EOL>xcdf = np.arange(n,<NUM_LIT:0>,-<NUM_LIT:1>,dtype='<STR_LIT:float>')/float(n)<EOL>q = x[x>=xmin]<EOL>fcdf = (q/xmin)**(<NUM_LIT:1>-alpha)<EOL>nc = xcdf[argmax(x>=xmin)]<EOL>fcdf_norm = nc*fcdf<EOL>D_location = argmax(xcdf[x>=xmin]-fcdf_norm)<EOL>pylab.vlines(q[D_location], xcdf[x>=xmin][D_location],<EOL>fcdf_norm[D_location], color='<STR_LIT:m>', linewidth=<NUM_LIT:2>, zorder=<NUM_LIT:2>)<EOL>pylab.plot([q[D_location]]*<NUM_LIT:2>,<EOL>[xcdf[x>=xmin][D_location], fcdf_norm[D_location]],<EOL>color='<STR_LIT:m>',<EOL>marker='<STR_LIT:s>', zorder=<NUM_LIT:3>)<EOL>if dolog:<EOL><INDENT>pylab.loglog(x,xcdf,marker=pointmarker,color=pointcolor,**kwargs)<EOL>pylab.loglog(q,fcdf_norm,'<STR_LIT:r>',**kwargs)<EOL><DEDENT>else:<EOL><INDENT>pylab.semilogx(x,xcdf,marker=pointmarker,color=pointcolor,**kwargs)<EOL>pylab.semilogx(q,fcdf_norm,'<STR_LIT:r>',**kwargs)<EOL><DEDENT>if zoom:<EOL><INDENT>pylab.axis([xmin, x.max(), xcdf.min(), nc])<EOL><DEDENT>


def plotpdf(self, x=None, xmin=None, alpha=None, nbins=<NUM_LIT:50>, dolog=True,<EOL>dnds=False, drawstyle='<STR_LIT>', histcolor='<STR_LIT:k>', plcolor='<STR_LIT:r>',<EOL>fill=False, dohist=True, **kwargs):

if x is None:<EOL><INDENT>x=self.data<EOL><DEDENT>if xmin is None:<EOL><INDENT>xmin=self._xmin<EOL><DEDENT>if alpha is None:<EOL><INDENT>alpha=self._alpha<EOL><DEDENT>x=np.sort(x)<EOL>pylab.gca().set_xscale('<STR_LIT>')<EOL>pylab.gca().set_yscale('<STR_LIT>')<EOL>if dnds:<EOL><INDENT>hb = pylab.histogram(x,bins=np.logspace(log10(min(x)),log10(max(x)),nbins))<EOL>h = hb[<NUM_LIT:0>]<EOL>b = hb[<NUM_LIT:1>]<EOL>db = hb[<NUM_LIT:1>][<NUM_LIT:1>:]-hb[<NUM_LIT:1>][:-<NUM_LIT:1>]<EOL>h = h/db<EOL>if dohist:<EOL><INDENT>pylab.plot(b[:-<NUM_LIT:1>],h,drawstyle=drawstyle,color=histcolor,**kwargs)<EOL><DEDENT><DEDENT>elif dolog:<EOL><INDENT>hb = pylab.hist(x, bins=np.logspace(log10(min(x)), log10(max(x)),<EOL>nbins), log=True, fill=fill,<EOL>edgecolor=histcolor, **kwargs)<EOL>alpha -= <NUM_LIT:1><EOL>h,b=hb[<NUM_LIT:0>],hb[<NUM_LIT:1>]<EOL>if not dohist:<EOL><INDENT>for rect in hb[<NUM_LIT:2>]:<EOL><INDENT>rect.set_visible(False)<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>hb = pylab.hist(x, bins=np.linspace((min(x)), (max(x)), nbins),<EOL>fill=fill, edgecolor=histcolor, **kwargs)<EOL>h,b=hb[<NUM_LIT:0>],hb[<NUM_LIT:1>]<EOL>if not dohist:<EOL><INDENT>for rect in hb[<NUM_LIT:2>]:<EOL><INDENT>rect.set_visible(False)<EOL><DEDENT><DEDENT><DEDENT>b = (b[<NUM_LIT:1>:]+b[:-<NUM_LIT:1>])/<NUM_LIT><EOL>q = x[x>=xmin]<EOL>px = (alpha-<NUM_LIT:1>)/xmin * (q/xmin)**(-alpha)<EOL>plotloc = (b>xmin)*(h><NUM_LIT:0>)<EOL>norm = np.median(h[plotloc] / ((alpha-<NUM_LIT:1>)/xmin *<EOL>(b[plotloc]/xmin)**(-alpha)))<EOL>px = px*norm<EOL>plotx = pylab.linspace(q.min(),q.max(),<NUM_LIT:1000>)<EOL>ploty = (alpha-<NUM_LIT:1>)/xmin * (plotx/xmin)**(-alpha) * norm<EOL>pylab.plot(plotx, ploty, color=plcolor, **kwargs)<EOL>axlims = pylab.axis()<EOL>pylab.vlines(xmin, axlims[<NUM_LIT:2>], max(px), colors=plcolor,<EOL>linestyle='<STR_LIT>')<EOL>if dolog and min(x) <= <NUM_LIT:0>:<EOL><INDENT>lolim = <NUM_LIT:0.1><EOL><DEDENT>else:<EOL><INDENT>lolim = min(x)<EOL><DEDENT>pylab.gca().set_xlim(lolim, max(x))<EOL>

Plots PDF and powerlaw.

kwargs is passed to pylab.hist and pylab.plot


if not(xmin): xmin=self._xmin<EOL>if not(alpha): alpha=self._alpha<EOL>if not(x): x=np.sort(self.data[self.data>xmin])<EOL>else: x=np.sort(x[x>xmin])<EOL>m0 = min(x)<EOL>N = (<NUM_LIT:1.0>+np.arange(len(x)))[::-<NUM_LIT:1>]<EOL>xmodel = m0 * N**(<NUM_LIT:1>/(<NUM_LIT:1>-alpha)) / max(N)**(<NUM_LIT:1>/(<NUM_LIT:1>-alpha))<EOL>if dolog:<EOL><INDENT>pylab.loglog(x,xmodel,'<STR_LIT:.>',**kwargs)<EOL>pylab.gca().set_xlim(min(x),max(x))<EOL>pylab.gca().set_ylim(min(x),max(x))<EOL><DEDENT>else:<EOL><INDENT>pylab.plot(x,xmodel,'<STR_LIT:.>',**kwargs)<EOL><DEDENT>pylab.plot([min(x),max(x)],[min(x),max(x)],'<STR_LIT>')<EOL>pylab.xlabel("<STR_LIT>")<EOL>pylab.ylabel("<STR_LIT>")<EOL>

Plots the power-law-predicted value on the Y-axis against the real
values along the X-axis.  Can be used as a diagnostic of the fit
quality.


<EOL>if scipyOK:<EOL><INDENT>fitpars = scipy.stats.lognorm.fit(self.data)<EOL>self.lognormal_dist = scipy.stats.lognorm(*fitpars)<EOL>self.lognormal_ksD,self.lognormal_ksP = scipy.stats.kstest(self.data,self.lognormal_dist.cdf)<EOL>self.lognormal_likelihood = -<NUM_LIT:1>*scipy.stats.lognorm.nnlf(fitpars,self.data)<EOL>self.power_lognorm_likelihood = (self._likelihood + self.lognormal_likelihood)<EOL>self.likelihood_ratio_D = -<NUM_LIT:2> * (log(self._likelihood/self.lognormal_likelihood))<EOL>if doprint:<EOL><INDENT>print("<STR_LIT>" % (self.lognormal_ksD,self.lognormal_ksP), end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % self.likelihood_ratio_D)<EOL>print("<STR_LIT>")<EOL><DEDENT><DEDENT>

Use the maximum likelihood estimator for a lognormal distribution to
produce the best-fit lognormal parameters


if not hasattr(self,'<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>normalized_pdf = self.lognormal_dist.pdf(self.data)/self.lognormal_dist.pdf(self.data).max()<EOL>minY,maxY = pylab.gca().get_ylim()<EOL>pylab.plot(self.data,normalized_pdf*maxY,'<STR_LIT:.>',**kwargs)<EOL>


if not hasattr(self,'<STR_LIT>'):<EOL><INDENT>return<EOL><DEDENT>x=np.sort(self.data)<EOL>n=len(x)<EOL>xcdf = np.arange(n,<NUM_LIT:0>,-<NUM_LIT:1>,dtype='<STR_LIT:float>')/float(n)<EOL>lcdf = self.lognormal_dist.sf(x)<EOL>D_location = argmax(xcdf-lcdf)<EOL>pylab.vlines(x[D_location],xcdf[D_location],lcdf[D_location],color='<STR_LIT:m>',linewidth=<NUM_LIT:2>)<EOL>pylab.plot(x, lcdf,'<STR_LIT:U+002C>',**kwargs)<EOL>


C = <NUM_LIT:1>/(-xm/(<NUM_LIT:1> - a) - xm/a + math.exp(a)*xm/a)<EOL>Ppl = lambda X: <NUM_LIT:1>+C*(xm/(<NUM_LIT:1>-a)*(X/xm)**(<NUM_LIT:1>-a))<EOL>Pexp = lambda X: C*xm/a*math.exp(a)-C*(xm/a)*math.exp(-a*(X/xm-<NUM_LIT:1>))<EOL>d=Ppl(x)<EOL>d[x<xm]=Pexp(x)<EOL>return d<EOL>

CDF(x) for the piecewise distribution exponential x<xmin, powerlaw x>=xmin
This is the CDF version of the distributions drawn in fig 3.4a of Clauset et al.


C = <NUM_LIT:1>/(-xm/(<NUM_LIT:1> - a) - xm/a + math.exp(a)*xm/a)<EOL>Pxm = <NUM_LIT:1>+C*(xm/(<NUM_LIT:1>-a))<EOL>pp = P<EOL>x = xm*(pp-<NUM_LIT:1>)*(<NUM_LIT:1>-a)/(C*xm)**(<NUM_LIT:1>/(<NUM_LIT:1>-a)) if pp >= Pxm else (math.log( ((C*xm/a)*math.exp(a)-pp)/(C*xm/a)) - a) * (-xm/a)<EOL>return x<EOL>

Inverse CDF for a piecewise PDF as defined in eqn. 3.10
of Clauset et al.


x = (<NUM_LIT:1>-P)**(<NUM_LIT:1>/(<NUM_LIT:1>-a)) * xm<EOL>return x<EOL>


neg = [i<<NUM_LIT:0> for i in x]<EOL>if any(neg) > <NUM_LIT:0>:<EOL><INDENT>print("<STR_LIT>" % (sum(neg)))<EOL>x = [i for i in x if i > <NUM_LIT:0>]<EOL><DEDENT>self.data = x<EOL>self.plfit(**kwargs)<EOL>

Initializes and fits the power law.  Can pass "quiet" to turn off
output (except for warnings; "silent" turns off warnings)


def alpha(xmin,x=x):<EOL><INDENT>"""<STR_LIT>"""<EOL>x = [i for i in x if i>=xmin]<EOL>n = sum(x)<EOL>divsum = sum([math.log(i/xmin) for i in x])<EOL>if divsum == <NUM_LIT:0>:<EOL><INDENT>return float('<STR_LIT>')<EOL><DEDENT>a = <NUM_LIT:1> + float(n) / divsum<EOL>return a<EOL><DEDENT>return alpha<EOL>

Create a mappable function alpha to apply to each xmin in a list of xmins.
        This is essentially the slow version of fplfit/cplfit, though I bet it could
        be speeded up with a clever use of parellel_map.  Not intended to be used by users.


x = self.data<EOL>z = sorted(x)<EOL>t = time.time()<EOL>possible_xmins = sorted(set(z))<EOL>argxmins = [z.index(i) for i in possible_xmins]<EOL>self._nunique = len(possible_xmins)<EOL>if xmin is None:<EOL><INDENT>av  = map(self.alpha_(z),possible_xmins)<EOL>dat = map(self.kstest_(z),possible_xmins)<EOL>sigma = [(a-<NUM_LIT:1>)/math.sqrt(len(z)-i+<NUM_LIT:1>) for a,i in zip(av,argxmins)]<EOL>if nosmall:<EOL><INDENT>goodvals = [s<<NUM_LIT:0.1> for s in sigma]<EOL>if False in goodvals: <EOL><INDENT>nmax = goodvals.index(False)<EOL>dat = dat[:nmax]<EOL>possible_xmins = possible_xmins[:nmax]<EOL>av = av[:nmax]<EOL><DEDENT>else:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT>if not quiet: print("<STR_LIT>" % (time.time()-t))<EOL>self._av = av<EOL>self._xmin_kstest = dat<EOL>self._sigma = sigma<EOL>if nosmall:<EOL><INDENT>xmin = possible_xmins[dat.index(min(dat))] <EOL><DEDENT>else:<EOL><INDENT>xmin = possible_xmins[dat.index(min(dat[:-<NUM_LIT:1>]))] <EOL><DEDENT><DEDENT>z     = [i for i in z if i >= xmin]<EOL>n     = len(z)<EOL>alpha = <NUM_LIT:1> + n / sum([math.log(a/xmin) for a in z]) <EOL>if finite:<EOL><INDENT>alpha = alpha*(n-<NUM_LIT:1.>)/n+<NUM_LIT:1.>/n<EOL><DEDENT>if n == <NUM_LIT:1> and not silent:<EOL><INDENT>print("<STR_LIT>")<EOL>self._alpha = <NUM_LIT:0><EOL>self._alphaerr = <NUM_LIT:0><EOL>self._likelihood = <NUM_LIT:0><EOL>self._ks = <NUM_LIT:0><EOL>self._ks_prob = <NUM_LIT:0><EOL>self._xmin = xmin<EOL>return xmin,<NUM_LIT:0><EOL><DEDENT>if n < <NUM_LIT:50> and not finite and not silent:<EOL><INDENT>print('<STR_LIT>' % n)<EOL><DEDENT>ks = max( [abs( i/float(n) - (<NUM_LIT:1>-(xmin/b)**(alpha-<NUM_LIT:1>))) for i,b in zip(range(n),z)] )<EOL>sl = sum([math.log(a/xmin) for a in z])<EOL>L = (n*math.log((alpha-<NUM_LIT:1>)/xmin) - alpha*sl)<EOL>self._likelihood = L<EOL>self._xmin = xmin<EOL>self._xmins = possible_xmins<EOL>self._alpha= alpha<EOL>self._alphaerr = (alpha-<NUM_LIT:1>)/math.sqrt(n)<EOL>self._ks = ks  <EOL>self._ngtx = n<EOL>if math.isnan(L) or math.isnan(xmin) or math.isnan(alpha):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not quiet:<EOL><INDENT>if verbose: print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % xmin, end='<STR_LIT:U+0020>')<EOL>if verbose: print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % n, end='<STR_LIT:U+0020>')<EOL>if verbose: print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % (alpha,self._alphaerr), end='<STR_LIT:U+0020>') <EOL>if verbose: print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % L, end='<STR_LIT:U+0020>')<EOL>if verbose: print("<STR_LIT>", end='<STR_LIT:U+0020>')<EOL>print("<STR_LIT>" % (ks))<EOL><DEDENT>return xmin,alpha<EOL>

A pure-Python implementation of the Matlab code http://www.santafe.edu/~aaronc/powerlaws/plfit.m
from http://www.santafe.edu/~aaronc/powerlaws/

See A. Clauset, C.R. Shalizi, and M.E.J. Newman, "Power-law distributions
in empirical data" SIAM Review, 51, 661-703 (2009). (arXiv:0706.1062)
http://arxiv.org/abs/0706.1062

nosmall is on by default; it rejects low s/n points
can specify xmin to skip xmin estimation

This is only for continuous distributions; I have not implemented a
pure-python discrete distribution fitter


n = len(x)<EOL>btop = n * (log(x)*log(y)).sum() - (log(x)).sum()*(log(y)).sum()<EOL>bbottom = n*(log(x)**<NUM_LIT:2>).sum() - (log(x).sum())**<NUM_LIT:2><EOL>b = btop / bbottom<EOL>a = ( log(y).sum() - b * log(x).sum() ) / n<EOL>A = exp(a)<EOL>return A,b<EOL>

Returns A and B in y=Ax^B
http://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html


xmins = unique(x)<EOL>xmins = xmins[<NUM_LIT:1>:-<NUM_LIT:1>]<EOL>dat = xmins * <NUM_LIT:0> <EOL>z = sort(x)<EOL>for xm in arange(len(xmins)):<EOL><INDENT>xmin = xmins[xm]<EOL>z    = z[z>=xmin] <EOL>n    = float(len(z))<EOL>a    =  n / sum( log(z/xmin) )<EOL>if nosmall:<EOL><INDENT>if (a-<NUM_LIT:1>)/sqrt(n) > <NUM_LIT:0.1>:<EOL><INDENT>dat = dat[:xm]<EOL>xm = len(xmins)+<NUM_LIT:1><EOL>break<EOL><DEDENT><DEDENT>cx   = arange(n)/float(n)  <EOL>cf   = <NUM_LIT:1>-(xmin/z)**a  <EOL>dat[xm] = max( abs(cf-cx) )<EOL><DEDENT>D     = min(dat);<EOL>xmin  = xmins[argmin(dat)]<EOL>z     = x[x>=xmin]<EOL>n     = len(z)<EOL>alpha = <NUM_LIT:1> + n / sum( log(z/xmin) )<EOL>if finite:<EOL><INDENT>alpha = alpha*(n-<NUM_LIT:1>)/n+<NUM_LIT:1>/n<EOL><DEDENT>if n < <NUM_LIT:50> and ~finite:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>L = n*log((alpha-<NUM_LIT:1>)/xmin) - alpha*sum(log(z/xmin));<EOL>return xmin,alpha,L,dat<EOL>

A Python implementation of the Matlab code http://www.santafe.edu/~aaronc/powerlaws/plfit.m
from http://www.santafe.edu/~aaronc/powerlaws/

See A. Clauset, C.R. Shalizi, and M.E.J. Newman, "Power-law distributions
in empirical data" SIAM Review, to appear (2009). (arXiv:0706.1062)
http://arxiv.org/abs/0706.1062


x=sort(x)<EOL>n=len(x)<EOL>xcdf = arange(n,<NUM_LIT:0>,-<NUM_LIT:1>,dtype='<STR_LIT:float>')/float(n)<EOL>q = x[x>=xmin]<EOL>fcdf = (q/xmin)**(<NUM_LIT:1>-alpha)<EOL>nc = xcdf[argmax(x>=xmin)]<EOL>fcdf_norm = nc*fcdf<EOL>loglog(x,xcdf)<EOL>loglog(q,fcdf_norm)<EOL>


x=sort(x)<EOL>n=len(x)<EOL>if dolog:<EOL><INDENT>hb = hist(x,bins=logspace(log10(min(x)),log10(max(x)),nbins),log=True)<EOL>alpha += <NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>hb = hist(x,bins=linspace((min(x)),(max(x)),nbins))<EOL><DEDENT>h,b=hb[<NUM_LIT:0>],hb[<NUM_LIT:1>]<EOL>b = b[<NUM_LIT:1>:]<EOL>q = x[x>=xmin]<EOL>px = (alpha-<NUM_LIT:1>)/xmin * (q/xmin)**(-alpha)<EOL>arg = argmin(abs(b-xmin))<EOL>norm = mean( h[b>xmin] / ((alpha-<NUM_LIT:1>)/xmin * (b[b>xmin]/xmin)**(-alpha))  )<EOL>px = px*norm<EOL>loglog(q,px)<EOL>gca().set_xlim(min(x),max(x))<EOL>


@property<EOL><INDENT>def description(self) -> str:<DEDENT>

return self.__doc__ or '<STR_LIT>'<EOL>

Service description.

        By default, return the class docstring.


@property<EOL><INDENT>def logger(self) -> logging.Logger:<DEDENT>

return logging.getLogger(name=self.name)<EOL>


def configure_argument_parser(self, parser: argparse.ArgumentParser):

Add configuration to the ArgumentParser.

        Subclasses can implement this to add options to the ArgumentParser for
        the script.


async def on_application_startup(self, application: Application):

Handler run at Application startup.

        This must be a coroutine.

        Subclasses can implement this to perform operations as part of
        Application.on_startup handler.


async def on_application_shutdown(self, application: Application):

Handler run at Application shutdown.

        This must be a coroutine.

        Subclasses can implement this to perform operations as part of
        Application.on_shutdown handler.


def configure(self, args: argparse.Namespace):

Perform additional confguration steps at script startup.

        Subclasses can implement this.


def create_metrics(<EOL>self, metric_configs: Iterable[MetricConfig]) -> Dict[str, Metric]:

return self.registry.create_metrics(metric_configs)<EOL>

Create and register metrics from a list of MetricConfigs.


def _setup_logging(self, log_level: str):

level = getattr(logging, log_level)<EOL>names = (<EOL>'<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>', self.name)<EOL>for name in names:<EOL><INDENT>setup_logger(name=name, stream=sys.stderr, level=level)<EOL><DEDENT>

Setup logging for the application and aiohttp.


def _configure_registry(self, include_process_stats: bool = False):

if include_process_stats:<EOL><INDENT>self.registry.register_additional_collector(<EOL>ProcessCollector(registry=None))<EOL><DEDENT>


def _get_exporter(self, args: argparse.Namespace) -> PrometheusExporter:

exporter = PrometheusExporter(<EOL>self.name, self.description, args.host, args.port, self.registry)<EOL>exporter.app.on_startup.append(self.on_application_startup)<EOL>exporter.app.on_shutdown.append(self.on_application_shutdown)<EOL>return exporter<EOL>

Return a :class:`PrometheusExporter` configured with args.


def create_metrics(self,<EOL>configs: Iterable[MetricConfig]) -> Dict[str, Metric]:

metrics: Dict[str, Metric] = {<EOL>config.name: self._register_metric(config)<EOL>for config in configs<EOL>}<EOL>self._metrics.update(metrics)<EOL>return metrics<EOL>

Create Prometheus metrics from a list of MetricConfigs.


def get_metric(<EOL>self, name: str,<EOL>labels: Union[Dict[str, str], None] = None) -> Metric:

metric = self._metrics[name]<EOL>if labels:<EOL><INDENT>return metric.labels(**labels)<EOL><DEDENT>return metric<EOL>

Return a metric, optionally configured with labels.


def get_metrics(self) -> Dict[str, Metric]:

return self._metrics.copy()<EOL>


self.registry.register(collector)<EOL>

Registrer an additional collector or metric.

        Metric(s) for the collector will not be include in the result of
        get_metrics.


return bytes(generate_latest(self.registry))<EOL>

Generate text with metrics values from the registry.


def set_metric_update_handler(self, handler: UpdateHandler):

self._update_handler = handler<EOL>

Set a handler to update metrics.

        The provided coroutine function is called at every request with a dict
        as argument, mapping metric names to metrics.  The signature is the
        following:

          async def update_handler(metrics):


run_app(<EOL>self.app,<EOL>host=self.host,<EOL>port=self.port,<EOL>print=lambda *args, **kargs: None,<EOL>access_log_format='<STR_LIT>')<EOL>

Run the :class:`aiohttp.web.Application` for the exporter.


def _make_application(self) -> Application:

app = Application()<EOL>app['<STR_LIT>'] = self<EOL>app.router.add_get('<STR_LIT:/>', self._handle_home)<EOL>app.router.add_get('<STR_LIT>', self._handle_metrics)<EOL>app.on_startup.append(self._log_startup_message)<EOL>return app<EOL>


async def _log_startup_message(self, app: Application):


async def _handle_home(self, request: Request) -> Response:

if self.description:<EOL><INDENT>title = f'<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>title = self.name<EOL><DEDENT>text = dedent(<EOL>f'''<STR_LIT>''')<EOL>return Response(content_type='<STR_LIT>', text=text)<EOL>


async def _handle_metrics(self, request: Request) -> Response:

if self._update_handler:<EOL><INDENT>await self._update_handler(self.registry.get_metrics())<EOL><DEDENT>response = Response(body=self.registry.generate_metrics())<EOL>response.content_type = CONTENT_TYPE_LATEST<EOL>return response<EOL>


def decorator(func):<EOL><INDENT>@wraps(func)<EOL>def wrapped_func(request, *args, **kwargs):<EOL><INDENT>if request.method not in ['<STR_LIT:GET>', '<STR_LIT:POST>']:<EOL><INDENT>return func(request, *args, **kwargs)<EOL><DEDENT>form_class = type('<STR_LIT>', (forms.Form,), fields.copy())<EOL>form = form_class(getattr(request, request.method))<EOL>if not form.is_valid():<EOL><INDENT>if settings.DEBUG:<EOL><INDENT>return JsonResponseBadRequest(<EOL>'<STR_LIT>' % dict(form.errors)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>logger.warn(<EOL>'<STR_LIT>',<EOL>request.path,<EOL>dict(form.errors)<EOL>)<EOL>return func(request, *args, **kwargs)<EOL><DEDENT><DEDENT>for (field_name, field_instance) in fields.items():<EOL><INDENT>if isinstance(field_instance, models.Model):<EOL><INDENT>field_type = type(field_instance)<EOL>field_id = '<STR_LIT>' % field_name<EOL>if field_id not in request.REQUEST:<EOL><INDENT>return JsonResponseBadRequest(<EOL>'<STR_LIT>' % field_name<EOL>)<EOL><DEDENT>field_pk = int(request.REQUEST[field_id])<EOL>try:<EOL><INDENT>field_value = field_type.objects.get(pk=field_pk)<EOL><DEDENT>except field_type.DoesNotExist:<EOL><INDENT>return JsonResponseNotFound(<EOL>'<STR_LIT>' % (<EOL>field_type, field_pk<EOL>)<EOL>)<EOL><DEDENT>form.cleaned_data[field_name] = field_value<EOL><DEDENT><DEDENT>validated_request = ValidatedRequest(request, form)<EOL>return func(validated_request, *args, **kwargs)<EOL><DEDENT>return wrapped_func<EOL><DEDENT>return decorator<EOL>

Define the accept schema of an API (GET or POST).

'fields' is a dict of Django form fields keyed by field name that specifies
the form-urlencoded fields that the API accepts*.

The view function is then called with GET/POST data that has been cleaned
by the Django form.

In debug and test modes, failure to validate the fields will result in a
400 Bad Request response.
In production mode, failure to validate will just log a
warning, unless overwritten by a 'strict' setting.

For example:

@api_accepts({
    'x': forms.IntegerField(min_value=0),
    'y': forms.IntegerField(min_value=0),
})
def add(request, *args, **kwargs):
    x = request.POST['x']
    y = request.POST['y']

    # x and y are integers already.
    return HttpResponse('%d' % (x + y))

*: 'fields' can also include Django models as {'key': Model()}. If present,
api_accepts will look for the field keyed by '<key>-id'
and pick the object that has that primary key. For example, if the entry is
{'course': Course()}, it will search for the key course_id='course-id' in
the request object, and find the object Course.objects.get(pk=course_id)


def decorator(func):<EOL><INDENT>@wraps(func)<EOL>def wrapped_func(request, *args, **kwargs):<EOL><INDENT>return_value = func(request, *args, **kwargs)<EOL>if not isinstance(return_value, JsonResponse):<EOL><INDENT>if settings.DEBUG:<EOL><INDENT>return JsonResponseBadRequest('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>logger.warn('<STR_LIT>')<EOL><DEDENT><DEDENT>accepted_return_codes = return_values.keys()<EOL>accepted_return_codes.append(<NUM_LIT>)<EOL>if return_value.status_code not in accepted_return_codes:<EOL><INDENT>if settings.DEBUG:<EOL><INDENT>return JsonResponseBadRequest(<EOL>'<STR_LIT>' %<EOL>(return_value.status_code, accepted_return_codes)<EOL>)<EOL><DEDENT>else:<EOL><INDENT>logger.warn(<EOL>'<STR_LIT>',<EOL>return_value.status_code,<EOL>accepted_return_codes,<EOL>)<EOL><DEDENT><DEDENT>return return_value<EOL><DEDENT>return wrapped_func<EOL><DEDENT>return decorator<EOL>

Define the return schema of an API.

'return_values' is a dictionary mapping
HTTP return code => documentation
In addition to validating that the status code of the response belongs to
one of the accepted status codes, it also validates that the returned
object is JSON (derived from JsonResponse)

In debug and test modes, failure to validate the fields will result in a
400 Bad Request response.
In production mode, failure to validate will just log a
warning, unless overwritten by a 'strict' setting.

For example:

@api_returns({
    200: 'Operation successful',
    403: 'User does not have persion',
    404: 'Resource not found',
    404: 'User not found',
})
def add(request, *args, **kwargs):
    if not request.user.is_superuser:
        return JsonResponseForbidden()  # 403

    return HttpResponse()  # 200


def decorator(func):<EOL><INDENT>@wraps(func)<EOL>def wrapped_func(request, *args, **kwargs):<EOL><INDENT>@api_accepts(accept_return_dict['<STR_LIT>'])<EOL>@api_returns(accept_return_dict['<STR_LIT>'])<EOL>def apid_fnc(request, *args, **kwargs):<EOL><INDENT>return func(request, *args, **kwargs)<EOL><DEDENT>return apid_fnc(request, *args, **kwargs)<EOL><DEDENT>return wrapped_func<EOL><DEDENT>return decorator<EOL>

Wrapper that calls @api_accepts and @api_returns in sequence.
For example:

@api({
    'accepts': {
        'x': forms.IntegerField(min_value=0),
        'y': forms.IntegerField(min_value=0),
    },
    'returns': [
        200: 'Operation successful',
        403: 'User does not have persion',
        404: 'Resource not found',
        404: 'User not found',
    ]
})
def add(request, *args, **kwargs):
    if not request.GET['x'] == 10:
        return JsonResponseForbidden()  # 403

    return HttpResponse()  # 200


def decorator(func):<EOL><INDENT>@wraps(func)<EOL>def wrapped_func(request, *args, **kwargs):<EOL><INDENT>try:<EOL><INDENT>request_dict = json.loads(request.raw_post_data)<EOL><DEDENT>except ValueError as e:<EOL><INDENT>return JsonResponseBadRequest('<STR_LIT>' % e)<EOL><DEDENT>for k in required_fields:<EOL><INDENT>if k not in request_dict:<EOL><INDENT>return JsonResponseBadRequest(<EOL>'<STR_LIT>' % k)<EOL><DEDENT><DEDENT>return func(request, request_dict, *args, **kwargs)<EOL><DEDENT>return wrapped_func<EOL><DEDENT>return decorator<EOL>

Return a decorator that ensures that the request passed to the view
function/method has a valid JSON request body with the given required
fields.  The dict parsed from the JSON is then passed as the second
argument to the decorated function/method.  For example:

@json_request({'name', 'date'})
def view_func(request, request_dict):
    ...


if isinstance(obj, models.Model):<EOL><INDENT>return self.encode(model_to_dict(obj))<EOL><DEDENT>elif isinstance(obj, models.query.QuerySet):<EOL><INDENT>return serializers.serialize('<STR_LIT>', obj)<EOL><DEDENT>else:<EOL><INDENT>return super(JsonResponseEncoder, self).default(obj)<EOL><DEDENT>

Convert QuerySet objects to their list counter-parts


def __init__(self, id = "<STR_LIT>", name = "<STR_LIT>", website = "<STR_LIT>", price_btc = "<STR_LIT>", volume_btc = "<STR_LIT>"):

self.id = id<EOL>self.name = name<EOL>self.website = website<EOL>self.price_btc = price_btc<EOL>self.volume_btc = volume_btc<EOL>


return "<STR_LIT>"<EOL>


return "<STR_LIT>" + self.id + '<STR_LIT:/>' + self.name + "<STR_LIT>" + self.price_btc<EOL>


return "<STR_LIT>"<EOL>

The typ representation of a TradingPair.


return "<STR_LIT>" + self.id + "<STR_LIT>" + self.price<EOL>

The string representation of a TradingPair.


url = self.API_PATH + '<STR_LIT>'<EOL>json_data = json.loads(self._getdata(url))<EOL>coins = []<EOL>for entry in json_data:<EOL><INDENT>coin = Coin()<EOL>coin.id = entry['<STR_LIT:id>']<EOL>coin.name = entry['<STR_LIT:name>']<EOL>coin.website = entry['<STR_LIT>']<EOL>coin.price_btc = entry['<STR_LIT>']<EOL>coin.volume_btc = entry['<STR_LIT>']<EOL>coins.append(coin)<EOL><DEDENT>return coins<EOL>

Use this function to list all coins with their data which are available on cryptocoincharts.
Usage: http://api.cryptocoincharts.info/listCoins


url = self.API_PATH + '<STR_LIT>' + pair<EOL>json_data = json.loads(self._getdata(url))<EOL>tradingpair = TradingPair()<EOL>tradingpair.id = json_data['<STR_LIT:id>']<EOL>tradingpair.price = json_data['<STR_LIT>']<EOL>tradingpair.price_before_24h = json_data['<STR_LIT>']<EOL>tradingpair.volume_first = json_data['<STR_LIT>']<EOL>tradingpair.volume_second = json_data['<STR_LIT>']<EOL>tradingpair.volume_btc = json_data['<STR_LIT>']<EOL>tradingpair.best_market = json_data['<STR_LIT>']<EOL>tradingpair.latest_trade = json_data['<STR_LIT>']<EOL>return tradingpair<EOL>

Use this function to query price and volume data for ONE trading pair.
A list with all coin currencies can be found by using the listcoins method.
A example pair: currency1_currency2 = "doge_btc"
Usage: http://api.cryptocoincharts.info/tradingPair/[currency1_currency2]


url = self.API_PATH + '<STR_LIT>'<EOL>data = { '<STR_LIT>':pairs }<EOL>json_data = json.loads(self._getdata(url, data))<EOL>tradingpairs = []<EOL>for entry in json_data:<EOL><INDENT>tradingpair = TradingPair()<EOL>tradingpair.id = entry['<STR_LIT:id>']<EOL>tradingpair.price = entry['<STR_LIT>']<EOL>tradingpair.price_before_24h = entry['<STR_LIT>']<EOL>tradingpair.volume_first = entry['<STR_LIT>']<EOL>tradingpair.volume_second = entry['<STR_LIT>']<EOL>tradingpair.volume_btc = entry['<STR_LIT>']<EOL>tradingpair.best_market = entry['<STR_LIT>']<EOL>tradingpair.latest_trade = entry['<STR_LIT>']<EOL>tradingpairs.append(tradingpair)<EOL><DEDENT>return tradingpairs<EOL>

Use this function to query price and volume data for MANY trading pairs.
Usage: http://api.cryptocoincharts.info/tradingPairs/[currency1_currency2,currency2_currency3,...]
       A example pair: currency1_currency2 = "doge_btc"
                       currency2_currency3 = "btc_eur"
       http://api.cryptocoincharts.info/tradingPairs/"doge_btc,btc_eur"


def _getdata(self, url, data = "<STR_LIT>"):

request = Request(url)<EOL>if data != "<STR_LIT>":<EOL><INDENT>request = Request(url, urlencode(data))<EOL><DEDENT>try:<EOL><INDENT>response = urlopen(request)<EOL><DEDENT>except HTTPError as e:<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>', e.code)<EOL><DEDENT>except URLError as e:<EOL><INDENT>print('<STR_LIT>')<EOL>print('<STR_LIT>', e.code)<EOL><DEDENT>else:<EOL><INDENT>return response.read()<EOL><DEDENT>


def reasonable_desired_version(self, desired_version, allow_equal=False,<EOL>allow_patch_skip=False):

try:<EOL><INDENT>desired_version = desired_version.base_version<EOL><DEDENT>except:<EOL><INDENT>pass<EOL><DEDENT>(new_major, new_minor, new_patch) =map(int, desired_version.split('<STR_LIT:.>'))<EOL>tag_versions = self._versions_from_tags()<EOL>if not tag_versions:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>max_version = max(self._versions_from_tags()).base_version<EOL>(old_major, old_minor, old_patch) =map(int, str(max_version).split('<STR_LIT:.>'))<EOL>update_str = str(max_version) + "<STR_LIT>" + str(desired_version)<EOL>v_desired = vers.Version(desired_version)<EOL>v_max = vers.Version(max_version)<EOL>if allow_equal and v_desired == v_max:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>if v_desired < v_max:<EOL><INDENT>return ("<STR_LIT>"<EOL>+ update_str + "<STR_LIT:\n>")<EOL><DEDENT>bad_update = skipped_version((old_major, old_minor, old_patch),<EOL>(new_major, new_minor, new_patch),<EOL>allow_patch_skip)<EOL>msg = "<STR_LIT>"<EOL>if bad_update:<EOL><INDENT>msg = ("<STR_LIT>"<EOL>+ update_str + "<STR_LIT>")<EOL><DEDENT>return msg<EOL>

Determine whether the desired version is a reasonable next version.

Parameters
----------
desired_version: str
    the proposed next version name


def consistency(self, desired_version=None, include_package=False,<EOL>strictness=None):

keys_to_check = list(self.versions.keys())<EOL>if not include_package and '<STR_LIT>' in keys_to_check:<EOL><INDENT>keys_to_check.remove('<STR_LIT>')<EOL><DEDENT>if desired_version is None:<EOL><INDENT>try:<EOL><INDENT>desired_version = self.versions['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>desired_version = self.versions[keys_to_check[<NUM_LIT:0>]]<EOL><DEDENT><DEDENT>if strictness is None:<EOL><INDENT>strictness = self.strictness<EOL><DEDENT>desired = self._version(desired_version, strictness)<EOL>error_keys = []<EOL>for key in keys_to_check:<EOL><INDENT>test = self._version(self.versions[key], strictness)<EOL>if test != desired:<EOL><INDENT>error_keys += [key]<EOL><DEDENT><DEDENT>msg = "<STR_LIT>"<EOL>for key in error_keys:<EOL><INDENT>msg += "<STR_LIT>".format(<EOL>d=str(desired),<EOL>v=str(self.versions[key]),<EOL>k=str(key)<EOL>)<EOL><DEDENT>return msg<EOL>

Checks that the versions are consistent

        Parameters
        ----------
        desired_version: str
            optional; the version that all of these should match
        include_package: bool
            whether to check the special 'package' version for consistency
            (default False)
        strictness: str


try:<EOL><INDENT>is_release = setup.IS_RELEASE<EOL><DEDENT>except AttributeError:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>if is_release and expected:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>elif not is_release and not expected:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return ("<STR_LIT>"<EOL>+ str(is_release) + "<STR_LIT>")<EOL><DEDENT><DEDENT>

Returns
-------
bool or None :
    None if we can't tell


pass<EOL>

Checks that the requirements defined in setup.py, requirements.txt, and
(optionally) the conda recipe's meta.yaml file are all in agreement.
Includes version checks (for pins) on requirements.txt and the conda
recipe.


if os.path.isfile("<STR_LIT>"):<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>"<EOL><DEDENT>

Checks that the README.rst file exists.

This file should be read in as the long description in setup.py.


def __call__(self, method, *args, **kwargs):

self.output.write(str(method.__name__) + "<STR_LIT>")<EOL>msg = method(*args, **kwargs)<EOL>fail = <NUM_LIT:0><EOL>if bool(msg):<EOL><INDENT>fail = <NUM_LIT:1><EOL>self.output.write("<STR_LIT>")<EOL>self.output.write(self.wrapper.fill(msg) + '<STR_LIT:\n>')<EOL><DEDENT>else:<EOL><INDENT>self.output.write("<STR_LIT>")<EOL><DEDENT>return fail<EOL>

Generic method to turn other methods into tests.


<EOL>def _minimal_ext_cmd(cmd):<EOL><INDENT>env = {}<EOL>for k in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>v = os.environ.get(k)<EOL>if v is not None:<EOL><INDENT>env[k] = v<EOL><DEDENT><DEDENT>env['<STR_LIT>'] = '<STR_LIT:C>'<EOL>env['<STR_LIT>'] = '<STR_LIT:C>'<EOL>env['<STR_LIT>'] = '<STR_LIT:C>'<EOL>with open(os.devnull, '<STR_LIT:w>') as err_out:<EOL><INDENT>out = subprocess.Popen(cmd,<EOL>stdout=subprocess.PIPE,<EOL>stderr=err_out, <EOL>env=env).communicate()[<NUM_LIT:0>]<EOL><DEDENT>return out<EOL><DEDENT>try:<EOL><INDENT>git_dir = os.path.dirname(os.path.realpath(__file__))<EOL>out = _minimal_ext_cmd(['<STR_LIT>', '<STR_LIT>', git_dir, '<STR_LIT>', '<STR_LIT>'])<EOL>GIT_REVISION = out.strip().decode('<STR_LIT:ascii>')<EOL><DEDENT>except OSError:<EOL><INDENT>GIT_REVISION = '<STR_LIT>'<EOL><DEDENT>return GIT_REVISION<EOL>

Return the git hash as a string.

Apparently someone got this from numpy's setup.py. It has since been
modified a few times.


def oauth2_url(self, redirect_uri: str, scope: Optional[str] = None, state: Optional[str] = None) -> str:

return OAuth2.url_(self.http.client_id, redirect_uri, scope=scope, state=state)<EOL>

Generate an outh2 url for user authentication.

        Parameters
        ----------
        redirect_uri : str
            Where spotify should redirect the user to after authentication.
        scope : Optional[str]
            Space seperated spotify scopes for different levels of access.
        state : Optional[str]
            Using a state value can increase your assurance that an incoming connection is the result of an authentication request.

        Returns
        -------
        url : str
            The OAuth2 url.


await self.http.close()<EOL>

Close the underlying HTTP session to Spotify.


async def user_from_token(self, token: str) -> User:

return await User.from_token(self, token)<EOL>

Create a user session from a token.

        This code is equivelent to `User.from_token(client, token)`

        Parameters
        ----------
        token : str
            The token to attatch the user session to.

        Returns
        -------
        user : User
            The user from the ID


async def get_album(self, spotify_id: str, *, market: str = '<STR_LIT>') -> Album:

data = await self.http.album(to_id(spotify_id), market=market)<EOL>return Album(self, data)<EOL>

Retrive an album with a spotify ID.

        Parameters
        ----------
        spotify_id : str
            The ID to search for.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code

        Returns
        -------
        album : Album
            The album from the ID


async def get_artist(self, spotify_id: str) -> Artist:

data = await self.http.artist(to_id(spotify_id))<EOL>return Artist(self, data)<EOL>

Retrive an artist with a spotify ID.

        Parameters
        ----------
        spotify_id : str
            The ID to search for.

        Returns
        -------
        artist : Artist
            The artist from the ID


async def get_track(self, spotify_id: str) -> Track:

data = await self.http.track(to_id(spotify_id))<EOL>return Track(self, data)<EOL>

Retrive an track with a spotify ID.

        Parameters
        ----------
        spotify_id : str
            The ID to search for.

        Returns
        -------
        track : Track
            The track from the ID


async def get_user(self, spotify_id: str) -> User:

data = await self.http.user(to_id(spotify_id))<EOL>return User(self, data)<EOL>

Retrive an user with a spotify ID.

        Parameters
        ----------
        spotify_id : str
            The ID to search for.

        Returns
        -------
        user : User
            The user from the ID


async def get_albums(self, *ids: List[str], market: str = '<STR_LIT>') -> List[Album]:

data = await self.http.albums('<STR_LIT:U+002C>'.join(to_id(_id) for _id in ids), market=market)<EOL>return list(Album(self, album) for album in data['<STR_LIT>'])<EOL>

Retrive multiple albums with a list of spotify IDs.

        Parameters
        ----------
        ids : List[str]
            the ID to look for
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code

        Returns
        -------
        albums : List[Album]
            The albums from the IDs


async def get_artists(self, *ids: List[str]) -> List[Artist]:

data = await self.http.artists('<STR_LIT:U+002C>'.join(to_id(_id) for _id in ids))<EOL>return list(Artist(self, artist) for artist in data['<STR_LIT>'])<EOL>

Retrive multiple artists with a list of spotify IDs.

        Parameters
        ----------
        ids : List[str]
            the IDs to look for

        Returns
        -------
        artists : List[Artist]
            The artists from the IDs


async def search(self, q: str, *, types: Optional[Iterable[str]] = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'], limit: Optional[int] = <NUM_LIT:20>, offset: Optional[int] = <NUM_LIT:0>, market: Optional[str] = None) -> Dict[str, List[Union[Track, Playlist, Artist, Album]]]:

if not hasattr(types, '<STR_LIT>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>elif not isinstance(types, list):<EOL><INDENT>types = list(item for item in types)<EOL><DEDENT>types_ = set(types)<EOL>if not types_.issubset(_SEARCH_TYPES):<EOL><INDENT>raise ValueError(_SEARCH_TYPE_ERR % types_.difference(_SEARCH_TYPES).pop())<EOL><DEDENT>kwargs = {<EOL>'<STR_LIT:q>': q.replace('<STR_LIT:U+0020>', '<STR_LIT:+>'),<EOL>'<STR_LIT>': '<STR_LIT:U+002C>'.join(tp.strip() for tp in types),<EOL>'<STR_LIT>': market,<EOL>'<STR_LIT>': limit,<EOL>'<STR_LIT>': offset<EOL>}<EOL>data = await self.http.search(**kwargs)<EOL>return {key: [_TYPES[obj['<STR_LIT:type>']](self, obj) for obj in value['<STR_LIT>']] for key, value in data.items()}<EOL>

Access the spotify search functionality.

        Parameters
        ----------
        q : str
            the search query
        types : Optional[Iterable[str]]
            A sequence of search types (can be any of `track`, `playlist`, `artist` or `album`) to refine the search request.
            A `ValueError` may be raised if a search type is found that is not valid.
        limit : Optional[int]
            The limit of search results to return when searching.
            Maximum limit is 50, any larger may raise a :class:`HTTPException`
        offset : Optional[int]
            The offset from where the api should start from in the search results.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.

        Returns
        -------
        results : Dict[str, List[Union[Track, Playlist, Artist, Album]]]
            The results of the search.


async def get_tracks(self, *, limit: Optional[int] = <NUM_LIT:20>, offset: Optional[int] = <NUM_LIT:0>) -> List[Track]:

data = await self.__client.http.album_tracks(self.id, limit=limit, offset=offset)<EOL>return list(Track(self.__client, item) for item in data['<STR_LIT>'])<EOL>

get the albums tracks from spotify.

        Parameters
        ----------
        limit : Optional[int]
            The limit on how many tracks to retrieve for this album (default is 20).
        offset : Optional[int]
            The offset from where the api should start from in the tracks.

        Returns
        -------
        tracks : List[Track]
            The tracks of the artist.


async def get_all_tracks(self, *, market: Optional[str] = '<STR_LIT>') -> List[Track]:

tracks = []<EOL>offset = <NUM_LIT:0><EOL>total = self.total_tracks or None<EOL>while True:<EOL><INDENT>data = await self.__client.http.album_tracks(self.id, limit=<NUM_LIT:50>, offset=offset, market=market)<EOL>if total is None:<EOL><INDENT>total = data['<STR_LIT>']<EOL><DEDENT>offset += <NUM_LIT:50><EOL>tracks += list(Track(self.__client, item) for item in data['<STR_LIT>'])<EOL>if len(tracks) >= total:<EOL><INDENT>break<EOL><DEDENT><DEDENT>return tracks<EOL>

loads all of the albums tracks, depending on how many the album has this may be a long operation.

        Parameters
        ----------
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code. Provide this parameter if you want to apply Track Relinking.

        Returns
        -------
        tracks : List[Track]
            The tracks of the artist.


async def contains_albums(self, *albums: Sequence[Union[str, Album]]) -> List[bool]:

_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]<EOL>return await self.user.http.is_saved_album(_albums)<EOL>

Check if one or more albums is already saved in the current Spotify user’s ‘Your Music’ library.

        Parameters
        ----------
        albums : Union[Album, str]
            A sequence of artist objects or spotify IDs


async def contains_tracks(self, *tracks: Sequence[Union[str, Track]]) -> List[bool]:

_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]<EOL>return await self.user.http.is_saved_track(_tracks)<EOL>

Check if one or more tracks is already saved in the current Spotify user’s ‘Your Music’ library.

        Parameters
        ----------
        tracks : Union[Track, str]
            A sequence of track objects or spotify IDs


async def get_tracks(self, *, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>) -> List[Track]:

data = await self.user.http.saved_tracks(limit=limit, offset=offset)<EOL>return [Track(self.__client, item['<STR_LIT>']) for item in data['<STR_LIT>']]<EOL>

Get a list of the songs saved in the current Spotify user’s ‘Your Music’ library.

        Parameters
        ----------
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first item to return. Default: 0


async def get_albums(self, *, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>) -> List[Album]:

data = await self.user.http.saved_albums(limit=limit, offset=offset)<EOL>return [Album(self.__client, item['<STR_LIT>']) for item in data['<STR_LIT>']]<EOL>

Get a list of the albums saved in the current Spotify user’s ‘Your Music’ library.

        Parameters
        ----------
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first item to return. Default: 0


_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]<EOL>await self.user.http.delete_saved_albums('<STR_LIT:U+002C>'.join(_albums))<EOL>

Remove one or more albums from the current user’s ‘Your Music’ library.

        Parameters
        ----------
        albums : Sequence[Union[Album, str]]
            A sequence of artist objects or spotify IDs


_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]<EOL>await self.user.http.delete_saved_tracks('<STR_LIT:U+002C>'.join(_tracks))<EOL>

Remove one or more tracks from the current user’s ‘Your Music’ library.

        Parameters
        ----------
        tracks : Sequence[Union[Track, str]]
            A sequence of track objects or spotify IDs


_albums = [(obj if isinstance(obj, str) else obj.id) for obj in albums]<EOL>await self.user.http.save_albums('<STR_LIT:U+002C>'.join(_albums))<EOL>

Save one or more albums to the current user’s ‘Your Music’ library.

        Parameters
        ----------
        albums : Sequence[Union[Album, str]]
            A sequence of artist objects or spotify IDs


_tracks = [(obj if isinstance(obj, str) else obj.id) for obj in tracks]<EOL>await self.user.http.save_tracks('<STR_LIT:U+002C>'.join(_tracks))<EOL>

Save one or more tracks to the current user’s ‘Your Music’ library.

        Parameters
        ----------
        tracks : Sequence[Union[Track, str]]
            A sequence of track objects or spotify IDs


return self.__client.http.track_audio_analysis(self.id)<EOL>

Get a detailed audio analysis for the track.


return self.__client.http.track_audio_features(self.id)<EOL>

Get audio feature information for the track.


async def pause(self, *, device: Optional[SomeDevice] = None):

await self._user.http.pause_playback(device_id=str(device))<EOL>

Pause playback on the user’s account.

        Parameters
        ----------
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def resume(self, *, device: Optional[SomeDevice] = None):

await self._user.http.play_playback(None, device_id=str(device))<EOL>

Resume playback on the user's account.

        Parameters
        ----------
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def seek(self, pos, *, device: Optional[SomeDevice] = None):

await self._user.http.seek_playback(pos, device_id=str(device))<EOL>

Seeks to the given position in the user’s currently playing track.

        Parameters
        ----------
        pos : int
            The position in milliseconds to seek to.
            Must be a positive number.
            Passing in a position that is greater than the length of the track will cause the player to start playing the next song.
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def set_repeat(self, state, *, device: Optional[SomeDevice] = None):

await self._user.http.repeat_playback(state, device_id=str(device))<EOL>

Set the repeat mode for the user’s playback.

        Parameters
        ----------
        state : str
            Options are repeat-track, repeat-context, and off
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def set_volume(self, volume: int, *, device: Optional[SomeDevice] = None):

await self._user.http.set_playback_volume(volume, device_id=str(device))<EOL>

Set the volume for the user’s current playback device.

        Parameters
        ----------
        volume : int
            The volume to set. Must be a value from 0 to 100 inclusive.
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def next(self, *, device: Optional[SomeDevice] = None):

await self._user.http.skip_next(device_id=str(device))<EOL>

Skips to next track in the user’s queue.

        Parameters
        ----------
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def previous(self, *, device: Optional[SomeDevice] = None):

return await self._user.http.skip_previous(device_id=str(device))<EOL>

Skips to previous track in the user’s queue.

        Note that this will ALWAYS skip to the previous track, regardless of the current track’s progress.
        Returning to the start of the current track should be performed using :meth:`seek`

        Parameters
        ----------
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def play(self, *uris: SomeURIs, offset: Optional[Offset] = <NUM_LIT:0>, device: Optional[SomeDevice] = None):

if len(uris) > <NUM_LIT:1>:<EOL><INDENT>context_uri = list(str(uri) for uri in uris)<EOL><DEDENT>else:<EOL><INDENT>context_uri = str(uris[<NUM_LIT:0>])<EOL><DEDENT>if device is not None:<EOL><INDENT>if not isinstance(device, (Device, str)):<EOL><INDENT>raise TypeError('<STR_LIT>'.format(device))<EOL><DEDENT>else:<EOL><INDENT>device = device.id<EOL><DEDENT><DEDENT>await self._user.http.play_playback(context_uri, offset=offset, device_id=device)<EOL>

Start a new context or resume current playback on the user’s active device.

        The method treats a single argument as a Spotify context, such as a Artist, Album and playlist objects/URI.
        When called with multiple positional arguments they are interpreted as a array of Spotify Track objects/URIs.

        Parameters
        ----------
        *uris : :obj:`SomeURIs`
            When a single argument is passed in that argument is treated as a context.
            Valid contexts are: albums, artists, playlists.
            Album, Artist and Playlist objects are accepted too.
            Otherwise when multiple arguments are passed in they,
            A sequence of Spotify Tracks or Track URIs to play.
        offset : Optional[:obj:`Offset`]
            Indicates from where in the context playback should start.
            Only available when `context` corresponds to an album or playlist object,
            or when the `uris` parameter is used. when an integer offset is zero based and can’t be negative.
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def shuffle(self, state: Optional[bool] = None, *, device: Optional[SomeDevice] = None):

await self.__user.http.shuffle_playback(state)<EOL>

shuffle on or off for user’s playback.

        Parameters
        ----------
        state : Optional[bool]
            if `True` then Shuffle user’s playback.
            else if `False` do not shuffle user’s playback.
        device : Optional[:obj:`SomeDevice`]
            The Device object or id of the device this command is targeting.
            If not supplied, the user’s currently active device is the target.


async def transfer(self, device: SomeDevice, ensure_playback: bool = False):

await self._user.http.transfer_player(str(device), play=ensure_playback)<EOL>

Transfer playback to a new device and determine if it should start playing.

        Parameters
        ----------
        device : :obj:`SomeDevice`
            The device on which playback should be started/transferred.
        ensure_playback : bool
            if `True` ensure playback happens on new device.
            else keep the current playback state.


data = await self.__func()<EOL>return list(PlaylistTrack(self.__client, track) for track in data['<STR_LIT>'])<EOL>

get the track object for each link in the partial tracks data

        Returns
        -------
        tracks : List[Track]
            The tracks


async def get_all_tracks(self) -> List[PlaylistTrack]:

if isinstance(self._tracks, PartialTracks):<EOL><INDENT>return await self._tracks.build()<EOL><DEDENT>_tracks = []<EOL>offset = <NUM_LIT:0><EOL>while len(self.tracks) < self.total_tracks:<EOL><INDENT>data = await self.__client.http.get_playlist_tracks(self.owner.id, self.id, limit=<NUM_LIT:50>, offset=offset)<EOL>_tracks += [PlaylistTrack(self.__client, item) for item in data['<STR_LIT>']]<EOL>offset += <NUM_LIT:50><EOL><DEDENT>self.total_tracks = len(self._tracks)<EOL>return list(self._tracks)<EOL>

Get all playlist tracks from the playlist.

        Returns
        -------
        tracks : List[PlaylistTrack]
            The playlists tracks.


if not hasattr(self, '<STR_LIT>'):<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>elif hasattr(self, '<STR_LIT:http>'):<EOL><INDENT>return await self.http.request(('<STR_LIT:GET>', self.href))<EOL><DEDENT>else:<EOL><INDENT>cls = type(self)<EOL><DEDENT>try:<EOL><INDENT>client = getattr(self, '<STR_LIT>'.format(cls.__name__))<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise TypeError('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>http = client.http<EOL><DEDENT>data = await http.request(('<STR_LIT:GET>', self.href))<EOL>return cls(client, data)<EOL>

Get the full object from spotify with a `href` attribute.


@ensure_http<EOL><INDENT>async def currently_playing(self) -> Tuple[Context, Track]:<DEDENT>

data = await self.http.currently_playing()<EOL>if data.get('<STR_LIT>'):<EOL><INDENT>data['<STR_LIT>'] = Context(data.get('<STR_LIT>'))<EOL>data['<STR_LIT>'] = Track(self.__client, data.get('<STR_LIT>'))<EOL><DEDENT>return data<EOL>

Get the users currently playing track.

        Returns
        -------
        context, track : Tuple[Context, Track]
            A tuple of the context and track.


@ensure_http<EOL><INDENT>async def get_player(self) -> Player:<DEDENT>

self._player = player = Player(self.__client, self, await self.http.current_player())<EOL>return player<EOL>

Get information about the users current playback.

        Returns
        -------
        player : Player
            A player object representing the current playback.


@ensure_http<EOL><INDENT>async def get_devices(self) -> List[Device]:<DEDENT>

data = await self.http.available_devices()<EOL>return [Device(item) for item in data['<STR_LIT>']]<EOL>

Get information about the users avaliable devices.

        Returns
        -------
        devices : List[Device]
            The devices the user has available.


@ensure_http<EOL><INDENT>async def recently_played(self) -> List[Dict[str, Union[Track, Context, str]]]:<DEDENT>

data = await self.http.recently_played()<EOL>f = lambda data: {'<STR_LIT>': Context(data.get('<STR_LIT>')), '<STR_LIT>': Track(self.__client, data.get('<STR_LIT>'))}<EOL>return [{'<STR_LIT>': track['<STR_LIT>'], **f(track)} for track in data['<STR_LIT>']]<EOL>

Get tracks from the current users recently played tracks.

        Returns
        -------
        playlist_history : List[Dict[str, Union[Track, Context, str]]]
            A list of playlist history object.
            Each object is a dict with a timestamp, track and context field.


async def add_tracks(self, playlist: Union[str, Playlist], *tracks) -> str:

tracks = [str(track) for track in tracks]<EOL>data = await self.http.add_playlist_tracks(self.id, str(playlist), tracks='<STR_LIT:U+002C>'.join(tracks))<EOL>return data['<STR_LIT>']<EOL>

Add one or more tracks to a user’s playlist.

        Parameters
        ----------
        playlist : Union[str, Playlist]
            The playlist to modify
        tracks : Sequence[Union[str, Track]]
            Tracks to add to the playlistv

        Returns
        -------
        snapshot_id : str
            The snapshot id of the playlist.


async def replace_tracks(self, playlist, *tracks) -> str:

tracks = [str(track) for track in tracks]<EOL>await self.http.replace_playlist_tracks(self.id, str(playlist), tracks='<STR_LIT:U+002C>'.join(tracks))<EOL>

Replace all the tracks in a playlist, overwriting its existing tracks.
        This powerful request can be useful for replacing tracks, re-ordering existing tracks, or clearing the playlist.

        Parameters
        ----------
        playlist : Union[str, PLaylist]
            The playlist to modify
        tracks : Sequence[Union[str, Track]]
            Tracks to place in the playlist


async def remove_tracks(self, playlist, *tracks):

tracks = [str(track) for track in tracks]<EOL>data = await self.http.remove_playlist_tracks(self.id, str(playlist), tracks='<STR_LIT:U+002C>'.join(tracks))<EOL>return data['<STR_LIT>']<EOL>

Remove one or more tracks from a user’s playlist.

        Parameters
        ----------
        playlist : Union[str, Playlist]
            The playlist to modify
        tracks : Sequence[Union[str, Track]]
            Tracks to remove from the playlist

        Returns
        -------
        snapshot_id : str
            The snapshot id of the playlist.


async def reorder_tracks(self, playlist, start, insert_before, length=<NUM_LIT:1>, *, snapshot_id=None):

data = await self.http.reorder_playlists_tracks(self.id, str(playlist), start, length, insert_before, snapshot_id=snapshot_id)<EOL>return data['<STR_LIT>']<EOL>

Reorder a track or a group of tracks in a playlist.

        Parameters
        ----------
        playlist : Union[str, Playlist]
            The playlist to modify
        start : int
            The position of the first track to be reordered.
        insert_before : int
            The position where the tracks should be inserted.
        length : Optional[int]
            The amount of tracks to be reordered. Defaults to 1 if not set.
        snapshot_id : str
            The playlist’s snapshot ID against which you want to make the changes.

        Returns
        -------
        snapshot_id : str
            The snapshot id of the playlist.


@ensure_http<EOL><INDENT>async def edit_playlist(self, playlist, *, name=None, public=None, collaborative=None, description=None):<DEDENT>

data = {}<EOL>if name:<EOL><INDENT>data['<STR_LIT:name>'] = name<EOL><DEDENT>if public:<EOL><INDENT>data['<STR_LIT>'] = public<EOL><DEDENT>if collaborative:<EOL><INDENT>data['<STR_LIT>'] = collaborative<EOL><DEDENT>if description:<EOL><INDENT>data['<STR_LIT:description>'] = description<EOL><DEDENT>await self.http.change_playlist_details(self.id, str(playlist), data)<EOL>

Change a playlist’s name and public/private, collaborative state and description.

        Parameters
        ----------
        playlist : Union[str, Playlist]
            The playlist to modify
        name : Optional[str]
            The new name of the playlist.
        public : Optional[bool]
            The public/private status of the playlist.
            `True` for public, `False` for private.
        collaborative : Optional[bool]
            If `True`, the playlist will become collaborative and other users will be able to modify the playlist.
        description : Optional[str]
            The new playlist description


@ensure_http<EOL><INDENT>async def create_playlist(self, name, *, public=True, collaborative=False, description=None):<DEDENT>

data = {<EOL>'<STR_LIT:name>': name,<EOL>'<STR_LIT>': public,<EOL>'<STR_LIT>': collaborative<EOL>}<EOL>if description:<EOL><INDENT>data['<STR_LIT:description>'] = description<EOL><DEDENT>playlist_data = await self.http.create_playlist(self.id, data)<EOL>return Playlist(self.__client, playlist_data)<EOL>

Create a playlist for a Spotify user.

        Parameters
        ----------
        name : str
            The name of the playlist.
        public : Optional[bool]
            The public/private status of the playlist.
            `True` for public, `False` for private.
        collaborative : Optional[bool]
            If `True`, the playlist will become collaborative and other users will be able to modify the playlist.
        description : Optional[str]
            The playlist description

        Returns
        -------
        playlist : Playlist
            The playlist that was created.


async def get_playlists(self, *, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>):

if hasattr(self, '<STR_LIT:http>'):<EOL><INDENT>http = self.http<EOL><DEDENT>else:<EOL><INDENT>http = self.__client.http<EOL><DEDENT>data = await http.get_playlists(self.id, limit=limit, offset=offset)<EOL>return [Playlist(self.__client, playlist_data) for playlist_data in data['<STR_LIT>']]<EOL>

get the users playlists from spotify.

        Parameters
        ----------
         limit : Optional[int]
             The limit on how many playlists to retrieve for this user (default is 20).
         offset : Optional[int]
             The offset from where the api should start from in the playlists.

        Returns
        -------
        playlists : List[Playlist]
            A list of the users playlists.


async def top_artists(self, **data) -> List[Artist]:

return await self._get_top(Artist, data)<EOL>

Get the current user’s top artists based on calculated affinity.

        Parameters
        ----------
        limit : Optional[int]
            The number of entities to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first entity to return. Default: 0
        time_range : Optional[str]
            Over what time frame the affinities are computed. (long_term, short_term, medium_term)

        Returns
        -------
        tracks : List[Artist]
            The top artists for the user.


async def top_tracks(self, **data) -> List[Track]:

return await self._get_top(Track, data)<EOL>

Get the current user’s top tracks based on calculated affinity.

        Parameters
        ----------
        limit : Optional[int]
            The number of entities to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first entity to return. Default: 0
        time_range : Optional[str]
            Over what time frame the affinities are computed. (long_term, short_term, medium_term)

        Returns
        -------
        tracks : List[Track]
            The top tracks for the user.


async def get_albums(self, *, limit: Optional[int] = <NUM_LIT:20>, offset: Optional[int] = <NUM_LIT:0>, include_groups=None, market: Optional[str] = None) -> List[Album]:

from .album import Album<EOL>data = await self.__client.http.artist_albums(self.id, limit=limit, offset=offset, include_groups=include_groups, market=market)<EOL>return list(Album(self.__client, item) for item in data['<STR_LIT>'])<EOL>

Get the albums of a Spotify artist.

        Parameters
        ----------
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optiona[int]
            The offset of which Spotify should start yielding from.
        include_groups : INCLUDE_GROUPS_TP
            INCLUDE_GROUPS
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.

        Returns
        -------
        albums : List[Album]
            The albums of the artist.


async def get_all_albums(self, *, market='<STR_LIT>') -> List[Album]:

from .album import Album<EOL>albums = []<EOL>offset = <NUM_LIT:0><EOL>total = await self.total_albums(market=market)<EOL>while len(albums) < total:<EOL><INDENT>data = await self.__client.http.artist_albums(self.id, limit=<NUM_LIT:50>, offset=offset, market=market)<EOL>offset += <NUM_LIT:50><EOL>albums += list(Album(self.__client, item) for item in data['<STR_LIT>'])<EOL><DEDENT>return albums<EOL>

loads all of the artists albums, depending on how many the artist has this may be a long operation.

        Parameters
        ----------
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.

        Returns
        -------
        albums : List[Album]
            The albums of the artist.


async def total_albums(self, *, market: str = None) -> int:

data = await self.__client.http.artist_albums(self.id, limit=<NUM_LIT:1>, offset=<NUM_LIT:0>, market=market)<EOL>return data['<STR_LIT>']<EOL>

get the total amout of tracks in the album.

        Parameters
        ----------
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.

        Returns
        -------
        total : int
            The total amount of albums.


async def top_tracks(self, country: str = '<STR_LIT>') -> List[Track]:

from .track import Track<EOL>top = await self.__client.http.artist_top_tracks(self.id, country=country)<EOL>return list(Track(self.__client, item) for item in top['<STR_LIT>'])<EOL>

Get Spotify catalog information about an artist’s top tracks by country.

        Parameters
        ----------
        country : str
            The country to search for, it defaults to 'US'.

        Returns
        -------
        tracks : List[Track]
            The artists top tracks.


async def related_artists(self) -> List[Artist]:

related = await self.__client.http.artist_related_artists(self.id)<EOL>return list(Artist(self.__client, item) for item in related['<STR_LIT>'])<EOL>

Get Spotify catalog information about artists similar to a given artist.

        Similarity is based on analysis of the Spotify community’s listening history.

        Returns
        -------
        artists : List[Artits]
            The artists deemed similar.


if self.client_id is None:<EOL><INDENT>raise SpotifyException(_GET_BEARER_ERR % '<STR_LIT>')<EOL><DEDENT>elif self.client_secret is None:<EOL><INDENT>raise SpotifyException(_GET_BEARER_ERR % '<STR_LIT>')<EOL><DEDENT>token = b64encode('<STR_LIT::>'.join((self.client_id, self.client_secret)).encode())<EOL>kwargs = {<EOL>'<STR_LIT:url>': '<STR_LIT>',<EOL>'<STR_LIT:data>': {'<STR_LIT>': '<STR_LIT>'},<EOL>'<STR_LIT>': {'<STR_LIT>': '<STR_LIT>' + token.decode()}<EOL>}<EOL>async with self._session.post(**kwargs) as resp:<EOL><INDENT>return json.loads(await resp.text(encoding='<STR_LIT:utf-8>'))<EOL><DEDENT>

Get the application bearer token from client_id and client_secret.


async def request(self, route, **kwargs):

if isinstance(route, tuple):<EOL><INDENT>method, url = route<EOL><DEDENT>else:<EOL><INDENT>method = route.method<EOL>url = route.url<EOL><DEDENT>if self.bearer_info is None:<EOL><INDENT>self.bearer_info = bearer_info = await self.get_bearer_info()<EOL>access_token = bearer_info['<STR_LIT>']<EOL><DEDENT>else:<EOL><INDENT>access_token = self.bearer_info['<STR_LIT>']<EOL><DEDENT>headers = {<EOL>'<STR_LIT>': '<STR_LIT>' + access_token,<EOL>'<STR_LIT:Content-Type>': kwargs.get('<STR_LIT>', '<STR_LIT:application/json>'),<EOL>**kwargs.pop('<STR_LIT>', {})<EOL>}<EOL>for _ in range(self.RETRY_AMOUNT):<EOL><INDENT>r = await self._session.request(method, url, headers=headers, **kwargs)<EOL>try:<EOL><INDENT>status = r.status<EOL>try:<EOL><INDENT>data = json.loads(await r.text(encoding='<STR_LIT:utf-8>'))<EOL><DEDENT>except json.decoder.JSONDecodeError:<EOL><INDENT>data = {}<EOL><DEDENT>if <NUM_LIT> > status >= <NUM_LIT:200>:<EOL><INDENT>return data<EOL><DEDENT>if status == <NUM_LIT>:<EOL><INDENT>self.bearer_info = bearer_info = await self.get_bearer_info()<EOL>headers['<STR_LIT>'] = '<STR_LIT>' + bearer_info['<STR_LIT>']<EOL>continue<EOL><DEDENT>if status == <NUM_LIT>:<EOL><INDENT>amount = r.headers.get('<STR_LIT>')<EOL>await asyncio.sleep(int(amount), loop=self.loop)<EOL>continue<EOL><DEDENT>if status in (<NUM_LIT>, <NUM_LIT>):<EOL><INDENT>continue<EOL><DEDENT>if status == <NUM_LIT>:<EOL><INDENT>raise Forbidden(r, data)<EOL><DEDENT>elif status == <NUM_LIT>:<EOL><INDENT>raise NotFound(r, data)<EOL><DEDENT><DEDENT>finally:<EOL><INDENT>await r.release()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise HTTPException(r, data)<EOL><DEDENT>

Make a request to the spotify API with the current bearer credentials.

        Parameters
        ----------
        route : Union[tuple[str, str], Route]
            A tuple of the method and url or a :class:`Route` object.
        kwargs : Any
            keyword arguments to pass into :class:`aiohttp.ClientSession.request`


await self._session.close()<EOL>


def album(self, spotify_id, market='<STR_LIT>'):

route = Route('<STR_LIT:GET>', '<STR_LIT>', spotify_id=spotify_id)<EOL>payload = {}<EOL>if market:<EOL><INDENT>payload['<STR_LIT>'] = market<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get a spotify album by its ID.

        Parameters
        ----------
        spotify_id : str
            The spotify_id to search by.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.

        Returns
        -------
        album : Dict
            The album object.


def album_tracks(self, spotify_id, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>, market='<STR_LIT>'):

route = Route('<STR_LIT:GET>', '<STR_LIT>', spotify_id=spotify_id)<EOL>payload = {'<STR_LIT>': limit, '<STR_LIT>': offset}<EOL>if market:<EOL><INDENT>payload['<STR_LIT>'] = market<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get an albums tracks by an ID.

        Parameters
        ----------
        spotify_id : str
            The spotify_id to search by.
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optiona[int]
            The offset of which Spotify should start yielding from.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.


def albums(self, spotify_ids, market='<STR_LIT>'):

route = Route('<STR_LIT:GET>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': spotify_ids}<EOL>if market:<EOL><INDENT>payload['<STR_LIT>'] = market<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get a spotify album by its ID.

        Parameters
        ----------
        spotify_ids : List[str]
            The spotify_ids to search by.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.


route = Route('<STR_LIT:GET>', '<STR_LIT>', spotify_id=spotify_id)<EOL>return self.request(route)<EOL>

Get a spotify artist by their ID.

        Parameters
        ----------
        spotify_id : str
            The spotify_id to search by.


def artist_albums(self, spotify_id, include_groups=None, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>, market='<STR_LIT>'):

route = Route('<STR_LIT:GET>', '<STR_LIT>', spotify_id=spotify_id)<EOL>payload = {'<STR_LIT>': limit, '<STR_LIT>': offset}<EOL>if include_groups:<EOL><INDENT>payload['<STR_LIT>'] = include_groups<EOL><DEDENT>if market:<EOL><INDENT>payload['<STR_LIT>'] = market<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get an artists tracks by their ID.

        Parameters
        ----------
        spotify_id : str
            The spotify_id to search by.
        include_groups : INCLUDE_GROUPS_TP
            INCLUDE_GROUPS
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optiona[int]
            The offset of which Spotify should start yielding from.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.


def artist_top_tracks(self, spotify_id, country):

route = Route('<STR_LIT:GET>', '<STR_LIT>', spotify_id=spotify_id)<EOL>payload = {'<STR_LIT>': country}<EOL>return self.request(route, params=payload)<EOL>

Get an artists top tracks per country with their ID.

        Parameters
        ----------
        spotify_id : str
            The spotify_id to search by.
        country : COUNTRY_TP
            COUNTRY


Get related artists for an artist by their ID.

        Parameters
        ----------
        spotify_id : str
            The spotify_id to search by.


route = Route('<STR_LIT:GET>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': spotify_ids}<EOL>return self.request(route, params=payload)<EOL>

Get a spotify artists by their IDs.

        Parameters
        ----------
        spotify_id : List[str]
            The spotify_ids to search with.


def category(self, category_id, country=None, locale=None):

route = Route('<STR_LIT:GET>', '<STR_LIT>', category_id=category_id)<EOL>payload = {}<EOL>if country:<EOL><INDENT>payload['<STR_LIT>'] = country<EOL><DEDENT>if locale:<EOL><INDENT>payload['<STR_LIT>'] = locale<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get a single category used to tag items in Spotify.

        Parameters
        ----------
        category_id : str
            The Spotify category ID for the category.
        country : COUNTRY_TP
            COUNTRY
        locale : LOCALE_TP
            LOCALE


def category_playlists(self, category_id, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>, country=None):

route = Route('<STR_LIT:GET>', '<STR_LIT>', category_id=category_id)<EOL>payload = {'<STR_LIT>': limit, '<STR_LIT>': offset}<EOL>if country:<EOL><INDENT>payload['<STR_LIT>'] = country<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get a list of Spotify playlists tagged with a particular category.

        Parameters
        ----------
        category_id : str
            The Spotify category ID for the category.
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first item to return. Default: 0
        country : COUNTRY_TP
            COUNTRY


def categories(self, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>, country=None, locale=None):

route = Route('<STR_LIT:GET>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': limit, '<STR_LIT>': offset}<EOL>if country:<EOL><INDENT>payload['<STR_LIT>'] = country<EOL><DEDENT>if locale:<EOL><INDENT>payload['<STR_LIT>'] = locale<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get a list of categories used to tag items in Spotify.

        Parameters
        ----------
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first item to return. Default: 0
        country : COUNTRY_TP
            COUNTRY
        locale : LOCALE_TP
            LOCALE


def featured_playlists(self, locale=None, country=None, timestamp=None, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>):

route = Route('<STR_LIT:GET>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': limit, '<STR_LIT>': offset}<EOL>if country:<EOL><INDENT>payload['<STR_LIT>'] = country<EOL><DEDENT>if locale:<EOL><INDENT>payload['<STR_LIT>'] = locale<EOL><DEDENT>if timestamp:<EOL><INDENT>payload['<STR_LIT>'] = timestamp<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get a list of Spotify featured playlists.

        Parameters
        ----------
        locale : LOCALE_TP
            LOCALE
        country : COUNTRY_TP
            COUNTRY
        timestamp : TIMESTAMP_TP
            TIMESTAMP
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first item to return. Default: 0


def new_releases(self, *, country=None, limit=<NUM_LIT:20>, offset=<NUM_LIT:0>):

route = Route('<STR_LIT:GET>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': limit, '<STR_LIT>': offset}<EOL>if country:<EOL><INDENT>payload['<STR_LIT>'] = country<EOL><DEDENT>return self.request(route, params=payload)<EOL>

Get a list of new album releases featured in Spotify.

        Parameters
        ----------
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        offset : Optional[int]
            The index of the first item to return. Default: 0
        country : COUNTRY_TP
            COUNTRY


def recommendations(self, seed_artists, seed_genres, seed_tracks, *, limit=<NUM_LIT:20>, market=None, **filters):

route = Route('<STR_LIT:GET>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': seed_artists, '<STR_LIT>': seed_genres, '<STR_LIT>': seed_tracks, '<STR_LIT>': limit}<EOL>if market:<EOL><INDENT>payload['<STR_LIT>'] = market<EOL><DEDENT>if filters:<EOL><INDENT>payload.update(filters)<EOL><DEDENT>return self.request(route, param=payload)<EOL>

Get Recommendations Based on Seeds.

        Parameters
        ----------
        seed_artists : str
            A comma separated list of Spotify IDs for seed artists. Up to 5 seed values may be provided.
        seed_genres : str
            A comma separated list of any genres in the set of available genre seeds. Up to 5 seed values may be provided.
        seed_tracks : str
            A comma separated list of Spotify IDs for a seed track. Up to 5 seed values may be provided.
        limit : Optional[int]
            The maximum number of items to return. Default: 20. Minimum: 1. Maximum: 50.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code.
        max_* : Optional[Keyword arguments]
            For each tunable track attribute, a hard ceiling on the selected track attribute’s value can be provided.
        min_* : Optional[Keyword arguments]
            For each tunable track attribute, a hard floor on the selected track attribute’s value can be provided.
        target_* : Optional[Keyword arguments]
            For each of the tunable track attributes (below) a target value may be provided.


def following_artists_or_users(self, ids, *, type='<STR_LIT>'):

route = Route('<STR_LIT:GET>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': ids, '<STR_LIT:type>': type}<EOL>return self.request(route, params=payload)<EOL>

Check to see if the current user is following one or more artists or other Spotify users.

        Parameters
        ----------
        ids : List[str]
            A comma-separated list of the artist or the user Spotify IDs to check.
            A maximum of 50 IDs can be sent in one request.
        type : Optional[str]
            The ID type: either "artist" or "user".
            Default: "artist"


def follow_artist_or_user(self, ids, *, type='<STR_LIT>'):

route = Route('<STR_LIT>', '<STR_LIT>')<EOL>payload = {'<STR_LIT>': ids, '<STR_LIT:type>': type}<EOL>return self.request(route, params=payload)<EOL>

Add the current user as a follower of one or more artists or other Spotify users.

        Parameters
        ----------
        ids : List[str]
            A comma-separated list of the artist or the user Spotify IDs to check.
            A maximum of 50 IDs can be sent in one request.
        type : Optional[str]
            The ID type: either "artist" or "user".
            Default: "artist"


string = string.strip()<EOL>match = _URI_RE.match(string)<EOL>if match is None:<EOL><INDENT>match = _OPEN_RE.match(string)<EOL>if match is None:<EOL><INDENT>return string<EOL><DEDENT>else:<EOL><INDENT>return match.group(<NUM_LIT:2>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return match.group(<NUM_LIT:1>)<EOL><DEDENT>

Get a spotify ID from a URI or open.spotify URL.

    Paramters
    ---------
    string : str
        The string to operate on.

    Returns
    -------
    id : str
        The Spotify ID from the string.


def assert_hasattr(attr: str, msg: str, tp: BaseException = SpotifyException) -> Callable:

def decorator(func: Callable) -> Callable:<EOL><INDENT>@functools.wraps(func)<EOL>def decorated(self, *args, **kwargs):<EOL><INDENT>if not hasattr(self, attr):<EOL><INDENT>raise tp(msg)<EOL><DEDENT>return func(self, *args, **kwargs)<EOL><DEDENT>if inspect.iscoroutinefunction(func):<EOL><INDENT>@functools.wraps(func)<EOL>async def decorated(*args, **kwargs):<EOL><INDENT>return await decorated(*args, **kwargs)<EOL><DEDENT><DEDENT>return decorated<EOL><DEDENT>return decorator<EOL>

decorator to assert an object has an attribute when run.


@classmethod<EOL><INDENT>def from_client(cls, client, *args, **kwargs):<DEDENT>

return cls(client.http.client_id, *args, **kwargs)<EOL>

Construct a OAuth2 object from a `spotify.Client`.


@staticmethod<EOL><INDENT>def url_(client_id: str, redirect_uri: str, *, scope: str = None, state: str = None, secure: bool = True) -> str:<DEDENT>

attrs = {<EOL>'<STR_LIT>': client_id,<EOL>'<STR_LIT>': quote(redirect_uri)<EOL>}<EOL>if scope is not None:<EOL><INDENT>attrs['<STR_LIT>'] = quote(scope)<EOL><DEDENT>if state is not None:<EOL><INDENT>attrs['<STR_LIT:state>'] = state<EOL><DEDENT>parameters = '<STR_LIT:&>'.join('<STR_LIT>'.format(*item) for item in attrs.items())<EOL>return OAuth2._BASE.format(parameters=parameters)<EOL>

Construct a OAuth2 URL instead of an OAuth2 object.


return OAuth2.url_(*args, **kwargs)<EOL>


data = {<EOL>'<STR_LIT>': self.client_id,<EOL>'<STR_LIT>': quote(self.redirect_uri),<EOL>}<EOL>if self.scope is not None:<EOL><INDENT>data['<STR_LIT>'] = quote(self.scope)<EOL><DEDENT>if self.state is not None:<EOL><INDENT>data['<STR_LIT:state>'] = self.state<EOL><DEDENT>return data<EOL>

Attributes used when constructing url parameters.


@property<EOL><INDENT>def parameters(self) -> str:<DEDENT>

return '<STR_LIT:&>'.join('<STR_LIT>'.format(*item) for item in self.attrs.items())<EOL>


@property<EOL><INDENT>def url(self) -> str:<DEDENT>

return self._BASE.format(parameters=self.parameters)<EOL>


self.initializers.append(fn)<EOL>return fn<EOL>

Adds a initializer function.

        If you want to initialize the navigation bar within a Flask app
        context, you can use this decorator.

        The decorated function should nave one paramater ``nav`` which is the
        bound navigation extension instance.


ident = self.alias[alias]<EOL>return self.items[ident]<EOL>


return self._get_current_item(self)<EOL>

Get the current active navigation Item if any.

        .. versionadded:: 0.2.0


if self._args is None:<EOL><INDENT>return {}<EOL><DEDENT>if callable(self._args):<EOL><INDENT>return dict(self._args())<EOL><DEDENT>return dict(self._args)<EOL>

The arguments which will be passed to ``url_for``.

        :type: :class:`dict`


if self.is_internal:<EOL><INDENT>return url_for(self.endpoint, **self.args)<EOL><DEDENT>return self._url<EOL>

The final url of this navigation item.

        By default, the value is generated by the :attr:`self.endpoint` and
        :attr:`self.args`.

        .. note::

           The :attr:`url` property require the app context without a provided
           config value :const:`SERVER_NAME`, because of :func:`flask.url_for`.

        :type: :class:`str`


return bool(request and self.is_current)<EOL>

``True`` if the item should be presented as active, and ``False``
        always if the request context is not bound.


return self._url is None<EOL>

``True`` if the target url is internal of current app.


if not self.is_internal:<EOL><INDENT>return False  <EOL><DEDENT>has_same_endpoint = (request.endpoint == self.endpoint)<EOL>has_same_args = (request.view_args == self.args)<EOL>return has_same_endpoint and has_same_args<EOL>

``True`` if current request has same endpoint with the item.

        The property should be used in a bound request context, or the
        :class:`RuntimeError` may be raised.


return ItemReference(self.endpoint, self.args)<EOL>

The identity of this item.

        :type: :class:`~flask.ext.navigation.Navigation.ItemReference`


pairs = dict_.items()<EOL>key_getter = operator.itemgetter(<NUM_LIT:0>)<EOL>return tuple(sorted(pairs, key=key_getter))<EOL>

Freezes ``dict`` into ``tuple``.

    A typical usage is packing ``dict`` into hashable.

    e.g.::

        >>> freeze_dict({'a': 1, 'b': 2})
        (('a', 1), ('b', 2))


attrs = collections.OrderedDict(freeze_dict(attrs or {}))<EOL>template = '<STR_LIT:U+0020>'.join('<STR_LIT>' % (k, i) for i, k in enumerate(attrs))<EOL>return template, list(attrs.values())<EOL>

Joins the map structure into HTML attributes.

    The return value is a 2-tuple ``(template, ordered_values)``. It should be
    passed into :class:`markupsafe.Markup` to prevent XSS attacked.

    e.g.::

        >>> join_html_attrs({'href': '/', 'data-active': 'true'})
        ('data-active="{0}" href="{1}"', ['true', '/'])


return self.bars[name]<EOL>

Gets a bound navigation bar by its name.


<EOL>appcontext_pushed.connect(self.initialize_bars, app)<EOL>app.add_template_global(self, '<STR_LIT>')<EOL>

Initializes an app to work with this extension.

        The app-context signals will be subscribed and the template context
        will be initialized.

        :param app: the :class:`flask.Flask` app instance.


def initialize_bars(self, sender=None, **kwargs):

for bar in self.bars.values():<EOL><INDENT>for initializer in bar.initializers:<EOL><INDENT>initializer(self)<EOL><DEDENT><DEDENT>

Calls the initializers of all bound navigation bars.


def bind_bar(self, sender=None, **kwargs):

bar = kwargs.pop('<STR_LIT:bar>')<EOL>self.bars[bar.name] = bar<EOL>

Binds a navigation bar into this extension instance.


This is a simple command that takes no args.


<EOL>print('<STR_LIT>' % (one, two))<EOL>

This command takes two (required) positional arguments.


<EOL>print('<STR_LIT>' % (three, four))<EOL>

This command takes some keyword options.


@app.command<EOL>def mix_and_match(name, greeting='<STR_LIT>', yell=False):

say = '<STR_LIT>' % (greeting, name)<EOL>if yell:<EOL><INDENT>print('<STR_LIT>' % say.upper())<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % say)<EOL><DEDENT>

Mixing and matching positional args and keyword options.


@app.option('<STR_LIT>', '<STR_LIT>', dest='<STR_LIT>', default='<STR_LIT>')<EOL>@app.option('<STR_LIT>', dest='<STR_LIT>', action='<STR_LIT:store_true>', default=False)<EOL>def option_decorator(name, greeting, yell):

<EOL>say = '<STR_LIT>' % (greeting, name)<EOL>if yell:<EOL><INDENT>print('<STR_LIT>' % say.upper())<EOL><DEDENT>else:<EOL><INDENT>print('<STR_LIT>' % say)<EOL><DEDENT>

Same as mix_and_match, but using the @option decorator.


print('<STR_LIT>')<EOL>return <NUM_LIT><EOL>

This description will show up in the --help. Try it!


def __init__(self, key, secret, raise_errors=False):

self.api_key = key<EOL>self.api_secret = secret<EOL>self._raise_errors = raise_errors<EOL>

Construct a Phaxio API object

        :param key: Phaxio api key
        :param secret: Phaxio api secret
        :param raise_errors: If set to False (default)
            an api call will return the json response
            as it did previously. If set to True, an api
            call will now raise an appropriate error.


payload = None<EOL>try:<EOL><INDENT>if isinstance(response.json, collections.Callable):<EOL><INDENT>payload = response.json()<EOL><DEDENT>else:<EOL><INDENT>payload = response.json<EOL><DEDENT><DEDENT>except ValueError:<EOL><INDENT>payload = response.content<EOL><DEDENT>if not self._raise_errors:<EOL><INDENT>return payload<EOL><DEDENT>else:<EOL><INDENT>if response.status_code == <NUM_LIT>:<EOL><INDENT>raise AuthenticationError(payload['<STR_LIT:message>'])<EOL><DEDENT>elif response.status_code == <NUM_LIT>:<EOL><INDENT>raise ServerError(payload['<STR_LIT:message>'])<EOL><DEDENT>elif isinstance(payload, dict) and not payload['<STR_LIT:success>']:<EOL><INDENT>raise APIError(payload['<STR_LIT:message>'])<EOL><DEDENT>else:<EOL><INDENT>return payload<EOL><DEDENT><DEDENT>

Parses the API response and raises appropriate
        errors if raise_errors was set to True

        :param response: response from requests http call
        :returns: dictionary of response
        :rtype: dict


payload = kwargs.copy()<EOL>payload['<STR_LIT>'] = self.api_key<EOL>payload['<STR_LIT>'] = self.api_secret<EOL>to = payload.pop('<STR_LIT:to>', None)<EOL>if to:<EOL><INDENT>if isinstance(to, basestring):<EOL><INDENT>payload['<STR_LIT:to>'] = to<EOL><DEDENT>else:<EOL><INDENT>for num_i, fax_num in enumerate(to):<EOL><INDENT>payload['<STR_LIT>' % num_i] = fax_num<EOL><DEDENT><DEDENT><DEDENT>files = payload.pop('<STR_LIT>', [])<EOL>if not isinstance(files, (list, tuple)): files = (files,)<EOL>req_files = {}<EOL>for file_i, f in enumerate(files):<EOL><INDENT>if isinstance(f, basestring):<EOL><INDENT>req_files['<STR_LIT>' % file_i] = open(f, '<STR_LIT:rb>')<EOL><DEDENT>else:<EOL><INDENT>f.seek(<NUM_LIT:0>)<EOL>req_files['<STR_LIT>' % file_i] = f<EOL><DEDENT><DEDENT>url = '<STR_LIT>' % (self.BASE_URL, self.VERSION, method)<EOL>r = requests.post(url, data=payload, files=req_files)<EOL>return self.parse_response(r)<EOL>

Builds the url for the specified method and arguments and returns
        the response as a dictionary.


rep = [int(elt) for elt in self]<EOL>return repr(rep)<EOL>

return the representation of a tuple
the __str__ method will use it also


<EOL>all_attributes = PyKCS11.CKA.keys()<EOL>all_attributes = [attr for attr in all_attributes if<EOL>isinstance(attr, int)]<EOL>attributes = self.session.getAttributeValue(self, all_attributes)<EOL>dico = dict()<EOL>for key, attr in zip(all_attributes, attributes):<EOL><INDENT>if attr is None:<EOL><INDENT>continue<EOL><DEDENT>if key == CKA_CLASS:<EOL><INDENT>dico[PyKCS11.CKA[key]] = PyKCS11.CKO[attr]<EOL><DEDENT>elif key == CKA_CERTIFICATE_TYPE:<EOL><INDENT>dico[PyKCS11.CKA[key]] = PyKCS11.CKC[attr]<EOL><DEDENT>elif key == CKA_KEY_TYPE:<EOL><INDENT>dico[PyKCS11.CKA[key]] = PyKCS11.CKK[attr]<EOL><DEDENT>else:<EOL><INDENT>dico[PyKCS11.CKA[key]] = attr<EOL><DEDENT><DEDENT>return dico<EOL>

convert the fields of the object into a dictionnary


dico = self.to_dict()<EOL>lines = list()<EOL>for key in sorted(dico.keys()):<EOL><INDENT>lines.append("<STR_LIT>" % (key, dico[key]))<EOL><DEDENT>return "<STR_LIT:\n>".join(lines)<EOL>


r = []<EOL>for v in self.flags_dict.keys():<EOL><INDENT>if self.flags & v:<EOL><INDENT>r.append(self.flags_dict[v])<EOL><DEDENT><DEDENT>return r<EOL>

parse the `self.flags` field and create a list of `CKF_*` strings
corresponding to bits set in flags

:return: a list of strings
:rtype: list


dico = dict()<EOL>for field in self.fields.keys():<EOL><INDENT>if field == "<STR_LIT>":<EOL><INDENT>dico[field] = self.flags2text()<EOL><DEDENT>elif field == "<STR_LIT:state>":<EOL><INDENT>dico[field] = self.state2text()<EOL><DEDENT>else:<EOL><INDENT>dico[field] = eval("<STR_LIT>" + field)<EOL><DEDENT><DEDENT>return dico<EOL>


dico = self.to_dict()<EOL>lines = list()<EOL>for key in sorted(dico.keys()):<EOL><INDENT>type = self.fields[key]<EOL>if type == "<STR_LIT>":<EOL><INDENT>lines.append("<STR_LIT>" % (key, "<STR_LIT:U+002CU+0020>".join(dico[key])))<EOL><DEDENT>elif type == "<STR_LIT>":<EOL><INDENT>lines.append("<STR_LIT>" % key + "<STR_LIT>" % dico[key])<EOL><DEDENT>else:<EOL><INDENT>lines.append("<STR_LIT>" % (key, dico[key]))<EOL><DEDENT><DEDENT>return "<STR_LIT:\n>".join(lines)<EOL>


return CKS[self.state]<EOL>

parse the `self.state` field and return a `CKS_*` string
corresponding to the state

:return: a string
:rtype: string


if self.value in CKR:<EOL><INDENT>if self.value < <NUM_LIT:0>:<EOL><INDENT>return CKR[self.value] + "<STR_LIT>" % self.text<EOL><DEDENT>else:<EOL><INDENT>return CKR[self.value] + "<STR_LIT>" % self.value<EOL><DEDENT><DEDENT>elif self.value & CKR_VENDOR_DEFINED:<EOL><INDENT>return "<STR_LIT>" % (self.value & <NUM_LIT> & ~CKR_VENDOR_DEFINED)<EOL><DEDENT>else:<EOL><INDENT>return "<STR_LIT>" % self.value<EOL><DEDENT>

The text representation of a PKCS#11 error is something like:
"CKR_DEVICE_ERROR (0x00000030)"


def load(self, pkcs11dll_filename=None, *init_string):

if pkcs11dll_filename is None:<EOL><INDENT>pkcs11dll_filename = os.getenv("<STR_LIT>")<EOL>if pkcs11dll_filename is None:<EOL><INDENT>raise PyKCS11Error(-<NUM_LIT:1>, "<STR_LIT>")<EOL><DEDENT><DEDENT>rv = self.lib.Load(pkcs11dll_filename)<EOL>if rv == <NUM_LIT:0>:<EOL><INDENT>raise PyKCS11Error(-<NUM_LIT:1>, pkcs11dll_filename)<EOL><DEDENT>

load a PKCS#11 library

:type pkcs11dll_filename: string
:param pkcs11dll_filename: the library name.
  If this parameter is not set then the environment variable
  `PYKCS11LIB` is used instead
:returns: a :class:`PyKCS11Lib` object
:raises: :class:`PyKCS11Error` (-1): when the load fails


pin1 = ckbytelist(pin)<EOL>rv = self.lib.C_InitToken(slot, pin1, label)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>

C_InitToken

:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param pin: Security Officer's initial PIN
:param label: new label of the token


info = PyKCS11.LowLevel.CK_INFO()<EOL>rv = self.lib.C_GetInfo(info)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>i = CK_INFO()<EOL>i.cryptokiVersion = (info.cryptokiVersion.major,<EOL>info.cryptokiVersion.minor)<EOL>i.manufacturerID = info.GetManufacturerID()<EOL>i.flags = info.flags<EOL>i.libraryDescription = info.GetLibraryDescription()<EOL>i.libraryVersion = (info.libraryVersion.major,<EOL>info.libraryVersion.minor)<EOL>return i<EOL>

C_GetInfo

:return: a :class:`CK_INFO` object


slotList = PyKCS11.LowLevel.ckintlist()<EOL>rv = self.lib.C_GetSlotList(CK_TRUE if tokenPresent else CK_FALSE,<EOL>slotList)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>s = []<EOL>for x in range(len(slotList)):<EOL><INDENT>s.append(slotList[x])<EOL><DEDENT>return s<EOL>

C_GetSlotList

:param tokenPresent: `False` (default) to list all slots,
  `True` to list only slots with present tokens
:type tokenPresent: bool
:return: a list of available slots
:rtype: list


slotInfo = PyKCS11.LowLevel.CK_SLOT_INFO()<EOL>rv = self.lib.C_GetSlotInfo(slot, slotInfo)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>s = CK_SLOT_INFO()<EOL>s.slotDescription = slotInfo.GetSlotDescription()<EOL>s.manufacturerID = slotInfo.GetManufacturerID()<EOL>s.flags = slotInfo.flags<EOL>s.hardwareVersion = slotInfo.GetHardwareVersion()<EOL>s.firmwareVersion = slotInfo.GetFirmwareVersion()<EOL>return s<EOL>

C_GetSlotInfo

:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: a :class:`CK_SLOT_INFO` object


tokeninfo = PyKCS11.LowLevel.CK_TOKEN_INFO()<EOL>rv = self.lib.C_GetTokenInfo(slot, tokeninfo)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>t = CK_TOKEN_INFO()<EOL>t.label = tokeninfo.GetLabel()<EOL>t.manufacturerID = tokeninfo.GetManufacturerID()<EOL>t.model = tokeninfo.GetModel()<EOL>t.serialNumber = tokeninfo.GetSerialNumber()<EOL>t.flags = tokeninfo.flags<EOL>t.ulMaxSessionCount = tokeninfo.ulMaxSessionCount<EOL>if t.ulMaxSessionCount == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulMaxSessionCount = -<NUM_LIT:1><EOL><DEDENT>t.ulSessionCount = tokeninfo.ulSessionCount<EOL>if t.ulSessionCount == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulSessionCount = -<NUM_LIT:1><EOL><DEDENT>t.ulMaxRwSessionCount = tokeninfo.ulMaxRwSessionCount<EOL>if t.ulMaxRwSessionCount == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulMaxRwSessionCount = -<NUM_LIT:1><EOL><DEDENT>t.ulRwSessionCount = tokeninfo.ulRwSessionCount<EOL>if t.ulRwSessionCount == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulRwSessionCount = -<NUM_LIT:1><EOL><DEDENT>t.ulMaxPinLen = tokeninfo.ulMaxPinLen<EOL>t.ulMinPinLen = tokeninfo.ulMinPinLen<EOL>t.ulTotalPublicMemory = tokeninfo.ulTotalPublicMemory<EOL>if t.ulTotalPublicMemory == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulTotalPublicMemory = -<NUM_LIT:1><EOL><DEDENT>t.ulFreePublicMemory = tokeninfo.ulFreePublicMemory<EOL>if t.ulFreePublicMemory == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulFreePublicMemory = -<NUM_LIT:1><EOL><DEDENT>t.ulTotalPrivateMemory = tokeninfo.ulTotalPrivateMemory<EOL>if t.ulTotalPrivateMemory == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulTotalPrivateMemory = -<NUM_LIT:1><EOL><DEDENT>t.ulFreePrivateMemory = tokeninfo.ulFreePrivateMemory<EOL>if t.ulFreePrivateMemory == CK_UNAVAILABLE_INFORMATION:<EOL><INDENT>t.ulFreePrivateMemory = -<NUM_LIT:1><EOL><DEDENT>t.hardwareVersion = (tokeninfo.hardwareVersion.major,<EOL>tokeninfo.hardwareVersion.minor)<EOL>t.firmwareVersion = (tokeninfo.firmwareVersion.major,<EOL>tokeninfo.firmwareVersion.minor)<EOL>t.utcTime = tokeninfo.GetUtcTime().replace('<STR_LIT>', '<STR_LIT:U+0020>')<EOL>return t<EOL>

C_GetTokenInfo

:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: a :class:`CK_TOKEN_INFO` object


def openSession(self, slot, flags=<NUM_LIT:0>):

se = PyKCS11.LowLevel.CK_SESSION_HANDLE()<EOL>flags |= CKF_SERIAL_SESSION<EOL>rv = self.lib.C_OpenSession(slot, flags, se)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>return Session(self, se)<EOL>

C_OpenSession

:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param flags: 0 (default), `CKF_RW_SESSION` for RW session
:type flags: integer
:return: a :class:`Session` object


rv = self.lib.C_CloseAllSessions(slot)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>

C_CloseAllSessions

:param slot: slot number
:type slot: integer


mechanismList = PyKCS11.LowLevel.ckintlist()<EOL>rv = self.lib.C_GetMechanismList(slot, mechanismList)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>m = []<EOL>for x in range(len(mechanismList)):<EOL><INDENT>mechanism = mechanismList[x]<EOL>if mechanism >= CKM_VENDOR_DEFINED:<EOL><INDENT>k = '<STR_LIT>' % (mechanism - CKM_VENDOR_DEFINED)<EOL>CKM[k] = mechanism<EOL>CKM[mechanism] = k<EOL><DEDENT>m.append(CKM[mechanism])<EOL><DEDENT>return m<EOL>

C_GetMechanismList

:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:return: the list of available mechanisms for a slot
:rtype: list


info = PyKCS11.LowLevel.CK_MECHANISM_INFO()<EOL>rv = self.lib.C_GetMechanismInfo(slot, CKM[type], info)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>i = CK_MECHANISM_INFO()<EOL>i.ulMinKeySize = info.ulMinKeySize<EOL>i.ulMaxKeySize = info.ulMaxKeySize<EOL>i.flags = info.flags<EOL>return i<EOL>

C_GetMechanismInfo

:param slot: slot number returned by :func:`getSlotList`
:type slot: integer
:param type: a `CKM_*` type
:type type: integer
:return: information about a mechanism
:rtype: a :class:`CK_MECHANISM_INFO` object


tmp = <NUM_LIT:0><EOL>(rv, slot) = self.lib.C_WaitForSlotEvent(flags, tmp)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>return slot<EOL>

C_WaitForSlotEvent

:param flags: 0 (default) or `CKF_DONT_BLOCK`
:type flags: integer
:return: slot
:rtype: integer


def __init__(self, mechanism, param=None):

self._mech = PyKCS11.LowLevel.CK_MECHANISM()<EOL>self._mech.mechanism = mechanism<EOL>self._param = None<EOL>if param:<EOL><INDENT>self._param = ckbytelist(param)<EOL>self._mech.pParameter = self._param<EOL>self._mech.ulParameterLen = len(param)<EOL><DEDENT>

:param mechanism: the mechanism to be used
:type mechanism: integer, any `CKM_*` value
:param param: data to be used as crypto operation parameter
  (i.e. the IV for some algorithms)
:type param: string or list/tuple of bytes

:see: :func:`Session.decrypt`, :func:`Session.sign`


def __init__(self, hashAlg, mgf, label=None):

self._param = PyKCS11.LowLevel.CK_RSA_PKCS_OAEP_PARAMS()<EOL>self._param.hashAlg = hashAlg<EOL>self._param.mgf = mgf<EOL>self._source = None<EOL>self._param.src = CKZ_DATA_SPECIFIED<EOL>if label:<EOL><INDENT>self._source = ckbytelist(label)<EOL>self._param.ulSourceDataLen = len(self._source)<EOL><DEDENT>else:<EOL><INDENT>self._param.ulSourceDataLen = <NUM_LIT:0><EOL><DEDENT>self._param.pSourceData = self._source<EOL>self._mech = PyKCS11.LowLevel.CK_MECHANISM()<EOL>self._mech.mechanism = CKM_RSA_PKCS_OAEP<EOL>self._mech.pParameter = self._param<EOL>self._mech.ulParameterLen = PyKCS11.LowLevel.CK_RSA_PKCS_OAEP_PARAMS_LENGTH<EOL>

:param hashAlg: the hash algorithm to use (like `CKM_SHA256`)
:param mgf: the mask generation function to use (like
  `CKG_MGF1_SHA256`)
:param label: the (optional) label to use


def __init__(self, mecha, hashAlg, mgf, sLen):

self._param = PyKCS11.LowLevel.CK_RSA_PKCS_PSS_PARAMS()<EOL>self._param.hashAlg = hashAlg<EOL>self._param.mgf = mgf<EOL>self._param.sLen = sLen<EOL>self._mech = PyKCS11.LowLevel.CK_MECHANISM()<EOL>self._mech.mechanism = mecha<EOL>self._mech.pParameter = self._param<EOL>self._mech.ulParameterLen = PyKCS11.LowLevel.CK_RSA_PKCS_PSS_PARAMS_LENGTH<EOL>

:param mecha: the mechanism to use (like
  `CKM_SHA384_RSA_PKCS_PSS`)
:param hashAlg: the hash algorithm to use (like `CKM_SHA384`)
:param mgf: the mask generation function to use (like
  `CKG_MGF1_SHA384`)
:param sLen: length, in bytes, of the salt value used in the PSS
  encoding (like 0 or the message length)


data1 = ckbytelist(data)<EOL>rv = self._lib.C_DigestUpdate(self._session, data1)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>return self<EOL>

C_DigestUpdate

:param data: data to add to the digest
:type data: bytes or string


rv = self._lib.C_DigestKey(self._session, handle)<EOL>if rv != CKR_OK:<EOL><INDENT>raise PyKCS11Error(rv)<EOL><DEDENT>return self<EOL>

C_DigestKey

:param handle: key handle
:type handle: CK_OBJECT_HANDLE