_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q234600 | Tile.from_google | train | def from_google(cls, google_x, google_y, zoom):
"""Creates a tile from Google format X Y and zoom"""
max_tile = (2 ** zoom) - 1
assert 0 <= google_x <= max_tile, 'Google X needs to be a value between 0 and (2^zoom) -1.'
assert 0 <= google_y <= max_tile, 'Google Y needs to be a value betw... | python | {
"resource": ""
} |
q234601 | Tile.for_point | train | def for_point(cls, point, zoom):
"""Creates a tile for given point"""
latitude, longitude = point.latitude_longitude
return cls.for_latitude_longitude(latitude=latitude, longitude=longitude, zoom=zoom) | python | {
"resource": ""
} |
q234602 | Tile.quad_tree | train | def quad_tree(self):
"""Gets the tile in the Microsoft QuadTree format, converted from TMS"""
value = ''
tms_x, tms_y = self.tms
tms_y = (2 ** self.zoom - 1) - tms_y
for i in range(self.zoom, 0, -1):
digit = 0
mask = 1 << (i - 1)
if (tms_x & ma... | python | {
"resource": ""
} |
q234603 | Tile.google | train | def google(self):
"""Gets the tile in the Google format, converted from TMS"""
tms_x, tms_y = self.tms
return tms_x, (2 ** self.zoom - 1) - tms_y | python | {
"resource": ""
} |
q234604 | Tile.bounds | train | def bounds(self):
"""Gets the bounds of a tile represented as the most west and south point and the most east and north point"""
google_x, google_y = self.google
pixel_x_west, pixel_y_north = google_x * TILE_SIZE, google_y * TILE_SIZE
pixel_x_east, pixel_y_south = (google_x + 1) * TILE_S... | python | {
"resource": ""
} |
q234605 | read_ix | train | def read_ix(ix, **kwargs):
"""Read timeseries data from an ixmp object
Parameters
----------
ix: ixmp.TimeSeries or ixmp.Scenario
this option requires the ixmp package as a dependency
kwargs: arguments passed to ixmp.TimeSeries.timeseries()
"""
if not isinstance(ix, ixmp.TimeSeries)... | python | {
"resource": ""
} |
q234606 | requires_package | train | def requires_package(pkg, msg, error_type=ImportError):
"""Decorator when a function requires an optional dependency
Parameters
----------
pkg : imported package object
msg : string
Message to show to user with error_type
error_type : python error class
"""
def _requires_package... | python | {
"resource": ""
} |
q234607 | write_sheet | train | def write_sheet(writer, name, df, index=False):
"""Write a pandas DataFrame to an ExcelWriter,
auto-formatting column width depending on maxwidth of data and colum header
Parameters
----------
writer: pandas.ExcelWriter
an instance of a pandas ExcelWriter
name: string
name of th... | python | {
"resource": ""
} |
q234608 | read_pandas | train | def read_pandas(fname, *args, **kwargs):
"""Read a file and return a pd.DataFrame"""
if not os.path.exists(fname):
raise ValueError('no data file `{}` found!'.format(fname))
if fname.endswith('csv'):
df = pd.read_csv(fname, *args, **kwargs)
else:
xl = pd.ExcelFile(fname)
... | python | {
"resource": ""
} |
q234609 | sort_data | train | def sort_data(data, cols):
"""Sort `data` rows and order columns"""
return data.sort_values(cols)[cols + ['value']].reset_index(drop=True) | python | {
"resource": ""
} |
q234610 | _escape_regexp | train | def _escape_regexp(s):
"""escape characters with specific regexp use"""
return (
str(s)
.replace('|', '\\|')
.replace('.', '\.') # `.` has to be replaced before `*`
.replace('*', '.*')
.replace('+', '\+')
.replace('(', '\(')
.replace(')', '\)')
.r... | python | {
"resource": ""
} |
q234611 | years_match | train | def years_match(data, years):
"""
matching of year columns for data filtering
"""
years = [years] if isinstance(years, int) else years
dt = datetime.datetime
if isinstance(years, dt) or isinstance(years[0], dt):
error_msg = "`year` can only be filtered with ints or lists of ints"
... | python | {
"resource": ""
} |
q234612 | hour_match | train | def hour_match(data, hours):
"""
matching of days in time columns for data filtering
"""
hours = [hours] if isinstance(hours, int) else hours
return data.isin(hours) | python | {
"resource": ""
} |
q234613 | datetime_match | train | def datetime_match(data, dts):
"""
matching of datetimes in time columns for data filtering
"""
dts = dts if islistable(dts) else [dts]
if any([not isinstance(i, datetime.datetime) for i in dts]):
error_msg = (
"`time` can only be filtered by datetimes"
)
raise Ty... | python | {
"resource": ""
} |
q234614 | to_int | train | def to_int(x, index=False):
"""Formatting series or timeseries columns to int and checking validity.
If `index=False`, the function works on the `pd.Series x`; else,
the function casts the index of `x` to int and returns x with a new index.
"""
_x = x.index if index else x
cols = list(map(int, _... | python | {
"resource": ""
} |
q234615 | concat_with_pipe | train | def concat_with_pipe(x, cols=None):
"""Concatenate a `pd.Series` separated by `|`, drop `None` or `np.nan`"""
cols = cols or x.index
return '|'.join([x[i] for i in cols if x[i] not in [None, np.nan]]) | python | {
"resource": ""
} |
q234616 | _make_index | train | def _make_index(df, cols=META_IDX):
"""Create an index from the columns of a dataframe"""
return pd.MultiIndex.from_tuples(
pd.unique(list(zip(*[df[col] for col in cols]))), names=tuple(cols)) | python | {
"resource": ""
} |
q234617 | check_aggregate | train | def check_aggregate(df, variable, components=None, exclude_on_fail=False,
multiplier=1, **kwargs):
"""Check whether the timeseries values match the aggregation
of sub-categories
Parameters
----------
df: IamDataFrame instance
args: see IamDataFrame.check_aggregate() for deta... | python | {
"resource": ""
} |
q234618 | filter_by_meta | train | def filter_by_meta(data, df, join_meta=False, **kwargs):
"""Filter by and join meta columns from an IamDataFrame to a pd.DataFrame
Parameters
----------
data: pd.DataFrame instance
DataFrame to which meta columns are to be joined,
index or columns must include `['model', 'scenario']`
... | python | {
"resource": ""
} |
q234619 | compare | train | def compare(left, right, left_label='left', right_label='right',
drop_close=True, **kwargs):
"""Compare the data in two IamDataFrames and return a pd.DataFrame
Parameters
----------
left, right: IamDataFrames
the IamDataFrames to be compared
left_label, right_label: str, default... | python | {
"resource": ""
} |
q234620 | concat | train | def concat(dfs):
"""Concatenate a series of `pyam.IamDataFrame`-like objects together"""
if isstr(dfs) or not hasattr(dfs, '__iter__'):
msg = 'Argument must be a non-string iterable (e.g., list or tuple)'
raise TypeError(msg)
_df = None
for df in dfs:
df = df if isinstance(df, I... | python | {
"resource": ""
} |
q234621 | IamDataFrame.variables | train | def variables(self, include_units=False):
"""Get a list of variables
Parameters
----------
include_units: boolean, default False
include the units
"""
if include_units:
return self.data[['variable', 'unit']].drop_duplicates()\
.res... | python | {
"resource": ""
} |
q234622 | IamDataFrame.append | train | def append(self, other, ignore_meta_conflict=False, inplace=False,
**kwargs):
"""Append any castable object to this IamDataFrame.
Columns in `other.meta` that are not in `self.meta` are always merged,
duplicate region-variable-unit-year rows raise a ValueError.
Parameters... | python | {
"resource": ""
} |
q234623 | IamDataFrame.pivot_table | train | def pivot_table(self, index, columns, values='value',
aggfunc='count', fill_value=None, style=None):
"""Returns a pivot table
Parameters
----------
index: str or list of strings
rows for Pivot table
columns: str or list of strings
colu... | python | {
"resource": ""
} |
q234624 | IamDataFrame.as_pandas | train | def as_pandas(self, with_metadata=False):
"""Return this as a pd.DataFrame
Parameters
----------
with_metadata : bool, default False or dict
if True, join data with all meta columns; if a dict, discover
meaningful meta columns from values (in key-value)
"""... | python | {
"resource": ""
} |
q234625 | IamDataFrame._new_meta_column | train | def _new_meta_column(self, name):
"""Add a column to meta if it doesn't exist, set to value `np.nan`"""
if name is None:
raise ValueError('cannot add a meta column `{}`'.format(name))
if name not in self.meta:
self.meta[name] = np.nan | python | {
"resource": ""
} |
q234626 | IamDataFrame.convert_unit | train | def convert_unit(self, conversion_mapping, inplace=False):
"""Converts units based on provided unit conversion factors
Parameters
----------
conversion_mapping: dict
for each unit for which a conversion should be carried out,
provide current unit and target unit ... | python | {
"resource": ""
} |
q234627 | IamDataFrame.normalize | train | def normalize(self, inplace=False, **kwargs):
"""Normalize data to a given value. Currently only supports normalizing
to a specific time.
Parameters
----------
inplace: bool, default False
if True, do operation inplace and return None
kwargs: the values on wh... | python | {
"resource": ""
} |
q234628 | IamDataFrame.aggregate | train | def aggregate(self, variable, components=None, append=False):
"""Compute the aggregate of timeseries components or sub-categories
Parameters
----------
variable: str
variable for which the aggregate should be computed
components: list of str, default None
... | python | {
"resource": ""
} |
q234629 | IamDataFrame.check_aggregate | train | def check_aggregate(self, variable, components=None, exclude_on_fail=False,
multiplier=1, **kwargs):
"""Check whether a timeseries matches the aggregation of its components
Parameters
----------
variable: str
variable to be checked for matching aggreg... | python | {
"resource": ""
} |
q234630 | IamDataFrame.aggregate_region | train | def aggregate_region(self, variable, region='World', subregions=None,
components=None, append=False):
"""Compute the aggregate of timeseries over a number of regions
including variable components only defined at the `region` level
Parameters
----------
v... | python | {
"resource": ""
} |
q234631 | IamDataFrame.check_aggregate_region | train | def check_aggregate_region(self, variable, region='World', subregions=None,
components=None, exclude_on_fail=False,
**kwargs):
"""Check whether the region timeseries data match the aggregation
of components
Parameters
-------... | python | {
"resource": ""
} |
q234632 | IamDataFrame.check_internal_consistency | train | def check_internal_consistency(self, **kwargs):
"""Check whether the database is internally consistent
We check that all variables are equal to the sum of their sectoral
components and that all the regions add up to the World total. If
the check is passed, None is returned, otherwise a ... | python | {
"resource": ""
} |
q234633 | IamDataFrame._apply_filters | train | def _apply_filters(self, **filters):
"""Determine rows to keep in data for given set of filters
Parameters
----------
filters: dict
dictionary of filters ({col: values}}); uses a pseudo-regexp syntax
by default, but accepts `regexp: True` to use regexp directly
... | python | {
"resource": ""
} |
q234634 | IamDataFrame.col_apply | train | def col_apply(self, col, func, *args, **kwargs):
"""Apply a function to a column
Parameters
----------
col: string
column in either data or metadata
func: functional
function to apply
"""
if col in self.data:
self.data[col] = s... | python | {
"resource": ""
} |
q234635 | IamDataFrame._to_file_format | train | def _to_file_format(self, iamc_index):
"""Return a dataframe suitable for writing to a file"""
df = self.timeseries(iamc_index=iamc_index).reset_index()
df = df.rename(columns={c: str(c).title() for c in df.columns})
return df | python | {
"resource": ""
} |
q234636 | IamDataFrame.to_csv | train | def to_csv(self, path, iamc_index=False, **kwargs):
"""Write timeseries data to a csv file
Parameters
----------
path: string
file path
iamc_index: bool, default False
if True, use `['model', 'scenario', 'region', 'variable', 'unit']`;
else, u... | python | {
"resource": ""
} |
q234637 | IamDataFrame.to_excel | train | def to_excel(self, excel_writer, sheet_name='data',
iamc_index=False, **kwargs):
"""Write timeseries data to Excel format
Parameters
----------
excel_writer: string or ExcelWriter object
file path or existing ExcelWriter
sheet_name: string, default '... | python | {
"resource": ""
} |
q234638 | IamDataFrame.export_metadata | train | def export_metadata(self, path):
"""Export metadata to Excel
Parameters
----------
path: string
path/filename for xlsx file of metadata export
"""
writer = pd.ExcelWriter(path)
write_sheet(writer, 'meta', self.meta, index=True)
writer.save() | python | {
"resource": ""
} |
q234639 | IamDataFrame.load_metadata | train | def load_metadata(self, path, *args, **kwargs):
"""Load metadata exported from `pyam.IamDataFrame` instance
Parameters
----------
path: string
xlsx file with metadata exported from `pyam.IamDataFrame` instance
"""
if not os.path.exists(path):
rais... | python | {
"resource": ""
} |
q234640 | IamDataFrame.line_plot | train | def line_plot(self, x='year', y='value', **kwargs):
"""Plot timeseries lines of existing data
see pyam.plotting.line_plot() for all available options
"""
df = self.as_pandas(with_metadata=kwargs)
# pivot data if asked for explicit variable name
variables = df['variable'... | python | {
"resource": ""
} |
q234641 | IamDataFrame.stack_plot | train | def stack_plot(self, *args, **kwargs):
"""Plot timeseries stacks of existing data
see pyam.plotting.stack_plot() for all available options
"""
df = self.as_pandas(with_metadata=True)
ax = plotting.stack_plot(df, *args, **kwargs)
return ax | python | {
"resource": ""
} |
q234642 | IamDataFrame.scatter | train | def scatter(self, x, y, **kwargs):
"""Plot a scatter chart using metadata columns
see pyam.plotting.scatter() for all available options
"""
variables = self.data['variable'].unique()
xisvar = x in variables
yisvar = y in variables
if not xisvar and not yisvar:
... | python | {
"resource": ""
} |
q234643 | RunControl.update | train | def update(self, rc):
"""Add additional run control parameters
Parameters
----------
rc : string, file, dictionary, optional
a path to a YAML file, a file handle for a YAML file, or a
dictionary describing run control configuration
"""
rc = self._... | python | {
"resource": ""
} |
q234644 | RunControl.recursive_update | train | def recursive_update(self, k, d):
"""Recursively update a top-level option in the run control
Parameters
----------
k : string
the top-level key
d : dictionary or similar
the dictionary to use for updating
"""
u = self.__getitem__(k)
... | python | {
"resource": ""
} |
q234645 | Connection.available_metadata | train | def available_metadata(self):
"""
List all scenario metadata indicators available in the connected
data source
"""
url = self.base_url + 'metadata/types'
headers = {'Authorization': 'Bearer {}'.format(self.auth())}
r = requests.get(url, headers=headers)
re... | python | {
"resource": ""
} |
q234646 | Connection.metadata | train | def metadata(self, default=True):
"""
Metadata of scenarios in the connected data source
Parameter
---------
default : bool, optional, default True
Return *only* the default version of each Scenario.
Any (`model`, `scenario`) without a default version is ... | python | {
"resource": ""
} |
q234647 | Connection.variables | train | def variables(self):
"""All variables in the connected data source"""
url = self.base_url + 'ts'
headers = {'Authorization': 'Bearer {}'.format(self.auth())}
r = requests.get(url, headers=headers)
df = pd.read_json(r.content, orient='records')
return pd.Series(df['variabl... | python | {
"resource": ""
} |
q234648 | Connection.query | train | def query(self, **kwargs):
"""
Query the data source, subselecting data. Available keyword arguments
include
- model
- scenario
- region
- variable
Example
-------
```
Connection.query(model='MESSAGE', scenario='SSP2*',
... | python | {
"resource": ""
} |
q234649 | Statistics.reindex | train | def reindex(self, copy=True):
"""Reindex the summary statistics dataframe"""
ret = deepcopy(self) if copy else self
ret.stats = ret.stats.reindex(index=ret._idx, level=0)
if ret.idx_depth == 2:
ret.stats = ret.stats.reindex(index=ret._sub_idx, level=1)
if ret.rows is... | python | {
"resource": ""
} |
q234650 | Statistics.summarize | train | def summarize(self, center='mean', fullrange=None, interquartile=None,
custom_format='{:.2f}'):
"""Format the compiled statistics to a concise string output
Parameter
---------
center : str, default `mean`
what to return as 'center' of the summary: `mean`, ... | python | {
"resource": ""
} |
q234651 | reset_default_props | train | def reset_default_props(**kwargs):
"""Reset properties to initial cycle point"""
global _DEFAULT_PROPS
pcycle = plt.rcParams['axes.prop_cycle']
_DEFAULT_PROPS = {
'color': itertools.cycle(_get_standard_colors(**kwargs))
if len(kwargs) > 0 else itertools.cycle([x['color'] for x in pcycle]... | python | {
"resource": ""
} |
q234652 | default_props | train | def default_props(reset=False, **kwargs):
"""Return current default properties
Parameters
----------
reset : bool
if True, reset properties and return
default: False
"""
global _DEFAULT_PROPS
if _DEFAULT_PROPS is None or reset:
reset_default_props(**kwargs)
... | python | {
"resource": ""
} |
q234653 | assign_style_props | train | def assign_style_props(df, color=None, marker=None, linestyle=None,
cmap=None):
"""Assign the style properties for a plot
Parameters
----------
df : pd.DataFrame
data to be used for style properties
"""
if color is None and cmap is not None:
raise ValueErr... | python | {
"resource": ""
} |
q234654 | reshape_line_plot | train | def reshape_line_plot(df, x, y):
"""Reshape data from long form to "line plot form".
Line plot form has x value as the index with one column for each line.
Each column has data points as values and all metadata as column headers.
"""
idx = list(df.columns.drop(y))
if df.duplicated(idx).any():
... | python | {
"resource": ""
} |
q234655 | reshape_bar_plot | train | def reshape_bar_plot(df, x, y, bars):
"""Reshape data from long form to "bar plot form".
Bar plot form has x value as the index with one column for bar grouping.
Table values come from y values.
"""
idx = [bars, x]
if df.duplicated(idx).any():
warnings.warn('Duplicated index found.')
... | python | {
"resource": ""
} |
q234656 | read_shapefile | train | def read_shapefile(fname, region_col=None, **kwargs):
"""Read a shapefile for use in regional plots. Shapefiles must have a
column denoted as "region".
Parameters
----------
fname : string
path to shapefile to be read by geopandas
region_col : string, default None
if provided, r... | python | {
"resource": ""
} |
q234657 | add_net_values_to_bar_plot | train | def add_net_values_to_bar_plot(axs, color='k'):
"""Add net values next to an existing vertical stacked bar chart
Parameters
----------
axs : matplotlib.Axes or list thereof
color : str, optional, default: black
the color of the bars to add
"""
axs = axs if isinstance(axs, Iterable) ... | python | {
"resource": ""
} |
q234658 | scatter | train | def scatter(df, x, y, ax=None, legend=None, title=None,
color=None, marker='o', linestyle=None, cmap=None,
groupby=['model', 'scenario'], with_lines=False, **kwargs):
"""Plot data as a scatter chart.
Parameters
----------
df : pd.DataFrame
Data to plot as a long-form dat... | python | {
"resource": ""
} |
q234659 | logger | train | def logger():
"""Access global logger"""
global _LOGGER
if _LOGGER is None:
logging.basicConfig()
_LOGGER = logging.getLogger()
_LOGGER.setLevel('INFO')
return _LOGGER | python | {
"resource": ""
} |
q234660 | NodeBalancerConfig.nodes | train | def nodes(self):
"""
This is a special derived_class relationship because NodeBalancerNode is the
only api object that requires two parent_ids
"""
if not hasattr(self, '_nodes'):
base_url = "{}/{}".format(NodeBalancerConfig.api_endpoint, NodeBalancerNode.derived_url_p... | python | {
"resource": ""
} |
q234661 | Volume.attach | train | def attach(self, to_linode, config=None):
"""
Attaches this Volume to the given Linode
"""
result = self._client.post('{}/attach'.format(Volume.api_endpoint), model=self,
data={
"linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_lin... | python | {
"resource": ""
} |
q234662 | Volume.detach | train | def detach(self):
"""
Detaches this Volume if it is attached
"""
self._client.post('{}/detach'.format(Volume.api_endpoint), model=self)
return True | python | {
"resource": ""
} |
q234663 | Volume.resize | train | def resize(self, size):
"""
Resizes this Volume
"""
result = self._client.post('{}/resize'.format(Volume.api_endpoint, model=self,
data={ "size": size }))
self._populate(result.json)
return True | python | {
"resource": ""
} |
q234664 | Volume.clone | train | def clone(self, label):
"""
Clones this volume to a new volume in the same region with the given label
:param label: The label for the new volume.
:returns: The new volume object.
"""
result = self._client.post('{}/clone'.format(Volume.api_endpoint),
mod... | python | {
"resource": ""
} |
q234665 | Tag._get_raw_objects | train | def _get_raw_objects(self):
"""
Helper function to populate the first page of raw objects for this tag.
This has the side effect of creating the ``_raw_objects`` attribute of
this object.
"""
if not hasattr(self, '_raw_objects'):
result = self._client.get(type... | python | {
"resource": ""
} |
q234666 | Tag.objects | train | def objects(self):
"""
Returns a list of objects with this Tag. This list may contain any
taggable object type.
"""
data = self._get_raw_objects()
return PaginatedList.make_paginated_list(data, self._client, TaggedObjectProxy,
... | python | {
"resource": ""
} |
q234667 | TaggedObjectProxy.make_instance | train | def make_instance(cls, id, client, parent_id=None, json=None):
"""
Overrides Base's ``make_instance`` to allow dynamic creation of objects
based on the defined type in the response json.
:param cls: The class this was called on
:param id: The id of the instance to create
... | python | {
"resource": ""
} |
q234668 | Disk.resize | train | def resize(self, new_size):
"""
Resizes this disk. The Linode Instance this disk belongs to must have
sufficient space available to accommodate the new size, and must be
offline.
**NOTE** If resizing a disk down, the filesystem on the disk must still
fit on the new disk... | python | {
"resource": ""
} |
q234669 | Config._populate | train | def _populate(self, json):
"""
Map devices more nicely while populating.
"""
from .volume import Volume
DerivedBase._populate(self, json)
devices = {}
for device_index, device in json['devices'].items():
if not device:
devices[device_... | python | {
"resource": ""
} |
q234670 | Instance.ips | train | def ips(self):
"""
The ips related collection is not normalized like the others, so we have to
make an ad-hoc object to return for its response
"""
if not hasattr(self, '_ips'):
result = self._client.get("{}/ips".format(Instance.api_endpoint), model=self)
... | python | {
"resource": ""
} |
q234671 | Instance.available_backups | train | def available_backups(self):
"""
The backups response contains what backups are available to be restored.
"""
if not hasattr(self, '_avail_backups'):
result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self)
if not 'automatic' in result:
... | python | {
"resource": ""
} |
q234672 | Instance.invalidate | train | def invalidate(self):
""" Clear out cached properties """
if hasattr(self, '_avail_backups'):
del self._avail_backups
if hasattr(self, '_ips'):
del self._ips
Base.invalidate(self) | python | {
"resource": ""
} |
q234673 | Instance.config_create | train | def config_create(self, kernel=None, label=None, devices=[], disks=[],
volumes=[], **kwargs):
"""
Creates a Linode Config with the given attributes.
:param kernel: The kernel to boot with.
:param label: The config label
:param disks: The list of disks, starting at sd... | python | {
"resource": ""
} |
q234674 | Instance.enable_backups | train | def enable_backups(self):
"""
Enable Backups for this Instance. When enabled, we will automatically
backup your Instance's data so that it can be restored at a later date.
For more information on Instance's Backups service and pricing, see our
`Backups Page`_
.. _Backup... | python | {
"resource": ""
} |
q234675 | Instance.mutate | train | def mutate(self):
"""
Upgrades this Instance to the latest generation type
"""
self._client.post('{}/mutate'.format(Instance.api_endpoint), model=self)
return True | python | {
"resource": ""
} |
q234676 | Instance.initiate_migration | train | def initiate_migration(self):
"""
Initiates a pending migration that is already scheduled for this Linode
Instance
"""
self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self) | python | {
"resource": ""
} |
q234677 | Instance.clone | train | def clone(self, to_linode=None, region=None, service=None, configs=[], disks=[],
label=None, group=None, with_backups=None):
""" Clones this linode into a new linode or into a new linode in the given region """
if to_linode and region:
raise ValueError('You may only specify one o... | python | {
"resource": ""
} |
q234678 | Instance.stats | train | def stats(self):
"""
Returns the JSON stats for this Instance
"""
# TODO - this would be nicer if we formatted the stats
return self._client.get('{}/stats'.format(Instance.api_endpoint), model=self) | python | {
"resource": ""
} |
q234679 | Instance.stats_for | train | def stats_for(self, dt):
"""
Returns stats for the month containing the given datetime
"""
# TODO - this would be nicer if we formatted the stats
if not isinstance(dt, datetime):
raise TypeError('stats_for requires a datetime object!')
return self._client.get(... | python | {
"resource": ""
} |
q234680 | StackScript._populate | train | def _populate(self, json):
"""
Override the populate method to map user_defined_fields to
fancy values
"""
Base._populate(self, json)
mapped_udfs = []
for udf in self.user_defined_fields:
t = UserDefinedFieldType.text
choices = None
... | python | {
"resource": ""
} |
q234681 | InvoiceItem._populate | train | def _populate(self, json):
"""
Allows population of "from_date" from the returned "from" attribute which
is a reserved word in python. Also populates "to_date" to be complete.
"""
super(InvoiceItem, self)._populate(json)
self.from_date = datetime.strptime(json['from'], ... | python | {
"resource": ""
} |
q234682 | OAuthClient.reset_secret | train | def reset_secret(self):
"""
Resets the client secret for this client.
"""
result = self._client.post("{}/reset_secret".format(OAuthClient.api_endpoint), model=self)
if not 'id' in result:
raise UnexpectedResponseError('Unexpected response when resetting secret!', jso... | python | {
"resource": ""
} |
q234683 | OAuthClient.thumbnail | train | def thumbnail(self, dump_to=None):
"""
This returns binary data that represents a 128x128 image.
If dump_to is given, attempts to write the image to a file
at the given location.
"""
headers = {
"Authorization": "token {}".format(self._client.token)
}
... | python | {
"resource": ""
} |
q234684 | OAuthClient.set_thumbnail | train | def set_thumbnail(self, thumbnail):
"""
Sets the thumbnail for this OAuth Client. If thumbnail is bytes,
uploads it as a png. Otherwise, assumes thumbnail is a path to the
thumbnail and reads it in as bytes before uploading.
"""
headers = {
"Authorization": ... | python | {
"resource": ""
} |
q234685 | User.grants | train | def grants(self):
"""
Retrieves the grants for this user. If the user is unrestricted, this
will result in an ApiError. This is smart, and will only fetch from the
api once unless the object is invalidated.
:returns: The grants for this user.
:rtype: linode.objects.acc... | python | {
"resource": ""
} |
q234686 | Base.save | train | def save(self):
"""
Send this object's mutable values to the server in a PUT request
"""
resp = self._client.put(type(self).api_endpoint, model=self,
data=self._serialize())
if 'error' in resp:
return False
return True | python | {
"resource": ""
} |
q234687 | Base.delete | train | def delete(self):
"""
Sends a DELETE request for this object
"""
resp = self._client.delete(type(self).api_endpoint, model=self)
if 'error' in resp:
return False
self.invalidate()
return True | python | {
"resource": ""
} |
q234688 | Base.invalidate | train | def invalidate(self):
"""
Invalidates all non-identifier Properties this object has locally,
causing the next access to re-fetch them from the server
"""
for key in [k for k in type(self).properties.keys()
if not type(self).properties[k].identifier]:
s... | python | {
"resource": ""
} |
q234689 | Base._serialize | train | def _serialize(self):
"""
A helper method to build a dict of all mutable Properties of
this object
"""
result = { a: getattr(self, a) for a in type(self).properties
if type(self).properties[a].mutable }
for k, v in result.items():
if isinstance(v,... | python | {
"resource": ""
} |
q234690 | Base._api_get | train | def _api_get(self):
"""
A helper method to GET this object from the server
"""
json = self._client.get(type(self).api_endpoint, model=self)
self._populate(json) | python | {
"resource": ""
} |
q234691 | Base._populate | train | def _populate(self, json):
"""
A helper method that, given a JSON object representing this object,
assigns values based on the properties dict and the attributes of
its Properties.
"""
if not json:
return
# hide the raw JSON away in case someone needs... | python | {
"resource": ""
} |
q234692 | Base.make | train | def make(id, client, cls, parent_id=None, json=None):
"""
Makes an api object based on an id and class.
:param id: The id of the object to create
:param client: The LinodeClient to give the new object
:param cls: The class type to instantiate
:param parent_id: The parent... | python | {
"resource": ""
} |
q234693 | Base.make_instance | train | def make_instance(cls, id, client, parent_id=None, json=None):
"""
Makes an instance of the class this is called on and returns it.
The intended usage is:
instance = Linode.make_instance(123, client, json=response)
:param cls: The class this was called on.
:param id: ... | python | {
"resource": ""
} |
q234694 | IPAddress.to | train | def to(self, linode):
"""
This is a helper method for ip-assign, and should not be used outside
of that context. It's used to cleanly build an IP Assign request with
pretty python syntax.
"""
from .linode import Instance
if not isinstance(linode, Instance):
... | python | {
"resource": ""
} |
q234695 | ProfileGroup.token_create | train | def token_create(self, label=None, expiry=None, scopes=None, **kwargs):
"""
Creates and returns a new Personal Access Token
"""
if label:
kwargs['label'] = label
if expiry:
if isinstance(expiry, datetime):
expiry = datetime.strftime(expiry,... | python | {
"resource": ""
} |
q234696 | ProfileGroup.ssh_key_upload | train | def ssh_key_upload(self, key, label):
"""
Uploads a new SSH Public Key to your profile This key can be used in
later Linode deployments.
:param key: The ssh key, or a path to the ssh key. If a path is provided,
the file at the path must exist and be readable or an ... | python | {
"resource": ""
} |
q234697 | LongviewGroup.client_create | train | def client_create(self, label=None):
"""
Creates a new LongviewClient, optionally with a given label.
:param label: The label for the new client. If None, a default label based
on the new client's ID will be used.
:returns: A new LongviewClient
:raises ApiError: I... | python | {
"resource": ""
} |
q234698 | AccountGroup.events_mark_seen | train | def events_mark_seen(self, event):
"""
Marks event as the last event we have seen. If event is an int, it is treated
as an event_id, otherwise it should be an event object whose id will be used.
"""
last_seen = event if isinstance(event, int) else event.id
self.client.po... | python | {
"resource": ""
} |
q234699 | AccountGroup.settings | train | def settings(self):
"""
Resturns the account settings data for this acocunt. This is not a
listing endpoint.
"""
result = self.client.get('/account/settings')
if not 'managed' in result:
raise UnexpectedResponseError('Unexpected response when getting accoun... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.