repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
bitprophet/releases | releases/__init__.py | handle_first_release_line | python | def handle_first_release_line(entries, manager):
# It's remotely possible the changelog is totally empty...
if not entries:
return
# Obtain (short-circuiting) first Release obj.
first_release = None
for obj in entries:
if isinstance(obj, Release):
first_release = obj
... | Set up initial line-manager entry for first encountered release line.
To be called at start of overall process; afterwards, subsequent major
lines are generated by `handle_upcoming_major_release`. | train | https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L434-L455 | [
"def add_family(self, major_number):\n \"\"\"\n Expand to a new release line with given ``major_number``.\n\n This will flesh out mandatory buckets like ``unreleased_bugfix`` and do\n other necessary bookkeeping.\n \"\"\"\n # Normally, we have separate buckets for bugfixes vs features\n keys = ... | import itertools
import re
import sys
from functools import partial
from docutils import nodes, utils
from docutils.parsers.rst import roles
import six
from .models import Issue, ISSUE_TYPES, Release, Version, Spec
from .line_manager import LineManager
from ._version import __version__
def _log(txt, config):
""... |
bitprophet/releases | releases/models.py | Issue.minor_releases | python | def minor_releases(self, manager):
# TODO: yea deffo need a real object for 'manager', heh. E.g. we do a
# very similar test for "do you have any actual releases yet?"
# elsewhere. (This may be fodder for changing how we roll up
# pre-major-release features though...?)
return [
... | Return all minor release line labels found in ``manager``. | train | https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/models.py#L69-L80 | null | class Issue(nodes.Element):
# Technically, we just need number, but heck, you never know...
_cmp_keys = ('type', 'number', 'backported', 'major')
@property
def type(self):
return self['type_']
@property
def is_featurelike(self):
if self.type == 'bug':
return self.ma... |
bitprophet/releases | releases/models.py | Issue.default_spec | python | def default_spec(self, manager):
# TODO: I feel like this + the surrounding bits in add_to_manager()
# could be consolidated & simplified...
specstr = ""
# Make sure truly-default spec skips 0.x if prehistory was unstable.
stable_families = manager.stable_families
if mana... | Given the current release-lines structure, return a default Spec.
Specifics:
* For feature-like issues, only the highest major release is used, so
given a ``manager`` with top level keys of ``[1, 2]``, this would
return ``Spec(">=2")``.
* When ``releases_always_forward... | train | https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/models.py#L82-L125 | [
"def minor_releases(self, manager):\n \"\"\"\n Return all minor release line labels found in ``manager``.\n \"\"\"\n # TODO: yea deffo need a real object for 'manager', heh. E.g. we do a\n # very similar test for \"do you have any actual releases yet?\"\n # elsewhere. (This may be fodder for chang... | class Issue(nodes.Element):
# Technically, we just need number, but heck, you never know...
_cmp_keys = ('type', 'number', 'backported', 'major')
@property
def type(self):
return self['type_']
@property
def is_featurelike(self):
if self.type == 'bug':
return self.ma... |
bitprophet/releases | releases/models.py | Issue.add_to_manager | python | def add_to_manager(self, manager):
# Derive version spec allowing us to filter against major/minor buckets
spec = self.spec or self.default_spec(manager)
# Only look in appropriate major version/family; if self is an issue
# declared as living in e.g. >=2, this means we don't even bother... | Given a 'manager' structure, add self to one or more of its 'buckets'. | train | https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/models.py#L127-L170 | [
"def minor_releases(self, manager):\n \"\"\"\n Return all minor release line labels found in ``manager``.\n \"\"\"\n # TODO: yea deffo need a real object for 'manager', heh. E.g. we do a\n # very similar test for \"do you have any actual releases yet?\"\n # elsewhere. (This may be fodder for chang... | class Issue(nodes.Element):
# Technically, we just need number, but heck, you never know...
_cmp_keys = ('type', 'number', 'backported', 'major')
@property
def type(self):
return self['type_']
@property
def is_featurelike(self):
if self.type == 'bug':
return self.ma... |
tompollard/tableone | tableone.py | TableOne._generate_remark_str | python | def _generate_remark_str(self, end_of_line = '\n'):
warnings = {}
msg = '{}'.format(end_of_line)
# generate warnings for continuous variables
if self._continuous:
# highlight far outliers
outlier_mask = self.cont_describe.far_outliers > 1
outlier_vars... | Generate a series of remarks that the user should consider
when interpreting the summary statistics. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L200-L235 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._detect_categorical_columns | python | def _detect_categorical_columns(self,data):
# assume all non-numerical and date columns are categorical
numeric_cols = set(data._get_numeric_data().columns.values)
date_cols = set(data.select_dtypes(include=[np.datetime64]).columns)
likely_cat = set(data.columns) - numeric_cols
l... | Detect categorical columns if they are not specified.
Parameters
----------
data : pandas DataFrame
The input dataset.
Returns
----------
likely_cat : list
List of variables that appear to be categorical. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L237-L261 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._std | python | def _std(self,x):
return np.nanstd(x.values,ddof=self._ddof) | Compute standard deviation with ddof degrees of freedom | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L275-L279 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._tukey | python | def _tukey(self,x,threshold):
vals = x.values[~np.isnan(x.values)]
try:
q1, q3 = np.percentile(vals, [25, 75])
iqr = q3 - q1
low_bound = q1 - (iqr * threshold)
high_bound = q3 + (iqr * threshold)
outliers = np.where((vals > high_bound) | (vals ... | Count outliers according to Tukey's rule.
Where Q1 is the lower quartile and Q3 is the upper quartile,
an outlier is an observation outside of the range:
[Q1 - k(Q3 - Q1), Q3 + k(Q3 - Q1)]
k = 1.5 indicates an outlier
k = 3.0 indicates an outlier that is "far out" | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L311-L332 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._outliers | python | def _outliers(self,x):
outliers = self._tukey(x, threshold = 1.5)
return np.size(outliers) | Compute number of outliers | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L334-L339 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._far_outliers | python | def _far_outliers(self,x):
outliers = self._tukey(x, threshold = 3.0)
return np.size(outliers) | Compute number of "far out" outliers | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L341-L346 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._t1_summary | python | def _t1_summary(self,x):
# set decimal places
if isinstance(self._decimals,int):
n = self._decimals
elif isinstance(self._decimals,dict):
try:
n = self._decimals[x.name]
except:
n = 1
else:
n = 1
... | Compute median [IQR] or mean (Std) for the input series.
Parameters
----------
x : pandas Series
Series of values to be summarised. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L348-L376 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._create_cont_describe | python | def _create_cont_describe(self,data):
aggfuncs = [pd.Series.count,np.mean,np.median,self._std,
self._q25,self._q75,min,max,self._t1_summary,self._diptest,
self._outliers,self._far_outliers,self._normaltest]
# coerce continuous data to numeric
cont_data = data[self._conti... | Describe the continuous data.
Parameters
----------
data : pandas DataFrame
The input dataset.
Returns
----------
df_cont : pandas DataFrame
Summarise the continuous variables. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L378-L432 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._create_cat_describe | python | def _create_cat_describe(self,data):
group_dict = {}
for g in self._groupbylvls:
if self._groupby:
d_slice = data.loc[data[self._groupby] == g, self._categorical]
else:
d_slice = data[self._categorical].copy()
# create a dataframe wit... | Describe the categorical data.
Parameters
----------
data : pandas DataFrame
The input dataset.
Returns
----------
df_cat : pandas DataFrame
Summarise the categorical variables. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L443-L516 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._create_significance_table | python | def _create_significance_table(self,data):
# list features of the variable e.g. matched, paired, n_expected
df=pd.DataFrame(index=self._continuous+self._categorical,
columns=['continuous','nonnormal','min_observed','pval','ptest'])
df.index.rename('variable', inplace=True)
d... | Create a table containing p-values for significance tests. Add features of
the distributions and the p-values to the dataframe.
Parameters
----------
data : pandas DataFrame
The input dataset.
Returns
----------
df : pandas DataFrame
... | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L518-L572 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._create_cont_table | python | def _create_cont_table(self,data):
# remove the t1_summary level
table = self.cont_describe[['t1_summary']].copy()
table.columns = table.columns.droplevel(level=0)
# add a column of null counts as 1-count() from previous function
nulltable = data[self._continuous].isnull().sum()... | Create tableone for continuous data.
Returns
----------
table : pandas DataFrame
A table summarising the continuous variables. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L642-L673 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._create_cat_table | python | def _create_cat_table(self,data):
table = self.cat_describe['t1_summary'].copy()
# add the total count of null values across all levels
isnull = data[self._categorical].isnull().sum().to_frame(name='isnull')
isnull.index.rename('variable', inplace=True)
try:
table = t... | Create table one for categorical data.
Returns
----------
table : pandas DataFrame
A table summarising the categorical variables. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L675-L700 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._create_tableone | python | def _create_tableone(self,data):
if self._continuous and self._categorical:
# support pandas<=0.22
try:
table = pd.concat([self.cont_table,self.cat_table],sort=False)
except:
table = pd.concat([self.cont_table,self.cat_table])
elif s... | Create table 1 by combining the continuous and categorical tables.
Returns
----------
table : pandas DataFrame
The complete table one. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L702-L834 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | tableone.py | TableOne._create_row_labels | python | def _create_row_labels(self):
# start with the original column names
labels = {}
for c in self._columns:
labels[c] = c
# replace column names with alternative names if provided
if self._alt_labels:
for k in self._alt_labels.keys():
... | Take the original labels for rows. Rename if alternative labels are
provided. Append label suffix if label_suffix is True.
Returns
----------
labels : dictionary
Dictionary, keys are original column name, values are final label. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/tableone.py#L836-L867 | null | class TableOne(object):
"""
If you use the tableone package, please cite:
Pollard TJ, Johnson AEW, Raffa JD, Mark RG (2018). tableone: An open source Python
package for producing summary statistics for research papers. JAMIA Open, Volume 1,
Issue 1, 1 July 2018, Pages 26-31. https://doi.org/10.109... |
tompollard/tableone | modality.py | dip_pval_tabinterpol | python | def dip_pval_tabinterpol(dip, N):
'''
dip - dip value computed from dip_from_cdf
N - number of observations
'''
# if qDiptab_df is None:
# raise DataError("Tabulated p-values not available. See installation instructions.")
if np.isnan(N) or N < 10:
return ... | dip - dip value computed from dip_from_cdf
N - number of observations | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/modality.py#L127-L713 | null |
# ###################################### #
# #
# Updated by: Tom Pollard (2018.03.19) #
# Author: Kerstin Johnsson #
# License: MIT License #
# Available from: #
# https://github.com/kjohnsson/modality #
# ... |
tompollard/tableone | modality.py | dip_and_closest_unimodal_from_cdf | python | def dip_and_closest_unimodal_from_cdf(xF, yF, plotting=False, verbose=False, eps=1e-12):
'''
Dip computed as distance between empirical distribution function (EDF) and
cumulative distribution function for the unimodal distribution with
smallest such distance. The optimal unimodal distributio... | Dip computed as distance between empirical distribution function (EDF) and
cumulative distribution function for the unimodal distribution with
smallest such distance. The optimal unimodal distribution is found by
the algorithm presented in
Hartigan (1985): Computation of the dip sta... | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/modality.py#L719-L942 | null |
# ###################################### #
# #
# Updated by: Tom Pollard (2018.03.19) #
# Author: Kerstin Johnsson #
# License: MIT License #
# Available from: #
# https://github.com/kjohnsson/modality #
# ... |
tompollard/tableone | modality.py | bandwidth_factor | python | def bandwidth_factor(nbr_data_pts, deriv_order=0):
'''
Scale factor for one-dimensional plug-in bandwidth selection.
'''
if deriv_order == 0:
return (3.0*nbr_data_pts/4)**(-1.0/5)
if deriv_order == 2:
return (7.0*nbr_data_pts/4)**(-1.0/9)
raise ValueError('Not implemented f... | Scale factor for one-dimensional plug-in bandwidth selection. | train | https://github.com/tompollard/tableone/blob/4a274d3d2f8d16b8eaa0bde030f3da29b876cee8/modality.py#L1011-L1021 | null |
# ###################################### #
# #
# Updated by: Tom Pollard (2018.03.19) #
# Author: Kerstin Johnsson #
# License: MIT License #
# Available from: #
# https://github.com/kjohnsson/modality #
# ... |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _register_scatter | python | def _register_scatter():
@functools.wraps(PathCollection.__init__)
def __init__(self, *args, **kwargs):
_nonscatter_pathcollections.add(self)
return __init__.__wrapped__(self, *args, **kwargs)
PathCollection.__init__ = __init__
@functools.wraps(Axes.scatter)
def scatter(*args, **kw... | Patch `PathCollection` and `scatter` to register their return values.
This registration allows us to distinguish `PathCollection`s created by
`Axes.scatter`, which should use point-like picking, from others, which
should use path-like picking. The former is more common, so we store the
latter instead;... | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L37-L60 | null | # Unsupported Artist classes: subclasses of AxesImage, QuadMesh (upstream could
# have a `format_coord`-like method); PolyCollection (picking is not well
# defined).
from collections import ChainMap, namedtuple
from contextlib import suppress
import copy
import functools
import inspect
from inspect import Signature
im... |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _compute_projection_pick | python | def _compute_projection_pick(artist, path, xy):
transform = artist.get_transform().frozen()
tpath = (path.cleaned(transform) if transform.is_affine
# `cleaned` only handles affine transforms.
else transform.transform_path(path).cleaned())
# `cleaned` should return a path where the ... | Project *xy* on *path* to obtain a `Selection` for *artist*.
*path* is first transformed to screen coordinates using the artist
transform, and the target of the returned `Selection` is transformed
back to data coordinates using the artist *axes* inverse transform. The
`Selection` `index` is returned a... | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L201-L252 | null | # Unsupported Artist classes: subclasses of AxesImage, QuadMesh (upstream could
# have a `format_coord`-like method); PolyCollection (picking is not well
# defined).
from collections import ChainMap, namedtuple
from contextlib import suppress
import copy
import functools
import inspect
from inspect import Signature
im... |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _untransform | python | def _untransform(orig_xy, screen_xy, ax):
tr_xy = ax.transData.transform(orig_xy)
return (
orig_xy
if ((tr_xy == screen_xy) | np.isnan(tr_xy) & np.isnan(screen_xy)).all()
else ax.transData.inverted().transform(screen_xy)) | Return data coordinates to place an annotation at screen coordinates
*screen_xy* in axes *ax*.
*orig_xy* are the "original" coordinates as stored by the artist; they are
transformed to *screen_xy* by whatever transform the artist uses. If the
artist uses ``ax.transData``, just return *orig_xy*; else, ... | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L255-L270 | null | # Unsupported Artist classes: subclasses of AxesImage, QuadMesh (upstream could
# have a `format_coord`-like method); PolyCollection (picking is not well
# defined).
from collections import ChainMap, namedtuple
from contextlib import suppress
import copy
import functools
import inspect
from inspect import Signature
im... |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _call_with_selection | python | def _call_with_selection(func):
wrapped_kwonly_params = [
param for param in inspect.signature(func).parameters.values()
if param.kind == param.KEYWORD_ONLY]
sel_sig = inspect.signature(Selection)
default_sel_sig = sel_sig.replace(
parameters=[param.replace(default=None) if param.def... | Decorator that passes a `Selection` built from the non-kwonly args. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L481-L508 | null | # Unsupported Artist classes: subclasses of AxesImage, QuadMesh (upstream could
# have a `format_coord`-like method); PolyCollection (picking is not well
# defined).
from collections import ChainMap, namedtuple
from contextlib import suppress
import copy
import functools
import inspect
from inspect import Signature
im... |
anntzer/mplcursors | lib/mplcursors/_pick_info.py | _set_valid_props | python | def _set_valid_props(artist, kwargs):
artist.set(**{k: kwargs[k] for k in kwargs if hasattr(artist, "set_" + k)})
return artist | Set valid properties for the artist, dropping the others. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_pick_info.py#L765-L768 | null | # Unsupported Artist classes: subclasses of AxesImage, QuadMesh (upstream could
# have a `format_coord`-like method); PolyCollection (picking is not well
# defined).
from collections import ChainMap, namedtuple
from contextlib import suppress
import copy
import functools
import inspect
from inspect import Signature
im... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _get_rounded_intersection_area | python | def _get_rounded_intersection_area(bbox_1, bbox_2):
# The rounding allows sorting areas without floating point issues.
bbox = bbox_1.intersection(bbox_1, bbox_2)
return round(bbox.width * bbox.height, 8) if bbox else 0 | Compute the intersection area between two bboxes rounded to 8 digits. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L66-L70 | null | from collections import ChainMap, Counter
from collections.abc import Iterable
from contextlib import suppress
import copy
from functools import partial
import sys
import weakref
from weakref import WeakKeyDictionary
from matplotlib.axes import Axes
from matplotlib.container import Container
from matplotlib.figure imp... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _iter_axes_subartists | python | def _iter_axes_subartists(ax):
r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*."""
yield from ax.collections
yield from ax.images
yield from ax.lines
yield from ax.patches
yield from ax.texts | r"""Yield all child `Artist`\s (*not* `Container`\s) of *ax*. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L73-L79 | null | from collections import ChainMap, Counter
from collections.abc import Iterable
from contextlib import suppress
import copy
from functools import partial
import sys
import weakref
from weakref import WeakKeyDictionary
from matplotlib.axes import Axes
from matplotlib.container import Container
from matplotlib.figure imp... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _is_alive | python | def _is_alive(artist):
return bool(artist
and artist.axes
and (artist.container in artist.axes.containers
if isinstance(artist, _pick_info.ContainerArtist) else
artist in _iter_axes_subartists(artist.axes))) | Check whether *artist* is still present on its parent axes. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L82-L88 | null | from collections import ChainMap, Counter
from collections.abc import Iterable
from contextlib import suppress
import copy
from functools import partial
import sys
import weakref
from weakref import WeakKeyDictionary
from matplotlib.axes import Axes
from matplotlib.container import Container
from matplotlib.figure imp... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | _reassigned_axes_event | python | def _reassigned_axes_event(event, ax):
event = copy.copy(event)
event.xdata, event.ydata = (
ax.transData.inverted().transform_point((event.x, event.y)))
return event | Reassign *event* to *ax*. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L91-L96 | null | from collections import ChainMap, Counter
from collections.abc import Iterable
from contextlib import suppress
import copy
from functools import partial
import sys
import weakref
from weakref import WeakKeyDictionary
from matplotlib.axes import Axes
from matplotlib.container import Container
from matplotlib.figure imp... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | cursor | python | def cursor(pickables=None, **kwargs):
if pickables is None:
# Do not import pyplot ourselves to avoid forcing the backend.
plt = sys.modules.get("matplotlib.pyplot")
pickables = [
plt.figure(num) for num in plt.get_fignums()] if plt else []
elif (isinstance(pickables, Contai... | Create a `Cursor` for a list of artists, containers, and axes.
Parameters
----------
pickables : Optional[List[Union[Artist, Container, Axes, Figure]]]
All artists and containers in the list or on any of the axes or
figures passed in the list are selectable by the constructed `Cursor`.
... | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L546-L601 | [
"def iter_unpack_figures(pickables):\n for entry in pickables:\n if isinstance(entry, Figure):\n yield from entry.axes\n else:\n yield entry\n",
"def iter_unpack_axes(pickables):\n for entry in pickables:\n if isinstance(entry, Axes):\n yield from _iter_... | from collections import ChainMap, Counter
from collections.abc import Iterable
from contextlib import suppress
import copy
from functools import partial
import sys
import weakref
from weakref import WeakKeyDictionary
from matplotlib.axes import Axes
from matplotlib.container import Container
from matplotlib.figure imp... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.selections | python | def selections(self):
r"""The tuple of current `Selection`\s."""
for sel in self._selections:
if sel.annotation.axes is None:
raise RuntimeError("Annotation unexpectedly removed; "
"use 'cursor.remove_selection' instead")
return tupl... | r"""The tuple of current `Selection`\s. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L259-L265 | null | class Cursor:
"""
A cursor for selecting Matplotlib artists.
Attributes
----------
bindings : dict
See the *bindings* keyword argument to the constructor.
annotation_kwargs : dict
See the *annotation_kwargs* keyword argument to the constructor.
annotation_positions : dict
... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.add_selection | python | def add_selection(self, pi):
# pi: "pick_info", i.e. an incomplete selection.
# Pre-fetch the figure and axes, as callbacks may actually unset them.
figure = pi.artist.figure
axes = pi.artist.axes
if axes.get_renderer_cache() is None:
figure.canvas.draw() # Needed by... | Create an annotation for a `Selection` and register it.
Returns a new `Selection`, that has been registered by the `Cursor`,
with the added annotation set in the :attr:`annotation` field and, if
applicable, the highlighting artist in the :attr:`extras` field.
Emits the ``"add"`` event ... | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L284-L372 | [
"def _get_rounded_intersection_area(bbox_1, bbox_2):\n \"\"\"Compute the intersection area between two bboxes rounded to 8 digits.\"\"\"\n # The rounding allows sorting areas without floating point issues.\n bbox = bbox_1.intersection(bbox_1, bbox_2)\n return round(bbox.width * bbox.height, 8) if bbox e... | class Cursor:
"""
A cursor for selecting Matplotlib artists.
Attributes
----------
bindings : dict
See the *bindings* keyword argument to the constructor.
annotation_kwargs : dict
See the *annotation_kwargs* keyword argument to the constructor.
annotation_positions : dict
... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.add_highlight | python | def add_highlight(self, artist, *args, **kwargs):
hl = _pick_info.make_highlight(
artist, *args,
**ChainMap({"highlight_kwargs": self.highlight_kwargs}, kwargs))
if hl:
artist.axes.add_artist(hl)
return hl | Create, add, and return a highlighting artist.
This method is should be called with an "unpacked" `Selection`,
possibly with some fields set to None.
It is up to the caller to register the artist with the proper
`Selection` (by calling ``sel.extras.append`` on the result of this
... | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L374-L390 | null | class Cursor:
"""
A cursor for selecting Matplotlib artists.
Attributes
----------
bindings : dict
See the *bindings* keyword argument to the constructor.
annotation_kwargs : dict
See the *annotation_kwargs* keyword argument to the constructor.
annotation_positions : dict
... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.connect | python | def connect(self, event, func=None):
if event not in self._callbacks:
raise ValueError("{!r} is not a valid cursor event".format(event))
if func is None:
return partial(self.connect, event)
self._callbacks[event].append(func)
return func | Connect a callback to a `Cursor` event; return the callback.
Two events can be connected to:
- callbacks connected to the ``"add"`` event are called when a
`Selection` is added, with that selection as only argument;
- callbacks connected to the ``"remove"`` event are called when a
... | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L392-L424 | null | class Cursor:
"""
A cursor for selecting Matplotlib artists.
Attributes
----------
bindings : dict
See the *bindings* keyword argument to the constructor.
annotation_kwargs : dict
See the *annotation_kwargs* keyword argument to the constructor.
annotation_positions : dict
... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.disconnect | python | def disconnect(self, event, cb):
try:
self._callbacks[event].remove(cb)
except KeyError:
raise ValueError("{!r} is not a valid cursor event".format(event))
except ValueError:
raise ValueError("Callback {} is not registered".format(event)) | Disconnect a previously connected callback.
If a callback is connected multiple times, only one connection is
removed. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L426-L438 | null | class Cursor:
"""
A cursor for selecting Matplotlib artists.
Attributes
----------
bindings : dict
See the *bindings* keyword argument to the constructor.
annotation_kwargs : dict
See the *annotation_kwargs* keyword argument to the constructor.
annotation_positions : dict
... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.remove | python | def remove(self):
for disconnectors in self._disconnectors:
disconnectors()
for sel in self.selections:
self.remove_selection(sel)
for s in type(self)._keep_alive.values():
with suppress(KeyError):
s.remove(self) | Remove a cursor.
Remove all `Selection`\\s, disconnect all callbacks, and allow the
cursor to be garbage collected. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L440-L453 | [
"def remove_selection(self, sel):\n \"\"\"Remove a `Selection`.\"\"\"\n self._selections.remove(sel)\n # <artist>.figure will be unset so we save them first.\n figures = {artist.figure for artist in [sel.annotation] + sel.extras}\n # ValueError is raised if the artist has already been removed.\n w... | class Cursor:
"""
A cursor for selecting Matplotlib artists.
Attributes
----------
bindings : dict
See the *bindings* keyword argument to the constructor.
annotation_kwargs : dict
See the *annotation_kwargs* keyword argument to the constructor.
annotation_positions : dict
... |
anntzer/mplcursors | lib/mplcursors/_mplcursors.py | Cursor.remove_selection | python | def remove_selection(self, sel):
self._selections.remove(sel)
# <artist>.figure will be unset so we save them first.
figures = {artist.figure for artist in [sel.annotation] + sel.extras}
# ValueError is raised if the artist has already been removed.
with suppress(ValueError):
... | Remove a `Selection`. | train | https://github.com/anntzer/mplcursors/blob/a4bce17a978162b5a1837cc419114c910e7992f9/lib/mplcursors/_mplcursors.py#L529-L543 | null | class Cursor:
"""
A cursor for selecting Matplotlib artists.
Attributes
----------
bindings : dict
See the *bindings* keyword argument to the constructor.
annotation_kwargs : dict
See the *annotation_kwargs* keyword argument to the constructor.
annotation_positions : dict
... |
avinassh/haxor | hackernews/__init__.py | HackerNews._get_sync | python | def _get_sync(self, url):
response = self.session.get(url)
if response.status_code == requests.codes.ok:
return response.json()
else:
raise HTTPError | Internal method used for GET requests
Args:
url (str): URL to fetch
Returns:
Individual URL request's response
Raises:
HTTPError: If HTTP request failed. | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L74-L90 | null | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews._get_async | python | async def _get_async(self, url, session):
data = None
async with session.get(url) as resp:
if resp.status == 200:
data = await resp.json()
return data | Asynchronous internal method used for GET requests
Args:
url (str): URL to fetch
session (obj): aiohttp client session for async loop
Returns:
data (obj): Individual URL request's response corountine | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L92-L107 | null | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews._async_loop | python | async def _async_loop(self, urls):
results = []
async with aiohttp.ClientSession(
connector=aiohttp.TCPConnector(ssl=False)
) as session:
for url in urls:
result = asyncio.ensure_future(self._get_async(url, session))
results.append(result)
... | Asynchronous internal method used to request multiple URLs
Args:
urls (list): URLs to fetch
Returns:
responses (obj): All URL requests' response coroutines | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L109-L127 | [
"async def _get_async(self, url, session):\n \"\"\"Asynchronous internal method used for GET requests\n\n Args:\n url (str): URL to fetch\n session (obj): aiohttp client session for async loop\n\n Returns:\n data (obj): Individual URL request's response corountine\n\n \"\"\"\n da... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews._run_async | python | def _run_async(self, urls):
loop = asyncio.get_event_loop()
results = loop.run_until_complete(self._async_loop(urls))
return results | Asynchronous event loop execution
Args:
urls (list): URLs to fetch
Returns:
results (obj): All URL requests' responses | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L129-L141 | [
"async def _async_loop(self, urls):\n \"\"\"Asynchronous internal method used to request multiple URLs\n\n Args:\n urls (list): URLs to fetch\n\n Returns:\n responses (obj): All URL requests' response coroutines\n\n \"\"\"\n results = []\n async with aiohttp.ClientSession(\n c... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews._get_stories | python | def _get_stories(self, page, limit):
url = urljoin(self.base_url, F"{page}.json")
story_ids = self._get_sync(url)[:limit]
return self.get_items_by_ids(item_ids=story_ids) | Hacker News has different categories (i.e. stories) like
'topstories', 'newstories', 'askstories', 'showstories', 'jobstories'.
This method, first fetches the relevant story ids of that category
The URL is: https://hacker-news.firebaseio.com/v0/<story_name>.json
e.g. https://hacker-new... | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L143-L163 | [
"def _get_sync(self, url):\n \"\"\"Internal method used for GET requests\n\n Args:\n url (str): URL to fetch\n\n Returns:\n Individual URL request's response\n\n Raises:\n HTTPError: If HTTP request failed.\n \"\"\"\n response = self.session.get(url)\n if response.status_code... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.get_item | python | def get_item(self, item_id, expand=False):
url = urljoin(self.item_url, F"{item_id}.json")
response = self._get_sync(url)
if not response:
raise InvalidItemID
item = Item(response)
if expand:
item.by = self.get_user(item.by)
item.kids = self.... | Returns Hacker News `Item` object.
Fetches the data from url:
https://hacker-news.firebaseio.com/v0/item/<item_id>.json
e.g. https://hacker-news.firebaseio.com/v0/item/69696969.json
Args:
item_id (int or string): Unique item id of Hacker News story,
comment... | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L165-L202 | [
"def _get_sync(self, url):\n \"\"\"Internal method used for GET requests\n\n Args:\n url (str): URL to fetch\n\n Returns:\n Individual URL request's response\n\n Raises:\n HTTPError: If HTTP request failed.\n \"\"\"\n response = self.session.get(url)\n if response.status_code... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.get_items_by_ids | python | def get_items_by_ids(self, item_ids, item_type=None):
urls = [urljoin(self.item_url, F"{i}.json") for i in item_ids]
result = self._run_async(urls=urls)
items = [Item(r) for r in result if r]
if item_type:
return [item for item in items if item.item_type == item_type]
... | Given a list of item ids, return all the Item objects
Args:
item_ids (obj): List of item IDs to query
item_type (str): (optional) Item type to filter results with
Returns:
List of `Item` objects for given item IDs and given item type | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L204-L221 | [
"def _run_async(self, urls):\n \"\"\"Asynchronous event loop execution\n\n Args:\n urls (list): URLs to fetch\n\n Returns:\n results (obj): All URL requests' responses\n\n \"\"\"\n loop = asyncio.get_event_loop()\n results = loop.run_until_complete(self._async_loop(urls))\n return... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.get_user | python | def get_user(self, user_id, expand=False):
url = urljoin(self.user_url, F"{user_id}.json")
response = self._get_sync(url)
if not response:
raise InvalidUserID
user = User(response)
if expand and user.submitted:
items = self.get_items_by_ids(user.submitte... | Returns Hacker News `User` object.
Fetches data from the url:
https://hacker-news.firebaseio.com/v0/user/<user_id>.json
e.g. https://hacker-news.firebaseio.com/v0/user/pg.json
Args:
user_id (string): unique user id of a Hacker News user.
expand (bool): Flag... | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L223-L266 | [
"def _get_sync(self, url):\n \"\"\"Internal method used for GET requests\n\n Args:\n url (str): URL to fetch\n\n Returns:\n Individual URL request's response\n\n Raises:\n HTTPError: If HTTP request failed.\n \"\"\"\n response = self.session.get(url)\n if response.status_code... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.get_users_by_ids | python | def get_users_by_ids(self, user_ids):
urls = [urljoin(self.user_url, F"{i}.json") for i in user_ids]
result = self._run_async(urls=urls)
return [User(r) for r in result if r] | Given a list of user ids, return all the User objects | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L268-L274 | [
"def _run_async(self, urls):\n \"\"\"Asynchronous event loop execution\n\n Args:\n urls (list): URLs to fetch\n\n Returns:\n results (obj): All URL requests' responses\n\n \"\"\"\n loop = asyncio.get_event_loop()\n results = loop.run_until_complete(self._async_loop(urls))\n return... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.top_stories | python | def top_stories(self, raw=False, limit=None):
top_stories = self._get_stories('topstories', limit)
if raw:
top_stories = [story.raw for story in top_stories]
return top_stories | Returns list of item ids of current top stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to represent all
objects in raw json.
Returns:
`list` object containing ids of top stories. | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L276-L291 | [
"def _get_stories(self, page, limit):\n \"\"\"\n Hacker News has different categories (i.e. stories) like\n 'topstories', 'newstories', 'askstories', 'showstories', 'jobstories'.\n This method, first fetches the relevant story ids of that category\n\n The URL is: https://hacker-news.firebaseio.com/v0... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.new_stories | python | def new_stories(self, raw=False, limit=None):
new_stories = self._get_stories('newstories', limit)
if raw:
new_stories = [story.raw for story in new_stories]
return new_stories | Returns list of item ids of current new stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to transform all
objects into raw json.
Returns:
`list` object containing ids of new stories. | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L293-L308 | [
"def _get_stories(self, page, limit):\n \"\"\"\n Hacker News has different categories (i.e. stories) like\n 'topstories', 'newstories', 'askstories', 'showstories', 'jobstories'.\n This method, first fetches the relevant story ids of that category\n\n The URL is: https://hacker-news.firebaseio.com/v0... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.ask_stories | python | def ask_stories(self, raw=False, limit=None):
ask_stories = self._get_stories('askstories', limit)
if raw:
ask_stories = [story.raw for story in ask_stories]
return ask_stories | Returns list of item ids of latest Ask HN stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to transform all
objects into raw json.
Returns:
`list` object containing ids of Ask HN stories. | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L310-L325 | [
"def _get_stories(self, page, limit):\n \"\"\"\n Hacker News has different categories (i.e. stories) like\n 'topstories', 'newstories', 'askstories', 'showstories', 'jobstories'.\n This method, first fetches the relevant story ids of that category\n\n The URL is: https://hacker-news.firebaseio.com/v0... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.show_stories | python | def show_stories(self, raw=False, limit=None):
show_stories = self._get_stories('showstories', limit)
if raw:
show_stories = [story.raw for story in show_stories]
return show_stories | Returns list of item ids of latest Show HN stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to transform all
objects into raw json.
Returns:
`list` object containing ids of Show HN storie... | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L327-L342 | [
"def _get_stories(self, page, limit):\n \"\"\"\n Hacker News has different categories (i.e. stories) like\n 'topstories', 'newstories', 'askstories', 'showstories', 'jobstories'.\n This method, first fetches the relevant story ids of that category\n\n The URL is: https://hacker-news.firebaseio.com/v0... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.job_stories | python | def job_stories(self, raw=False, limit=None):
job_stories = self._get_stories('jobstories', limit)
if raw:
job_stories = [story.raw for story in job_stories]
return job_stories | Returns list of item ids of latest Job stories
Args:
limit (int): specifies the number of stories to be returned.
raw (bool): Flag to indicate whether to transform all
objects into raw json.
Returns:
`list` object containing ids of Job stories. | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L344-L359 | [
"def _get_stories(self, page, limit):\n \"\"\"\n Hacker News has different categories (i.e. stories) like\n 'topstories', 'newstories', 'askstories', 'showstories', 'jobstories'.\n This method, first fetches the relevant story ids of that category\n\n The URL is: https://hacker-news.firebaseio.com/v0... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.updates | python | def updates(self):
url = urljoin(self.base_url, 'updates.json')
response = self._get_sync(url)
return {
'items': self.get_items_by_ids(item_ids=response['items']),
'profiles': self.get_users_by_ids(user_ids=response['profiles'])
} | Returns list of item ids and user ids that have been
changed/updated recently.
Fetches data from URL:
https://hacker-news.firebaseio.com/v0/updates.json
Returns:
`dict` with two keys whose values are `list` objects | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L361-L377 | [
"def _get_sync(self, url):\n \"\"\"Internal method used for GET requests\n\n Args:\n url (str): URL to fetch\n\n Returns:\n Individual URL request's response\n\n Raises:\n HTTPError: If HTTP request failed.\n \"\"\"\n response = self.session.get(url)\n if response.status_code... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.get_max_item | python | def get_max_item(self, expand=False):
url = urljoin(self.base_url, 'maxitem.json')
response = self._get_sync(url)
if expand:
return self.get_item(response)
else:
return response | The current largest item id
Fetches data from URL:
https://hacker-news.firebaseio.com/v0/maxitem.json
Args:
expand (bool): Flag to indicate whether to transform all
IDs into objects.
Returns:
`int` if successful. | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L379-L398 | [
"def _get_sync(self, url):\n \"\"\"Internal method used for GET requests\n\n Args:\n url (str): URL to fetch\n\n Returns:\n Individual URL request's response\n\n Raises:\n HTTPError: If HTTP request failed.\n \"\"\"\n response = self.session.get(url)\n if response.status_code... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
avinassh/haxor | hackernews/__init__.py | HackerNews.get_last | python | def get_last(self, num=10):
max_item = self.get_max_item()
urls = [urljoin(self.item_url, F"{i}.json") for i in range(
max_item - num + 1, max_item + 1)]
result = self._run_async(urls=urls)
return [Item(r) for r in result if r] | Returns last `num` of HN stories
Downloads all the HN articles and returns them as Item objects
Returns:
`list` object containing ids of HN stories. | train | https://github.com/avinassh/haxor/blob/71dbecf87531f7a24bb39c736d53127427aaca84/hackernews/__init__.py#L412-L425 | [
"def _run_async(self, urls):\n \"\"\"Asynchronous event loop execution\n\n Args:\n urls (list): URLs to fetch\n\n Returns:\n results (obj): All URL requests' responses\n\n \"\"\"\n loop = asyncio.get_event_loop()\n results = loop.run_until_complete(self._async_loop(urls))\n return... | class HackerNews(object):
def __init__(self, version='v0'):
"""
Args:
version (string): specifies Hacker News API version.
Default is `v0`.
Raises:
InvalidAPIVersion: If Hacker News version is not supported.
"""
try:
self.base... |
Zsailer/phylopandas | phylopandas/treeio/read.py | _dendropy_to_dataframe | python | def _dendropy_to_dataframe(
tree,
add_node_labels=True,
use_uids=True):
# Maximum distance from root.
tree.max_distance_from_root()
# Initialize the data object.
idx = []
data = {
'type': [],
'id': [],
'parent': [],
'length': [],
'label': [],
... | Convert Dendropy tree to Pandas dataframe. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/read.py#L35-L104 | null | import pandas
import dendropy
from ..utils import get_random_id
def _read_doc_template(schema):
doc = """
Read a {} tree into a phylopandas.DataFrame.
The resulting DataFrame has the following columns:
- name: label for each taxa or node.
- id: unique id (created by phylopandas) given to e... |
Zsailer/phylopandas | phylopandas/treeio/read.py | _read | python | def _read(
filename=None,
data=None,
schema=None,
add_node_labels=True,
use_uids=True
):
if filename is not None:
# Use Dendropy to parse tree.
tree = dendropy.Tree.get(
path=filename,
schema=schema,
preserve_underscores=True)
elif data... | Read a phylogenetic tree into a phylopandas.DataFrame.
The resulting DataFrame has the following columns:
- name: label for each taxa or node.
- id: unique id (created by phylopandas) given to each node.
- type: type of node (leaf, internal, or root).
- parent: parent id. necessary ... | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/read.py#L107-L158 | [
"def _dendropy_to_dataframe(\n tree,\n add_node_labels=True,\n use_uids=True):\n \"\"\"Convert Dendropy tree to Pandas dataframe.\"\"\"\n # Maximum distance from root.\n tree.max_distance_from_root()\n\n # Initialize the data object.\n idx = []\n data = {\n 'type': [],\n 'id... | import pandas
import dendropy
from ..utils import get_random_id
def _read_doc_template(schema):
doc = """
Read a {} tree into a phylopandas.DataFrame.
The resulting DataFrame has the following columns:
- name: label for each taxa or node.
- id: unique id (created by phylopandas) given to e... |
Zsailer/phylopandas | phylopandas/treeio/read.py | _read_function | python | def _read_function(schema):
def func(
filename=None,
data=None,
add_node_labels=True,
use_uids=True,
**kwargs):
# Use generic write class to write data.
return _read(
filename=filename,
data=data,
schema=schema,
... | Add a write method for named schema to a class. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/read.py#L189-L209 | [
"def _read_doc_template(schema):\n doc = \"\"\"\n Read a {} tree into a phylopandas.DataFrame.\n\n The resulting DataFrame has the following columns:\n - name: label for each taxa or node.\n - id: unique id (created by phylopandas) given to each node.\n - type: type of node (leaf, inte... | import pandas
import dendropy
from ..utils import get_random_id
def _read_doc_template(schema):
doc = """
Read a {} tree into a phylopandas.DataFrame.
The resulting DataFrame has the following columns:
- name: label for each taxa or node.
- id: unique id (created by phylopandas) given to e... |
Zsailer/phylopandas | phylopandas/seqio/write.py | pandas_df_to_biopython_seqrecord | python | def pandas_df_to_biopython_seqrecord(
df,
id_col='uid',
sequence_col='sequence',
extra_data=None,
alphabet=None,
):
seq_records = []
for i, row in df.iterrows():
# Tries getting sequence data. If a TypeError at the seqrecord
# creation is thrown, it is assumed that this ... | Convert pandas dataframe to biopython seqrecord for easy writing.
Parameters
----------
df : Dataframe
Pandas dataframe to convert
id_col : str
column in dataframe to use as sequence label
sequence_col str:
column in dataframe to use as sequence data
extra_data : list... | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/write.py#L34-L93 | null | __doc__ = """
Functions for write sequence data to sequence files.
"""
import pandas as pd
# Import Biopython
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import Bio.Alphabet
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filena... |
Zsailer/phylopandas | phylopandas/seqio/write.py | pandas_series_to_biopython_seqrecord | python | def pandas_series_to_biopython_seqrecord(
series,
id_col='uid',
sequence_col='sequence',
extra_data=None,
alphabet=None
):
# Get sequence
seq = Seq(series[sequence_col], alphabet=alphabet)
# Get id
id = series[id_col]
# Build a description
description = ""
if extra_... | Convert pandas series to biopython seqrecord for easy writing.
Parameters
----------
series : Series
Pandas series to convert
id_col : str
column in dataframe to use as sequence label
sequence_col : str
column in dataframe to use as sequence data
extra_data : list
... | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/write.py#L95-L142 | null | __doc__ = """
Functions for write sequence data to sequence files.
"""
import pandas as pd
# Import Biopython
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import Bio.Alphabet
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filena... |
Zsailer/phylopandas | phylopandas/seqio/write.py | _write | python | def _write(
data,
filename=None,
schema='fasta',
id_col='uid',
sequence_col='sequence',
extra_data=None,
alphabet=None,
**kwargs):
# Check Alphabet if given
if alphabet is None:
alphabet = Bio.Alphabet.Alphabet()
elif alphabet in ['dna', 'rna', 'protein', 'nucleotide... | General write function. Write phylopanda data to biopython format.
Parameters
----------
filename : str
File to write string to. If no filename is given, a string
will be returned.
sequence_col : str (default='sequence')
Sequence column name in DataFrame.
id_col : str (def... | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/write.py#L144-L207 | [
"def pandas_df_to_biopython_seqrecord(\n df,\n id_col='uid',\n sequence_col='sequence',\n extra_data=None,\n alphabet=None,\n ):\n \"\"\"Convert pandas dataframe to biopython seqrecord for easy writing.\n\n Parameters\n ----------\n df : Dataframe\n Pandas dataframe to convert\n... | __doc__ = """
Functions for write sequence data to sequence files.
"""
import pandas as pd
# Import Biopython
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import Bio.Alphabet
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filena... |
Zsailer/phylopandas | phylopandas/seqio/write.py | _write_method | python | def _write_method(schema):
def method(
self,
filename=None,
schema=schema,
id_col='uid',
sequence_col='sequence',
extra_data=None,
alphabet=None,
**kwargs):
# Use generic write class to write data.
return _write(
self._data,... | Add a write method for named schema to a class. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/write.py#L209-L234 | [
"def _write_doc_template(schema):\n s = \"\"\"Write to {} format.\n\n Parameters\n ----------\n filename : str\n File to write {} string to. If no filename is given, a {} string\n will be returned.\n\n sequence_col : str (default='sequence')\n Sequence column name in DataFrame.\n... | __doc__ = """
Functions for write sequence data to sequence files.
"""
import pandas as pd
# Import Biopython
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import Bio.Alphabet
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filena... |
Zsailer/phylopandas | phylopandas/seqio/write.py | _write_function | python | def _write_function(schema):
def func(
data,
filename=None,
schema=schema,
id_col='uid',
sequence_col='sequence',
extra_data=None,
alphabet=None,
**kwargs):
# Use generic write class to write data.
return _write(
data,
... | Add a write method for named schema to a class. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/write.py#L237-L262 | [
"def _write_doc_template(schema):\n s = \"\"\"Write to {} format.\n\n Parameters\n ----------\n filename : str\n File to write {} string to. If no filename is given, a {} string\n will be returned.\n\n sequence_col : str (default='sequence')\n Sequence column name in DataFrame.\n... | __doc__ = """
Functions for write sequence data to sequence files.
"""
import pandas as pd
# Import Biopython
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
import Bio.Alphabet
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filena... |
Zsailer/phylopandas | phylopandas/seqio/read.py | _read | python | def _read(
filename,
schema,
seq_label='sequence',
alphabet=None,
use_uids=True,
**kwargs):
# Check Alphabet if given
if alphabet is None:
alphabet = Bio.Alphabet.Alphabet()
elif alphabet in ['dna', 'rna', 'protein', 'nucleotide']:
alphabet = getattr(Bio.Alphabet, 'g... | Use BioPython's sequence parsing module to convert any file format to
a Pandas DataFrame.
The resulting DataFrame has the following columns:
- name
- id
- description
- sequence | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/read.py#L37-L88 | [
"def get_random_id(length):\n \"\"\"Generate a random, alpha-numerical id.\"\"\"\n alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits\n return ''.join(random.choice(alphabet) for _ in range(length))\n"
] | __doc__ = """
Functions for reading sequence files into pandas DataFrame.
"""
# Imports
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Blast import NCBIXML
import Bio.Alphabet
# Import Phylopandas DataFrame
import pandas as pd
from ..utils import get_random_id
def _read_d... |
Zsailer/phylopandas | phylopandas/seqio/read.py | _read_method | python | def _read_method(schema):
def func(
self,
filename,
seq_label='sequence',
alphabet=None,
combine_on='uid',
use_uids=True,
**kwargs):
# Use generic write class to write data.
df0 = self._data
df1 = _read(
filename=filename,
... | Add a write method for named schema to a class. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/read.py#L91-L116 | [
"def _read_doc_template(schema):\n s = \"\"\"Read a {} file.\n\n Construct a PhyloPandas DataFrame with columns:\n - name\n - id\n - description\n - sequence\n\n Parameters\n ----------\n filename : str\n File name of {} file.\n\n seq_label : str (default='sequen... | __doc__ = """
Functions for reading sequence files into pandas DataFrame.
"""
# Imports
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Blast import NCBIXML
import Bio.Alphabet
# Import Phylopandas DataFrame
import pandas as pd
from ..utils import get_random_id
def _read_d... |
Zsailer/phylopandas | phylopandas/seqio/read.py | _read_function | python | def _read_function(schema):
def func(
filename,
seq_label='sequence',
alphabet=None,
use_uids=True,
**kwargs):
# Use generic write class to write data.
return _read(
filename=filename,
schema=schema,
seq_label=seq_label,
... | Add a write method for named schema to a class. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/read.py#L119-L139 | [
"def _read_doc_template(schema):\n s = \"\"\"Read a {} file.\n\n Construct a PhyloPandas DataFrame with columns:\n - name\n - id\n - description\n - sequence\n\n Parameters\n ----------\n filename : str\n File name of {} file.\n\n seq_label : str (default='sequen... | __doc__ = """
Functions for reading sequence files into pandas DataFrame.
"""
# Imports
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Blast import NCBIXML
import Bio.Alphabet
# Import Phylopandas DataFrame
import pandas as pd
from ..utils import get_random_id
def _read_d... |
Zsailer/phylopandas | phylopandas/seqio/read.py | read_blast_xml | python | def read_blast_xml(filename, **kwargs):
# Read file.
with open(filename, 'r') as f:
blast_record = NCBIXML.read(f)
# Prepare DataFrame fields.
data = {'accession': [],
'hit_def': [],
'hit_id': [],
'title': [],
'length': [],
'e_value': ... | Read BLAST XML format. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/seqio/read.py#L154-L180 | null | __doc__ = """
Functions for reading sequence files into pandas DataFrame.
"""
# Imports
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Blast import NCBIXML
import Bio.Alphabet
# Import Phylopandas DataFrame
import pandas as pd
from ..utils import get_random_id
def _read_d... |
Zsailer/phylopandas | phylopandas/treeio/write.py | _pandas_df_to_dendropy_tree | python | def _pandas_df_to_dendropy_tree(
df,
taxon_col='uid',
taxon_annotations=[],
node_col='uid',
node_annotations=[],
branch_lengths=True,
):
if isinstance(taxon_col, str) is False:
raise Exception("taxon_col must be a string.")
if isinstance(node_col, str) is False:
rais... | Turn a phylopandas dataframe into a dendropy tree.
Parameters
----------
df : DataFrame
DataFrame containing tree data.
taxon_col : str (optional)
Column in dataframe to label the taxon. If None, the index will be used.
taxon_annotations : str
List of columns to annotation... | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/write.py#L31-L126 | null | import pandas
import dendropy
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filename : str
File to write {} string to. If no filename is given, a {} string
will be returned.
taxon_col : str (default='sequence')
Sequence column name in Da... |
Zsailer/phylopandas | phylopandas/treeio/write.py | _write | python | def _write(
df,
filename=None,
schema='newick',
taxon_col='uid',
taxon_annotations=[],
node_col='uid',
node_annotations=[],
branch_lengths=True,
**kwargs
):
tree = _pandas_df_to_dendropy_tree(
df,
taxon_col=taxon_col,
taxon_annotations=taxon_annotation... | Write a phylopandas tree DataFrame to various formats.
Parameters
----------
df : DataFrame
DataFrame containing tree data.
filename : str
filepath to write out tree. If None, will return string.
schema : str
tree format to write out.
taxon_col : str (optional)
... | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/write.py#L129-L182 | [
"def _pandas_df_to_dendropy_tree(\n df,\n taxon_col='uid',\n taxon_annotations=[],\n node_col='uid',\n node_annotations=[],\n branch_lengths=True,\n ):\n \"\"\"Turn a phylopandas dataframe into a dendropy tree.\n\n Parameters\n ----------\n df : DataFrame\n DataFrame containi... | import pandas
import dendropy
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filename : str
File to write {} string to. If no filename is given, a {} string
will be returned.
taxon_col : str (default='sequence')
Sequence column name in Da... |
Zsailer/phylopandas | phylopandas/treeio/write.py | _write_method | python | def _write_method(schema):
def method(
self,
filename=None,
schema=schema,
taxon_col='uid',
taxon_annotations=[],
node_col='uid',
node_annotations=[],
branch_lengths=True,
**kwargs):
# Use generic write class to write data.
retu... | Add a write method for named schema to a class. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/write.py#L185-L212 | [
"def _write_doc_template(schema):\n s = \"\"\"Write to {} format.\n\n Parameters\n ----------\n filename : str\n File to write {} string to. If no filename is given, a {} string\n will be returned.\n\n taxon_col : str (default='sequence')\n Sequence column name in DataFrame.\n\n ... | import pandas
import dendropy
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filename : str
File to write {} string to. If no filename is given, a {} string
will be returned.
taxon_col : str (default='sequence')
Sequence column name in Da... |
Zsailer/phylopandas | phylopandas/treeio/write.py | _write_function | python | def _write_function(schema):
def func(
data,
filename=None,
schema=schema,
taxon_col='uid',
taxon_annotations=[],
node_col='uid',
node_annotations=[],
branch_lengths=True,
**kwargs):
# Use generic write class to write data.
retu... | Add a write method for named schema to a class. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/treeio/write.py#L215-L242 | [
"def _write_doc_template(schema):\n s = \"\"\"Write to {} format.\n\n Parameters\n ----------\n filename : str\n File to write {} string to. If no filename is given, a {} string\n will be returned.\n\n taxon_col : str (default='sequence')\n Sequence column name in DataFrame.\n\n ... | import pandas
import dendropy
def _write_doc_template(schema):
s = """Write to {} format.
Parameters
----------
filename : str
File to write {} string to. If no filename is given, a {} string
will be returned.
taxon_col : str (default='sequence')
Sequence column name in Da... |
Zsailer/phylopandas | phylopandas/utils.py | get_random_id | python | def get_random_id(length):
alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits
return ''.join(random.choice(alphabet) for _ in range(length)) | Generate a random, alpha-numerical id. | train | https://github.com/Zsailer/phylopandas/blob/f163c4a2b9369eb32f6c8f3793f711f6fe4e6130/phylopandas/utils.py#L4-L7 | null | import random
import string
|
nyergler/hieroglyph | src/hieroglyph/directives.py | filter_doctree_for_slides | python | def filter_doctree_for_slides(doctree):
current = 0
num_children = len(doctree.children)
while current < num_children:
child = doctree.children[current]
child.replace_self(
child.traverse(no_autoslides_filter)
)
if len(doctree.children) == num_children:
... | Given a doctree, remove all non-slide related elements from it. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/directives.py#L309-L326 | null | from docutils import nodes
from sphinx.util.nodes import set_source_info
from docutils.nodes import SkipNode
from docutils.parsers.rst import Directive, directives
from docutils.parsers.rst.directives import (
admonitions,
)
from docutils.parsers.rst.roles import set_classes
from docutils.transforms import Transfo... |
nyergler/hieroglyph | src/hieroglyph/directives.py | TransformNextSlides._make_title_node | python | def _make_title_node(self, node, increment=True):
parent_title_node = node.parent.next_node(nodes.title)
nextslide_info = getattr(
parent_title_node, 'nextslide_info',
(parent_title_node.deepcopy().children, 1),
)
nextslide_info = (
nextslide_info[0],... | Generate a new title node for ``node``.
``node`` is a ``nextslide`` node. The title will use the node's
parent's title, or the title specified as an argument. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/directives.py#L137-L177 | null | class TransformNextSlides(Transform):
default_priority = 550
def apply(self, *args, **kwargs):
app = self.document.settings.env.app
from hieroglyph import builder
is_slides = builder.building_slides(app)
return self.apply_to_document(
self.document,
... |
nyergler/hieroglyph | src/hieroglyph/directives.py | slideconf.apply | python | def apply(self, builder):
if 'theme' in self.attributes:
builder.apply_theme(
self.attributes['theme'],
builder.theme_options,
) | Apply the Slide Configuration to a Builder. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/directives.py#L217-L224 | null | class slideconf(nodes.Element):
def restore(self, builder):
"""Restore the previous Slide Configuration for the Builder."""
if 'theme' in self.attributes:
builder.pop_theme()
@classmethod
def get(cls, doctree):
"""Return the first slideconf node for the doctree."""
... |
nyergler/hieroglyph | src/hieroglyph/directives.py | slideconf.get_conf | python | def get_conf(cls, builder, doctree=None):
# set up the default conf
result = {
'theme': builder.config.slide_theme,
'autoslides': builder.config.autoslides,
'slide_classes': [],
}
# now look for a slideconf node in the doctree and update the conf
... | Return a dictionary of slide configuration for this doctree. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/directives.py#L241-L257 | [
"def get(cls, doctree):\n \"\"\"Return the first slideconf node for the doctree.\"\"\"\n\n conf_nodes = doctree.traverse(cls)\n if conf_nodes:\n return conf_nodes[0]\n"
] | class slideconf(nodes.Element):
def apply(self, builder):
"""Apply the Slide Configuration to a Builder."""
if 'theme' in self.attributes:
builder.apply_theme(
self.attributes['theme'],
builder.theme_options,
)
def restore(self, builder)... |
nyergler/hieroglyph | src/hieroglyph/slides.py | __fix_context | python | def __fix_context(context):
COPY_LISTS = ('script_files', 'css_files',)
for attr in COPY_LISTS:
if attr in context:
context[attr] = context[attr][:]
return context | Return a new context dict based on original context.
The new context will be a copy of the original, and some mutable
members (such as script and css files) will also be copied to
prevent polluting shared context. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/slides.py#L4-L18 | null | from hieroglyph.builder import building_slides
def get_extra_pages(app):
"""
"""
result = []
context = app.builder.globalcontext
for context_key in context:
if context_key.startswith('theme_extra_pages_'):
page_name = context_key.split('theme_extra_pages_')[-1]
... |
nyergler/hieroglyph | src/hieroglyph/quickstart.py | ask_user | python | def ask_user(d):
# Print welcome message
msg = bold('Welcome to the Hieroglyph %s quickstart utility.') % (
version(),
)
print(msg)
msg = """
This will ask questions for creating a Hieroglyph project, and then ask
some basic Sphinx questions.
"""
print(msg)
# set a few defaults tha... | Wrap sphinx.quickstart.ask_user, and add additional questions. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/quickstart.py#L16-L76 | [
"def version():\n \"\"\"Return the installed package version.\"\"\"\n\n import pkg_resources\n\n return pkg_resources.get_distribution('hieroglyph').version\n"
] | from __future__ import print_function
from __future__ import absolute_import
from argparse import ArgumentParser
import datetime
import os
import pkg_resources
from sphinx import version_info as sphinx_version_info
import sphinx.quickstart
from sphinx.util.console import bold
from hieroglyph import version
def qu... |
nyergler/hieroglyph | src/hieroglyph/writer.py | SlideData.get_slide_context | python | def get_slide_context(self):
return {
'title': self.title,
'level': self.level,
'content': self.content,
'classes': self.classes,
'slide_classes': self._filter_classes(exclude='content-'),
'content_classes': self._filter_classes(include='c... | Return the context dict for rendering this slide. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/writer.py#L83-L96 | [
"def _filter_classes(self, include=None, exclude=None):\n\n classes = self.classes[:]\n if include is not None:\n classes = [\n c[len(include):] for c in classes\n if c.startswith(include)\n ]\n\n if exclude is not None:\n classes = [\n c for c in class... | class SlideData(object):
def __init__(self, translator, **kwargs):
self._translator = translator
self.level = 0
self.title = ''
self.content = ''
self.classes = []
self.slide_number = 0
self.id = ''
for name, value in kwargs.items():
se... |
nyergler/hieroglyph | src/hieroglyph/writer.py | BaseSlideTranslator._add_slide_number | python | def _add_slide_number(self, slide_no):
if self.builder.config.slide_numbers:
self.body.append(
'\n<div class="slide-no">%s</div>\n' % (slide_no,),
) | Add the slide number to the output if enabled. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/writer.py#L127-L133 | null | class BaseSlideTranslator(HTMLTranslator):
def __init__(self, *args, **kwargs):
HTMLTranslator.__init__(self, *args, **kwargs)
self.section_count = 0
self.body_stack = []
self.current_slide = None
self.slide_data = []
def push_body(self):
"""Push the current b... |
nyergler/hieroglyph | src/hieroglyph/writer.py | BaseSlideTranslator._add_slide_footer | python | def _add_slide_footer(self, slide_no):
if self.builder.config.slide_footer:
self.body.append(
'\n<div class="slide-footer">%s</div>\n' % (
self.builder.config.slide_footer,
),
) | Add the slide footer to the output if enabled. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/writer.py#L135-L143 | null | class BaseSlideTranslator(HTMLTranslator):
def __init__(self, *args, **kwargs):
HTMLTranslator.__init__(self, *args, **kwargs)
self.section_count = 0
self.body_stack = []
self.current_slide = None
self.slide_data = []
def push_body(self):
"""Push the current b... |
nyergler/hieroglyph | src/hieroglyph/html.py | inspect_config | python | def inspect_config(app):
# avoid import cycles :/
from hieroglyph import writer
# only reconfigure Sphinx if we're generating HTML
if app.builder.name not in HTML_BUILDERS:
return
if app.config.slide_link_html_to_slides:
# add the slide theme dir as a Loader
app.builder.t... | Inspect the Sphinx configuration and update for slide-linking.
If links from HTML to slides are enabled, make sure the sidebar
configuration includes the template and add the necessary theme
directory as a loader so the sidebar template can be located.
If the sidebar configuration already includes ``s... | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/html.py#L12-L89 | null | """Support for interacting with HTML builds."""
import os
import sphinx
from sphinx.jinja2glue import SphinxFileSystemLoader
HTML_BUILDERS = ('html', 'dirhtml', 'singlehtml',)
SLIDELINK_TEMPLATE = 'slidelink.html'
def slide_path(builder, pagename=None):
"""Calculate the relative path to the Slides for pagenam... |
nyergler/hieroglyph | src/hieroglyph/html.py | slide_path | python | def slide_path(builder, pagename=None):
return builder.get_relative_uri(
pagename or builder.current_docname,
os.path.join(
builder.app.config.slide_relative_path,
pagename or builder.current_docname,
)) | Calculate the relative path to the Slides for pagename. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/html.py#L92-L100 | null | """Support for interacting with HTML builds."""
import os
import sphinx
from sphinx.jinja2glue import SphinxFileSystemLoader
HTML_BUILDERS = ('html', 'dirhtml', 'singlehtml',)
SLIDELINK_TEMPLATE = 'slidelink.html'
def inspect_config(app):
"""Inspect the Sphinx configuration and update for slide-linking.
I... |
nyergler/hieroglyph | src/hieroglyph/html.py | html_path | python | def html_path(builder, pagename=None):
return builder.get_relative_uri(
pagename or builder.current_docname,
os.path.join(
builder.app.config.slide_html_relative_path,
pagename or builder.current_docname,
)) | Calculate the relative path to the Slides for pagename. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/html.py#L103-L111 | null | """Support for interacting with HTML builds."""
import os
import sphinx
from sphinx.jinja2glue import SphinxFileSystemLoader
HTML_BUILDERS = ('html', 'dirhtml', 'singlehtml',)
SLIDELINK_TEMPLATE = 'slidelink.html'
def inspect_config(app):
"""Inspect the Sphinx configuration and update for slide-linking.
I... |
nyergler/hieroglyph | src/hieroglyph/html.py | add_link | python | def add_link(app, pagename, templatename, context, doctree):
# we can only show the slidelink if we can resolve the filename
context['show_slidelink'] = (
app.config.slide_link_html_to_slides and
hasattr(app.builder, 'get_outfilename')
)
if context['show_slidelink']:
context['s... | Add the slides link to the HTML context. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/html.py#L114-L124 | [
"def slide_path(builder, pagename=None):\n \"\"\"Calculate the relative path to the Slides for pagename.\"\"\"\n\n return builder.get_relative_uri(\n pagename or builder.current_docname,\n os.path.join(\n builder.app.config.slide_relative_path,\n pagename or builder.current... | """Support for interacting with HTML builds."""
import os
import sphinx
from sphinx.jinja2glue import SphinxFileSystemLoader
HTML_BUILDERS = ('html', 'dirhtml', 'singlehtml',)
SLIDELINK_TEMPLATE = 'slidelink.html'
def inspect_config(app):
"""Inspect the Sphinx configuration and update for slide-linking.
I... |
nyergler/hieroglyph | src/hieroglyph/builder.py | AbstractSlideBuilder.apply_theme | python | def apply_theme(self, themename, themeoptions):
# push the existing values onto the Stack
self._theme_stack.append(
(self.theme, self.theme_options)
)
theme_factory = HTMLThemeFactory(self.app)
theme_factory.load_additional_themes(self.get_builtin_theme_dirs() + sel... | Apply a new theme to the document.
This will store the existing theme configuration and apply a new one. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/builder.py#L82-L103 | [
"def load_additional_themes(self, paths):\n Theme.init_themes(self.app.confdir, paths)\n",
"def create(self, themename):\n return Theme(themename)\n",
"def get_builtin_theme_dirs(self):\n\n return [\n os.path.join(os.path.dirname(__file__), 'themes',)\n ]\n"
] | class AbstractSlideBuilder(object):
format = 'slides'
add_permalinks = False
default_translator_class = writer.SlideTranslator
def init_translator_class(self):
"""Compatibility shim to support versions of Sphinx prior to 1.6."""
self.translator_class = self.default_translator_class
... |
nyergler/hieroglyph | src/hieroglyph/builder.py | AbstractSlideBuilder.post_process_images | python | def post_process_images(self, doctree):
super(AbstractSlideBuilder, self).post_process_images(doctree)
# figure out where this doctree is in relation to the srcdir
relative_base = (
['..'] *
doctree.attributes.get('source')[len(self.srcdir) + 1:].count('/')
)
... | Pick the best candidate for all image URIs. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/builder.py#L145-L167 | null | class AbstractSlideBuilder(object):
format = 'slides'
add_permalinks = False
default_translator_class = writer.SlideTranslator
def init_translator_class(self):
"""Compatibility shim to support versions of Sphinx prior to 1.6."""
self.translator_class = self.default_translator_class
... |
nyergler/hieroglyph | src/hieroglyph/themes/slides2/static/scripts/md/render.py | parse_metadata | python | def parse_metadata(section):
metadata = {}
metadata_lines = section.split('\n')
for line in metadata_lines:
colon_index = line.find(':')
if colon_index != -1:
key = line[:colon_index].strip()
val = line[colon_index + 1:].strip()
metadata[key] = val
return metadata | Given the first part of a slide, returns metadata associated with it. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/themes/slides2/static/scripts/md/render.py#L36-L47 | null | #!/usr/bin/env python
import codecs
import re
import jinja2
import markdown
def process_slides():
with codecs.open('../../presentation-output.html', 'w', encoding='utf8') as outfile:
md = codecs.open('slides.md', encoding='utf8').read()
md_slides = md.split('\n---\n')
print('Compiled %s slides.' % len(m... |
nyergler/hieroglyph | src/hieroglyph/themes/slides2/static/scripts/md/render.py | postprocess_html | python | def postprocess_html(html, metadata):
if metadata.get('build_lists') and metadata['build_lists'] == 'true':
html = html.replace('<ul>', '<ul class="build">')
html = html.replace('<ol>', '<ol class="build">')
return html | Returns processed HTML to fit into the slide template format. | train | https://github.com/nyergler/hieroglyph/blob/1ef062fad5060006566f8d6bd3b5a231ac7e0488/src/hieroglyph/themes/slides2/static/scripts/md/render.py#L49-L54 | null | #!/usr/bin/env python
import codecs
import re
import jinja2
import markdown
def process_slides():
with codecs.open('../../presentation-output.html', 'w', encoding='utf8') as outfile:
md = codecs.open('slides.md', encoding='utf8').read()
md_slides = md.split('\n---\n')
print('Compiled %s slides.' % len(m... |
idlesign/torrentool | torrentool/cli.py | info | python | def info(torrent_path):
my_torrent = Torrent.from_file(torrent_path)
size = my_torrent.total_size
click.secho('Name: %s' % my_torrent.name, fg='blue')
click.secho('Files:')
for file_tuple in my_torrent.files:
click.secho(file_tuple.name)
click.secho('Hash: %s' % my_torrent.info_hash,... | Print out information from .torrent file. | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/cli.py#L25-L39 | [
"def humanize_filesize(bytes_size):\n \"\"\"Returns human readable filesize.\n\n :param int bytes_size:\n :rtype: str\n \"\"\"\n if not bytes_size:\n return '0 B'\n\n names = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')\n\n name_idx = int(math.floor(math.log(bytes_size, 1024)))\... | from __future__ import division
import click
from os import path, getcwd
from . import VERSION
from .api import Torrent
from .utils import humanize_filesize, upload_to_cache_server, get_open_trackers_from_remote, \
get_open_trackers_from_local
from .exceptions import RemoteUploadError, RemoteDownloadError
@click... |
idlesign/torrentool | torrentool/cli.py | create | python | def create(source, dest, tracker, open_trackers, comment, cache):
source_title = path.basename(source).replace('.', '_').replace(' ', '_')
dest = '%s.torrent' % path.join(dest, source_title)
click.secho('Creating torrent from %s ...' % source)
my_torrent = Torrent.create_from(source)
if comment:... | Create torrent file from a single file or a directory. | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/cli.py#L49-L90 | [
"def upload_to_cache_server(fpath):\n \"\"\"Uploads .torrent file to a cache server.\n\n Returns upload file URL.\n\n :rtype: str\n \"\"\"\n url_base = 'http://torrage.info'\n url_upload = '%s/autoupload.php' % url_base\n url_download = '%s/torrent.php?h=' % url_base\n file_field = 'torrent'... | from __future__ import division
import click
from os import path, getcwd
from . import VERSION
from .api import Torrent
from .utils import humanize_filesize, upload_to_cache_server, get_open_trackers_from_remote, \
get_open_trackers_from_local
from .exceptions import RemoteUploadError, RemoteDownloadError
@click... |
idlesign/torrentool | torrentool/torrent.py | Torrent.files | python | def files(self):
files = []
info = self._struct.get('info')
if not info:
return files
if 'files' in info:
base = info['name']
for f in info['files']:
files.append(TorrentFile(join(base, *f['path']), f['length']))
else:
... | Files in torrent.
List of namedtuples (filepath, size).
:rtype: list[TorrentFile] | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L108-L130 | null | class Torrent(object):
"""Represents a torrent file, and exposes utilities to work with it."""
_filepath = None
def __init__(self, dict_struct=None):
dict_struct = dict_struct or {'info': {}}
self._struct = dict_struct
def __str__(self):
return 'Torrent: %s' % self.name
a... |
idlesign/torrentool | torrentool/torrent.py | Torrent.info_hash | python | def info_hash(self):
info = self._struct.get('info')
if not info:
return None
return sha1(Bencode.encode(info)).hexdigest() | Hash of torrent file info section. Also known as torrent hash. | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L138-L145 | [
"def encode(cls, value):\n \"\"\"Encodes a value into bencoded bytes.\n\n :param value: Python object to be encoded (str, int, list, dict).\n :param str val_encoding: Encoding used by strings in a given object.\n :rtype: bytes\n \"\"\"\n val_encoding = 'utf-8'\n\n def encode_str(v):\n tr... | class Torrent(object):
"""Represents a torrent file, and exposes utilities to work with it."""
_filepath = None
def __init__(self, dict_struct=None):
dict_struct = dict_struct or {'info': {}}
self._struct = dict_struct
def __str__(self):
return 'Torrent: %s' % self.name
a... |
idlesign/torrentool | torrentool/torrent.py | Torrent.announce_urls | python | def announce_urls(self):
urls = self._struct.get('announce-list')
if not urls:
urls = self._struct.get('announce')
if not urls:
return []
urls = [[urls]]
return urls | List of lists of announce (tracker) URLs.
First inner list is considered as primary announcers list,
the following lists as back-ups.
http://bittorrent.org/beps/bep_0012.html | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L153-L170 | [
"def set_single(val):\n del self._struct['announce-list']\n self._struct['announce'] = val\n"
] | class Torrent(object):
"""Represents a torrent file, and exposes utilities to work with it."""
_filepath = None
def __init__(self, dict_struct=None):
dict_struct = dict_struct or {'info': {}}
self._struct = dict_struct
def __str__(self):
return 'Torrent: %s' % self.name
a... |
idlesign/torrentool | torrentool/torrent.py | Torrent.get_magnet | python | def get_magnet(self, detailed=True):
result = 'magnet:?xt=urn:btih:' + self.info_hash
def add_tr():
urls = self.announce_urls
if not urls:
return
trackers = []
urls = urls[0] # Only primary announcers are enough.
for url in ... | Returns torrent magnet link, consisting of BTIH (BitTorrent Info Hash) URN
anr optional other information.
:param bool|list|tuple|set detailed:
For boolean - whether additional info (such as trackers) should be included.
For iterable - expected allowed parameter names:
... | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L246-L298 | null | class Torrent(object):
"""Represents a torrent file, and exposes utilities to work with it."""
_filepath = None
def __init__(self, dict_struct=None):
dict_struct = dict_struct or {'info': {}}
self._struct = dict_struct
def __str__(self):
return 'Torrent: %s' % self.name
a... |
idlesign/torrentool | torrentool/torrent.py | Torrent.to_file | python | def to_file(self, filepath=None):
if filepath is None and self._filepath is None:
raise TorrentError('Unable to save torrent to file: no filepath supplied.')
if filepath is not None:
self._filepath = filepath
with open(self._filepath, mode='wb') as f:
f.writ... | Writes Torrent object into file, either
:param filepath: | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L300-L312 | [
"def to_string(self):\n \"\"\"Returns bytes representing torrent file.\n\n :param str encoding: Encoding used by strings in Torrent object.\n :rtype: bytearray\n \"\"\"\n return Bencode.encode(self._struct)\n"
] | class Torrent(object):
"""Represents a torrent file, and exposes utilities to work with it."""
_filepath = None
def __init__(self, dict_struct=None):
dict_struct = dict_struct or {'info': {}}
self._struct = dict_struct
def __str__(self):
return 'Torrent: %s' % self.name
a... |
idlesign/torrentool | torrentool/torrent.py | Torrent.create_from | python | def create_from(cls, src_path):
is_dir = isdir(src_path)
target_files, size_data = cls._get_target_files_info(src_path)
SIZE_MIN = 32768 # 32 KiB
SIZE_DEFAULT = 262144 # 256 KiB
SIZE_MAX = 1048576 # 1 MiB
CHUNKS_MIN = 1000 # todo use those limits as advised
... | Returns Torrent object created from a file or a directory.
:param str src_path:
:rtype: Torrent | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L348-L416 | [
"def get_app_version():\n \"\"\"Returns full version string including application name\n suitable for putting into Torrent.created_by.\n\n \"\"\"\n from torrentool import VERSION\n return 'torrentool/%s' % '.'.join(map(str, VERSION))\n",
"def _get_target_files_info(cls, src_path):\n src_path = u... | class Torrent(object):
"""Represents a torrent file, and exposes utilities to work with it."""
_filepath = None
def __init__(self, dict_struct=None):
dict_struct = dict_struct or {'info': {}}
self._struct = dict_struct
def __str__(self):
return 'Torrent: %s' % self.name
a... |
idlesign/torrentool | torrentool/torrent.py | Torrent.from_file | python | def from_file(cls, filepath):
torrent = cls(Bencode.read_file(filepath))
torrent._filepath = filepath
return torrent | Alternative constructor to get Torrent object from file.
:param str filepath:
:rtype: Torrent | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/torrent.py#L428-L436 | [
"def read_file(cls, filepath):\n \"\"\"Decodes bencoded data of a given file.\n\n Returns decoded structure(s).\n\n :param str filepath:\n :rtype: list\n \"\"\"\n with open(filepath, mode='rb') as f:\n contents = f.read()\n return cls.decode(contents)\n"
] | class Torrent(object):
"""Represents a torrent file, and exposes utilities to work with it."""
_filepath = None
def __init__(self, dict_struct=None):
dict_struct = dict_struct or {'info': {}}
self._struct = dict_struct
def __str__(self):
return 'Torrent: %s' % self.name
a... |
idlesign/torrentool | torrentool/utils.py | humanize_filesize | python | def humanize_filesize(bytes_size):
if not bytes_size:
return '0 B'
names = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
name_idx = int(math.floor(math.log(bytes_size, 1024)))
size = round(bytes_size / math.pow(1024, name_idx), 2)
return '%s %s' % (size, names[name_idx]) | Returns human readable filesize.
:param int bytes_size:
:rtype: str | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/utils.py#L20-L34 | null | import math
from os import path
from .exceptions import RemoteUploadError, RemoteDownloadError
OPEN_TRACKERS_FILENAME = 'open_trackers.ini'
REMOTE_TIMEOUT = 4
def get_app_version():
"""Returns full version string including application name
suitable for putting into Torrent.created_by.
"""
from tor... |
idlesign/torrentool | torrentool/utils.py | upload_to_cache_server | python | def upload_to_cache_server(fpath):
url_base = 'http://torrage.info'
url_upload = '%s/autoupload.php' % url_base
url_download = '%s/torrent.php?h=' % url_base
file_field = 'torrent'
try:
import requests
response = requests.post(url_upload, files={file_field: open(fpath, 'rb')}, time... | Uploads .torrent file to a cache server.
Returns upload file URL.
:rtype: str | train | https://github.com/idlesign/torrentool/blob/78c474c2ecddbad2e3287b390ac8a043957f3563/torrentool/utils.py#L37-L61 | null | import math
from os import path
from .exceptions import RemoteUploadError, RemoteDownloadError
OPEN_TRACKERS_FILENAME = 'open_trackers.ini'
REMOTE_TIMEOUT = 4
def get_app_version():
"""Returns full version string including application name
suitable for putting into Torrent.created_by.
"""
from tor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.