text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Return a list of the existing tables in a database
<END_TASK>
<USER_TASK:>
Description:
def tables_(self) -> list:
"""Return a list of the existing tables in a database
:return: list of the table names
:rtype: list
:example: ``tables = ds.tables_()``
""" |
if self._check_db() == False:
return
try:
return self._tables()
except Exception as e:
self.err(e, "Can not print tables") |
<SYSTEM_TASK:>
Extracts the value of the expand query string parameter from a request.
<END_TASK>
<USER_TASK:>
Description:
def parse_requested_expands(query_key, request):
"""
Extracts the value of the expand query string parameter from a request.
Supports comma separated lists.
:param query_key: The name query string parameter.
:param request: Request instance.
:return: List of strings representing the values of the expand query string value.
""" |
requested_expands = []
for key, val in request.params.items():
if key == query_key:
requested_expands += val.split(',')
return requested_expands |
<SYSTEM_TASK:>
Factory and permission are likely only going to exist until I have enough time
<END_TASK>
<USER_TASK:>
Description:
def register(self, prefix, viewset, basename, factory=None, permission=None):
"""
Factory and permission are likely only going to exist until I have enough time
to write a permissions module for PRF.
:param prefix: the uri route prefix.
:param viewset: The ViewSet class to route.
:param basename: Used to name the route in pyramid.
:param factory: Optional, root factory to be used as the context to the route.
:param permission: Optional, permission to assign the route.
""" |
lookup = self.get_lookup(viewset)
routes = self.get_routes(viewset)
for route in routes:
# Only actions which actually exist on the viewset will be bound
mapping = self.get_method_map(viewset, route.mapping)
if not mapping:
continue # empty viewset
url = route.url.format(
prefix=prefix,
lookup=lookup,
trailing_slash=self.trailing_slash
)
view = viewset.as_view(mapping, **route.initkwargs)
name = route.name.format(basename=basename)
if factory:
self.configurator.add_route(name, url, factory=factory)
else:
self.configurator.add_route(name, url)
self.configurator.add_view(view, route_name=name, permission=permission) |
<SYSTEM_TASK:>
Augment `self.routes` with any dynamically generated routes.
<END_TASK>
<USER_TASK:>
Description:
def get_routes(self, viewset):
"""
Augment `self.routes` with any dynamically generated routes.
Returns a list of the Route namedtuple.
""" |
known_actions = list(flatten([route.mapping.values() for route in self.routes if isinstance(route, Route)]))
# Determine any `@detail_route` or `@list_route` decorated methods on the viewset
detail_routes = []
list_routes = []
for methodname in dir(viewset):
attr = getattr(viewset, methodname)
httpmethods = getattr(attr, 'bind_to_methods', None)
detail = getattr(attr, 'detail', True)
if httpmethods:
# check against know actions list
if methodname in known_actions:
raise ImproperlyConfigured('Cannot use @detail_route or @list_route '
'decorators on method "%s" '
'as it is an existing route'.format(methodname))
httpmethods = [method.lower() for method in httpmethods]
if detail:
detail_routes.append((httpmethods, methodname))
else:
list_routes.append((httpmethods, methodname))
def _get_dynamic_routes(route, dynamic_routes):
ret = []
for httpmethods, methodname in dynamic_routes:
method_kwargs = getattr(viewset, methodname).kwargs
initkwargs = route.initkwargs.copy()
initkwargs.update(method_kwargs)
url_path = initkwargs.pop("url_path", None) or methodname
ret.append(Route(
url=replace_methodname(route.url, url_path),
mapping={httpmethod: methodname for httpmethod in httpmethods},
name=replace_methodname(route.name, url_path),
initkwargs=initkwargs,
))
return ret
ret = []
for route in self.routes:
if isinstance(route, DynamicDetailRoute):
# Dynamic detail routes (@detail_route decorator)
ret += _get_dynamic_routes(route, detail_routes)
elif isinstance(route, DynamicListRoute):
# Dynamic list routes (@list_route decorator)
ret += _get_dynamic_routes(route, list_routes)
else:
# Standard route
ret.append(route)
return ret |
<SYSTEM_TASK:>
Given a viewset, and a mapping of http methods to actions, return a new mapping which only
<END_TASK>
<USER_TASK:>
Description:
def get_method_map(self, viewset, method_map):
"""
Given a viewset, and a mapping of http methods to actions, return a new mapping which only
includes any mappings that are actually implemented by the viewset.
""" |
bound_methods = {}
for method, action in method_map.items():
if hasattr(viewset, action):
bound_methods[method] = action
return bound_methods |
<SYSTEM_TASK:>
Prepare the incoming request, checking to see the request is sending
<END_TASK>
<USER_TASK:>
Description:
def prepare(self):
"""Prepare the incoming request, checking to see the request is sending
JSON content in the request body. If so, the content is decoded and
assigned to the json_arguments attribute.
""" |
super(RequestHandler, self).prepare()
if self.request.headers.get('content-type', '').startswith(self.JSON):
self.request.body = escape.json_decode(self.request.body) |
<SYSTEM_TASK:>
Writes the given chunk to the output buffer. Checks for curl in the
<END_TASK>
<USER_TASK:>
Description:
def write(self, chunk):
"""Writes the given chunk to the output buffer. Checks for curl in the
user-agent and if set, provides indented output if returning JSON.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set
the Content-Type of the response to be ``application/json``.
(if you want to send JSON as a different ``Content-Type``, call
set_header *after* calling write()).
:param mixed chunk: The string or dict to write to the client
""" |
if self._finished:
raise RuntimeError("Cannot write() after finish(). May be caused "
"by using async operations without the "
"@asynchronous decorator.")
if isinstance(chunk, dict):
options = {'ensure_ascii': False}
if 'curl' in self.request.headers.get('user-agent'):
options['indent'] = 2
options['sort_keys'] = True
chunk = json.dumps(chunk, **options).replace("</", "<\\/") + '\n'
self.set_header("Content-Type", "application/json; charset=UTF-8")
self._write_buffer.append(web.utf8(chunk)) |
<SYSTEM_TASK:>
Called by Tornado when the request is done. Update the session data
<END_TASK>
<USER_TASK:>
Description:
def on_finish(self):
"""Called by Tornado when the request is done. Update the session data
and remove the session object.
""" |
super(SessionRequestHandler, self).on_finish()
LOGGER.debug('Entering SessionRequestHandler.on_finish: %s',
self.session.id)
self.session.last_request_at = self.current_epoch()
self.session.last_request_uri = self.request.uri
if self.session.dirty:
result = yield self.session.save()
LOGGER.debug('on_finish yield save: %r', result)
self.session = None
LOGGER.debug('Exiting SessionRequestHandler.on_finish: %r',
self.session) |
<SYSTEM_TASK:>
Prepare the session, setting up the session object and loading in
<END_TASK>
<USER_TASK:>
Description:
def prepare(self):
"""Prepare the session, setting up the session object and loading in
the values, assigning the IP address to the session if it's an new one.
""" |
super(SessionRequestHandler, self).prepare()
result = yield gen.Task(self.start_session)
LOGGER.debug('Exiting SessionRequestHandler.prepare: %r', result) |
<SYSTEM_TASK:>
Return an instance of the proper session object.
<END_TASK>
<USER_TASK:>
Description:
def _session_start(self):
"""Return an instance of the proper session object.
:rtype: Session
""" |
return self._session_class(self._session_id,
self._session_duration,
self._session_settings) |
<SYSTEM_TASK:>
Renames a column in the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def rename(self, source_col: str, dest_col: str):
"""
Renames a column in the main dataframe
:param source_col: name of the column to rename
:type source_col: str
:param dest_col: new name of the column
:type dest_col: str
:example: ``ds.rename("Col 1", "New col")``
""" |
try:
self.df = self.df.rename(columns={source_col: dest_col})
except Exception as e:
self.err(e, self.rename, "Can not rename column")
return
self.ok("Column", source_col, "renamed") |
<SYSTEM_TASK:>
Add a column with default values
<END_TASK>
<USER_TASK:>
Description:
def add(self, col: str, value):
"""
Add a column with default values
:param col: column name
:type col: str
:param value: column value
:type value: any
:example: ``ds.add("Col 4", 0)``
""" |
try:
self.df[col] = value
except Exception as e:
self.err(e, self.add, "Can not add column") |
<SYSTEM_TASK:>
Returns a dataswim instance with a dataframe limited
<END_TASK>
<USER_TASK:>
Description:
def keep_(self, *cols) -> "Ds":
"""
Returns a dataswim instance with a dataframe limited
to some columns
:param cols: names of the columns
:type cols: str
:return: a dataswim instance
:rtype: Ds
:example: ``ds2 = ds.keep_("Col 1", "Col 2")``
""" |
try:
ds2 = self._duplicate_(self.df[list(cols)])
except Exception as e:
self.err(e, "Can not remove colums")
return
self.ok("Columns", " ,".join(cols), "kept")
return ds2 |
<SYSTEM_TASK:>
Limit the dataframe to some columns
<END_TASK>
<USER_TASK:>
Description:
def keep(self, *cols):
"""
Limit the dataframe to some columns
:param cols: names of the columns
:type cols: str
:example: ``ds.keep("Col 1", "Col 2")``
""" |
try:
self.df = self.df[list(cols)]
except Exception as e:
self.err(e, "Can not remove colums")
return
self.ok("Setting dataframe to columns", " ".join(cols)) |
<SYSTEM_TASK:>
Drops columns from the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def drop(self, *cols):
"""
Drops columns from the main dataframe
:param cols: names of the columns
:type cols: str
:example: ``ds.drop("Col 1", "Col 2")``
""" |
try:
index = self.df.columns.values
for col in cols:
if col not in index:
self.warning("Column", col, "not found. Aborting")
return
self.df = self.df.drop(col, axis=1)
except Exception as e:
self.err(e, self.drop, "Can not drop column") |
<SYSTEM_TASK:>
Delete rows based on value
<END_TASK>
<USER_TASK:>
Description:
def exclude(self, col: str, val):
"""
Delete rows based on value
:param col: column name
:type col: str
:param val: value to delete
:type val: any
:example: ``ds.exclude("Col 1", "value")``
""" |
try:
self.df = self.df[self.df[col] != val]
except Exception as e:
self.err(e, "Can not exclude rows based on value " + str(val)) |
<SYSTEM_TASK:>
Copy a columns values in another column
<END_TASK>
<USER_TASK:>
Description:
def copycol(self, origin_col: str, dest_col: str):
"""
Copy a columns values in another column
:param origin_col: name of the column to copy
:type origin_col: str
:param dest_col: name of the new column
:type dest_col: str
:example: ``ds.copy("col 1", "New col")``
""" |
try:
self.df[dest_col] = self.df[[origin_col]]
except Exception as e:
self.err(e, self.copy_col, "Can not copy column") |
<SYSTEM_TASK:>
Add a column from the index
<END_TASK>
<USER_TASK:>
Description:
def indexcol(self, col: str):
"""
Add a column from the index
:param col: name of the new column
:type col: str
:example: ``ds.index_col("New col")``
""" |
try:
self.df[col] = self.df.index.values
except Exception as e:
self.err(e)
return
self.ok("Column", col, "added from the index") |
<SYSTEM_TASK:>
In the project settings set up the variable
<END_TASK>
<USER_TASK:>
Description:
def get_article_placeholders(self, article):
"""
In the project settings set up the variable
CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = {
'include': [ 'slot1', 'slot2', etc. ],
'exclude': [ 'slot3', 'slot4', etc. ],
}
or leave it empty
CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST = {}
""" |
placeholders_search_list = getattr(settings, 'CMS_ARTICLES_PLACEHOLDERS_SEARCH_LIST', {})
included = placeholders_search_list.get('include', [])
excluded = placeholders_search_list.get('exclude', [])
diff = set(included) - set(excluded)
if diff:
return article.placeholders.filter(slot__in=diff)
elif excluded:
return article.placeholders.exclude(slot__in=excluded)
else:
return article.placeholders.all() |
<SYSTEM_TASK:>
Insert one or many records in the database from a dictionary or a list of dictionaries
<END_TASK>
<USER_TASK:>
Description:
def insert(self, table, records, create_cols=False, dtypes=None):
"""
Insert one or many records in the database from a dictionary or a list of dictionaries
""" |
if self._check_db() is False:
return
try:
table = self.db[table]
except Exception as e:
self.err(e, "Can not find table " + table)
t = type(records)
if t == dict:
func = table.insert
elif t == list:
func = table.insert_many
else:
msg = "Rows datatype " + \
str(t) + " not valid: use a list or a dictionary"
self.err(msg)
if create_cols is True:
try:
func(records, ensure=True, types=dtypes)
except Exception as e:
self.err(e, "Can not insert create columns and insert data")
return
else:
try:
func(records, types=dtypes)
except Exception as e:
self.err(e, "Can not insert data")
return
self.ok("Rows inserted in the database") |
<SYSTEM_TASK:>
Upsert a record in a table
<END_TASK>
<USER_TASK:>
Description:
def upsert(self, table: str, record: dict, create_cols: bool=False,
dtypes: list=None, pks=["id"], namefields=["id"]):
"""
Upsert a record in a table
""" |
try:
self.db[table].upsert(record, pks, create_cols, dtypes)
except Exception as e:
self.err(e, "Can not upsert data")
return
names = ""
for el in namefields:
names += " " + record[el]
self.ok("Upserted record"+names) |
<SYSTEM_TASK:>
Update records in a database table from the main dataframe
<END_TASK>
<USER_TASK:>
Description:
def update_table(self, table, pks=['id']):
"""
Update records in a database table from the main dataframe
""" |
if self._check_db() is False:
return
try:
table = self.db[table]
except Exception as e:
self.err(e, "Can not find table " + table)
if self.db is None:
msg = "Please connect a database before or provide a database url"
self.err(msg)
return
recs = self.to_records_()
for rec in recs:
table.insert_ignore(rec, pks, ensure=True)
self.ok("Data updated in table", table) |
<SYSTEM_TASK:>
Save the main dataframe to the database
<END_TASK>
<USER_TASK:>
Description:
def to_db(self, table, dtypes=None):
"""
Save the main dataframe to the database
""" |
if self._check_db() is False:
return
if table not in self.db.tables:
self.db.create_table(table)
self.info("Created table ", table)
self.start("Saving data to database table " + table + " ...")
recs = self.to_records_()
self.insert(table, recs, dtypes)
self.end("Data inserted in table", table) |
<SYSTEM_TASK:>
Returns a Seaborn models residuals chart
<END_TASK>
<USER_TASK:>
Description:
def residual_(self, label=None, style=None, opts=None):
"""
Returns a Seaborn models residuals chart
""" |
color, _ = self._get_color_size(style)
try:
fig = sns.residplot(self.df[self.x], self.df[self.y],
lowess=True, color=color)
fig = self._set_with_height(fig, opts)
return fig
except Exception as e:
self.err(e, self.residual_,
"Can not draw models residuals chart") |
<SYSTEM_TASK:>
Returns a Seaborn density chart
<END_TASK>
<USER_TASK:>
Description:
def _density_seaborn_(self, label=None, style=None, opts=None):
"""
Returns a Seaborn density chart
""" |
try:
fig = sns.kdeplot(self.df[self.x], self.df[self.y])
fig = self._set_with_height(fig, opts)
return fig
except Exception as e:
self.err(e, self.density_,
"Can not draw density chart") |
<SYSTEM_TASK:>
Returns a Seaborn distribution chart
<END_TASK>
<USER_TASK:>
Description:
def _distrib_seaborn_(self, label=None, style=None, opts=None):
"""
Returns a Seaborn distribution chart
""" |
try:
kde = False
rug = True
if "kde" in opts:
kde = opts["kde"]
rug = opts["rug"]
fig = sns.distplot(self.df[self.x], kde=kde, rug=rug)
fig = self._set_with_height(fig, opts)
return fig
except Exception as e:
self.err(e, self.distrib_,
"Can not draw distribution chart") |
<SYSTEM_TASK:>
Returns a Seaborn linear regression plot
<END_TASK>
<USER_TASK:>
Description:
def _linear_seaborn_(self, label=None, style=None, opts=None):
"""
Returns a Seaborn linear regression plot
""" |
xticks, yticks = self._get_ticks(opts)
try:
fig = sns.lmplot(self.x, self.y, data=self.df)
fig = self._set_with_height(fig, opts)
return fig
except Exception as e:
self.err(e, self.linear_,
"Can not draw linear regression chart") |
<SYSTEM_TASK:>
Returns a Seaborn linear regression plot with marginal distribution
<END_TASK>
<USER_TASK:>
Description:
def _dlinear_seaborn_(self, label=None, style=None, opts=None):
"""
Returns a Seaborn linear regression plot with marginal distribution
""" |
color, size = self._get_color_size(style)
try:
fig = sns.jointplot(self.x, self.y, color=color,
size=size, data=self.df, kind="reg")
fig = self._set_with_height(fig, opts)
return fig
except Exception as e:
self.err(e, self.dlinear_,
"Can not draw linear regression chart with distribution") |
<SYSTEM_TASK:>
Get a Seaborn bar chart
<END_TASK>
<USER_TASK:>
Description:
def seaborn_bar_(self, label=None, style=None, opts=None):
"""
Get a Seaborn bar chart
""" |
try:
fig = sns.barplot(self.x, self.y, palette="BuGn_d")
return fig
except Exception as e:
self.err(e, self.seaborn_bar_,
"Can not get Seaborn bar chart object") |
<SYSTEM_TASK:>
Initialialize for chart rendering
<END_TASK>
<USER_TASK:>
Description:
def _get_opts_seaborn(self, opts, style):
"""
Initialialize for chart rendering
""" |
if opts is None:
if self.chart_opts is None:
opts = {}
else:
opts = self.chart_opts
if style is None:
if self.chart_style is None:
style = self.chart_style
else:
style = {}
return opts, style |
<SYSTEM_TASK:>
Get an Seaborn chart object
<END_TASK>
<USER_TASK:>
Description:
def _get_seaborn_chart(self, xfield, yfield, chart_type, label,
_opts=None, _style=None, **kwargs):
"""
Get an Seaborn chart object
""" |
plt.figure()
try:
opts, style = self._get_opts_seaborn(_opts, _style)
except Exception as e:
self.err(e, "Can not get chart options")
return
# params
# opts["xfield"] = xfield
# opts["yfield"] = yfield
# opts["dataobj"] = self.df
opts["chart_type"] = chart_type
self.x = xfield
self.y = yfield
# generate
try:
if chart_type == "dlinear":
chart_obj = self._dlinear_seaborn_(label, style, opts)
elif chart_type == "linear":
chart_obj = self._linear_seaborn_(label, style, opts)
elif chart_type == "distribution":
chart_obj = self._distrib_seaborn_(label, style, opts)
elif chart_type == "density":
chart_obj = self._density_seaborn_(label, style, opts)
elif chart_type == "residual":
chart_obj = self.residual_(label, style, opts)
elif chart_type == "bar":
chart_obj = self.seaborn_bar_(label, style, opts)
else:
self.err(self._get_seaborn_chart, "Chart type " +
chart_type + " not supported with Seaborn")
return
except Exception as e:
self.err(e, self._get_seaborn_chart,
"Can not get Seaborn chart object")
return
return chart_obj |
<SYSTEM_TASK:>
Check if xticks and yticks are set
<END_TASK>
<USER_TASK:>
Description:
def _get_ticks(self, opts):
"""
Check if xticks and yticks are set
""" |
opts, _ = self._get_opts(opts, None)
if "xticks" not in opts:
if "xticks" not in self.chart_opts:
self.err(self.dlinear_,
"Please set the xticks option for this chart to work")
return
else:
xticks = self.chart_opts["xticks"]
else:
xticks = opts["xticks"]
if "yticks" not in opts:
if "yticks"not in self.chart_opts:
self.err(self.dlinear_,
"Please set the yticks option for this chart to work")
return
else:
yticks = self.chart_opts["yticks"]
else:
yticks = opts["yticks"]
return xticks, yticks |
<SYSTEM_TASK:>
Get color and size from a style dict
<END_TASK>
<USER_TASK:>
Description:
def _get_color_size(self, style):
"""
Get color and size from a style dict
""" |
color = "b"
if "color" in style:
color = style["color"]
size = 7
if "size" in style:
size = style["size"]
return color, size |
<SYSTEM_TASK:>
Set the width and height of a Matplotlib figure
<END_TASK>
<USER_TASK:>
Description:
def _set_with_height(self, fig, opts):
"""
Set the width and height of a Matplotlib figure
""" |
h = 5
if "height" in opts:
h = opts["height"]
w = 12
if "width" in opts:
w = opts["width"]
try:
fig.figure.set_size_inches((w, h))
return fig
except Exception:
try:
fig.fig.set_size_inches((w, h))
return fig
except Exception as e:
self.err(e, self._set_with_height,
"Can not set figure width and height from chart object") |
<SYSTEM_TASK:>
Saves a png image of the seaborn chart
<END_TASK>
<USER_TASK:>
Description:
def _save_seaborn_chart(self, report, folderpath):
"""
Saves a png image of the seaborn chart
""" |
if folderpath is None:
if self.imgs_path is None:
self.err(self._save_seaborn_chart,
"Please set a path where to save images: ds.imgs_path"
" = '/my/path'")
return
path = self.imgs_path
else:
path = folderpath
path = path + "/" + report["slug"] + ".png"
try:
try:
# print("*** TRY", report["seaborn_chart"].figure.show())
fig = report["seaborn_chart"].figure
fig.savefig(path)
except Exception as e:
try:
fig = report["seaborn_chart"]
fig.savefig(path)
except Exception:
plot = report["seaborn_chart"]
plot = plot.get_figure()
plot.savefig(path)
except Exception as e:
self.err(e, self._save_seaborn_chart, "Can not save Seaborn chart")
return
if self.autoprint is True:
self.ok("Seaborn chart writen to " + path) |
<SYSTEM_TASK:>
Registers a dimension on this cube.
<END_TASK>
<USER_TASK:>
Description:
def register_dimension(self, name, dim_data, **kwargs):
"""
Registers a dimension on this cube.
.. code-block:: python
cube.register_dimension('ntime', 10000,
decription="Number of Timesteps",
lower_extent=100, upper_extent=200)
Parameters
----------
dim_data : int or :class:`~hypercube.dims.Dimension`
if an integer, this will be used to
define the global_size of the dimension
and possibly other attributes if they are
not present in kwargs.
If a Dimension, it will be updated with
any appropriate keyword arguments
description : str
The description for this dimension.
e.g. 'Number of timesteps'.
lower_extent : int
The lower extent of this dimension
within the global space
upper_extent : int
The upper extent of this dimension
within the global space
name : Dimension name
Returns
-------
:class:`~hypercube.dims.Dimension`
A hypercube Dimension
""" |
if name in self._dims:
raise AttributeError((
"Attempted to register dimension '{n}'' "
"as an attribute of the cube, but "
"it already exists. Please choose "
"a different name!").format(n=name))
# Create the dimension dictionary
D = self._dims[name] = create_dimension(name,
dim_data, **kwargs)
return D |
<SYSTEM_TASK:>
Register multiple dimensions on the cube.
<END_TASK>
<USER_TASK:>
Description:
def register_dimensions(self, dims):
"""
Register multiple dimensions on the cube.
.. code-block:: python
cube.register_dimensions([
{'name' : 'ntime', 'global_size' : 10,
'lower_extent' : 2, 'upper_extent' : 7 },
{'name' : 'na', 'global_size' : 3,
'lower_extent' : 2, 'upper_extent' : 7 },
])
Parameters
----------
dims : list or dict
A list or dictionary of dimensions
""" |
if isinstance(dims, collections.Mapping):
dims = dims.itervalues()
for dim in dims:
self.register_dimension(dim.name, dim) |
<SYSTEM_TASK:>
Returns a list of dimension attribute attr, for the
<END_TASK>
<USER_TASK:>
Description:
def _dim_attribute(self, attr, *args, **kwargs):
"""
Returns a list of dimension attribute attr, for the
dimensions specified as strings in args.
.. code-block:: python
ntime, nbl, nchan = cube._dim_attribute('global_size', 'ntime', 'nbl', 'nchan')
or
.. code-block:: python
ntime, nbl, nchan, nsrc = cube._dim_attribute('global_size', 'ntime,nbl:nchan nsrc')
""" |
import re
# If we got a single string argument, try splitting it by separators
if len(args) == 1 and isinstance(args[0], str):
args = (s.strip() for s in re.split(',|:|;| ', args[0]))
# Now get the specific attribute for each string dimension
# Integers are returned as is
result = [d if isinstance(d, (int, np.integer))
else getattr(self._dims[d], attr) for d in args]
# Return single element if length one and single else entire list
return (result[0] if kwargs.get('single', True)
and len(result) == 1 else result) |
<SYSTEM_TASK:>
Returns a mapping of dimension name to global size
<END_TASK>
<USER_TASK:>
Description:
def dim_global_size_dict(self):
""" Returns a mapping of dimension name to global size """ |
return { d.name: d.global_size for d in self._dims.itervalues()} |
<SYSTEM_TASK:>
Returns a mapping of dimension name to lower_extent
<END_TASK>
<USER_TASK:>
Description:
def dim_lower_extent_dict(self):
""" Returns a mapping of dimension name to lower_extent """ |
return { d.name: d.lower_extent for d in self._dims.itervalues()} |
<SYSTEM_TASK:>
Returns a mapping of dimension name to upper_extent
<END_TASK>
<USER_TASK:>
Description:
def dim_upper_extent_dict(self):
""" Returns a mapping of dimension name to upper_extent """ |
return { d.name: d.upper_extent for d in self._dims.itervalues()} |
<SYSTEM_TASK:>
Returns the lower extent of the dimensions in args.
<END_TASK>
<USER_TASK:>
Description:
def dim_lower_extent(self, *args, **kwargs):
"""
Returns the lower extent of the dimensions in args.
.. code-block:: python
t_ex, bl_ex, ch_ex = cube.dim_lower_extent('ntime', 'nbl', 'nchan')
or
.. code-block:: python
t_ex, bl_ex, ch_ex, src_ex = cube.dim_lower_extent('ntime,nbl:nchan nsrc')
""" |
# The lower extent of any integral dimension is 0 by default
args = tuple(0 if isinstance(a, (int, np.integer))
else a for a in args)
return self._dim_attribute('lower_extent', *args, **kwargs) |
<SYSTEM_TASK:>
Returns extent tuples of the dimensions in args.
<END_TASK>
<USER_TASK:>
Description:
def dim_extents(self, *args, **kwargs):
"""
Returns extent tuples of the dimensions in args.
.. code-block:: python
(tl, tu), (bl, bu) = cube.dim_extents('ntime', 'nbl')
or
.. code-block:: python
(tl, tu), (bl, bu) = cube.dim_upper_extent('ntime,nbl')
""" |
l = self.dim_lower_extent(*args, **kwargs)
u = self.dim_upper_extent(*args, **kwargs)
# Handle sequence and singles differently
if isinstance(l, collections.Sequence):
return zip(l, u)
else:
return (l, u) |
<SYSTEM_TASK:>
Returns extent sizes of the dimensions in args.
<END_TASK>
<USER_TASK:>
Description:
def dim_extent_size(self, *args, **kwargs):
"""
Returns extent sizes of the dimensions in args.
.. code-block:: python
ts, bs, cs = cube.dim_extent_size('ntime', 'nbl', 'nchan')
or
.. code-block:: python
ts, bs, cs, ss = cube.dim_extent_size('ntime,nbl:nchan nsrc')
""" |
extents = self.dim_extents(*args, **kwargs)
# Handle tuples and sequences differently
if isinstance(extents, tuple):
return extents[1] - extents[0]
else: # isinstance(extents, collections.Sequence):
return (u-l for l, u in extents) |
<SYSTEM_TASK:>
Register an array with this cube.
<END_TASK>
<USER_TASK:>
Description:
def register_array(self, name, shape, dtype, **kwargs):
"""
Register an array with this cube.
.. code-block:: python
cube.register_array("model_vis", ("ntime", "nbl", "nchan", 4), np.complex128)
Parameters
----------
name : str
Array name
shape : A tuple containing either Dimension names or ints
Array shape schema
dtype :
Array data type
""" |
# Complain if array exists
if name in self._arrays:
raise ValueError(('Array %s is already registered '
'on this cube object.') % name)
# OK, create a record for this array
A = self._arrays[name] = AttrDict(name=name,
dtype=dtype, shape=shape,
**kwargs)
return A |
<SYSTEM_TASK:>
Register arrays using a list of dictionaries defining the arrays.
<END_TASK>
<USER_TASK:>
Description:
def register_arrays(self, arrays):
"""
Register arrays using a list of dictionaries defining the arrays.
The list should itself contain dictionaries. i.e.
.. code-block:: python
D = [{ 'name':'uvw', 'shape':(3,'ntime','nbl'),'dtype':np.float32 },
{ 'name':'lm', 'shape':(2,'nsrc'),'dtype':np.float32 }]
Parameters
----------
arrays : A list or dict.
A list or dictionary of dictionaries describing arrays.
""" |
if isinstance(arrays, collections.Mapping):
arrays = arrays.itervalues()
for ary in arrays:
self.register_array(**ary) |
<SYSTEM_TASK:>
Register properties using a list defining the properties.
<END_TASK>
<USER_TASK:>
Description:
def register_properties(self, properties):
"""
Register properties using a list defining the properties.
The dictionary should itself contain dictionaries. i.e.
.. code-block:: python
D = [
{ 'name':'ref_wave','dtype':np.float32,
'default':1.41e6 },
]
Parameters
----------
properties : A dictionary or list
A dictionary or list of dictionaries
describing properties
""" |
if isinstance(properties, collections.Mapping):
properties = properties.itervalues()
for prop in properties:
self.register_property(**prop) |
<SYSTEM_TASK:>
Return a list of lower and upper extents for
<END_TASK>
<USER_TASK:>
Description:
def array_extents(self, array_name, **kwargs):
"""
Return a list of lower and upper extents for
the given array_name.
.. code-block:: python
cube.register("uvw", ("ntime", "na", 3), np.float64)
(lt, ut), (la, ua), (_, _) = cube.array_extents("uvw")
Parameters
----------
array_name : string
Name of an array registered on this hypercube
Returns
-------
list
List of (lower_extent, upper_extent) tuples
associated with each array dimension
""" |
A = self.array(array_name, reify=False)
return self.dim_extents(*A.shape, single=False) |
<SYSTEM_TASK:>
Check if key is in adict. The search is case insensitive.
<END_TASK>
<USER_TASK:>
Description:
def contains_case_insensitive(adict, akey):
"""Check if key is in adict. The search is case insensitive.""" |
for key in adict:
if key.lower() == akey.lower():
return True
return False |
<SYSTEM_TASK:>
Format a comic name.
<END_TASK>
<USER_TASK:>
Description:
def format_name(text):
"""Format a comic name.""" |
name = unescape(text)
name = asciify(name.replace(u'&', u'And').replace(u'@', u'At'))
name = capfirst(name)
return name |
<SYSTEM_TASK:>
Resolves a slug to a single article object.
<END_TASK>
<USER_TASK:>
Description:
def get_article_from_slug(tree, slug, preview=False, draft=False):
"""
Resolves a slug to a single article object.
Returns None if article does not exist
""" |
from ..models import Title
titles = Title.objects.select_related('article').filter(article__tree=tree)
published_only = (not draft and not preview)
if draft:
titles = titles.filter(publisher_is_draft=True)
elif preview:
titles = titles.filter(publisher_is_draft=False)
else:
titles = titles.filter(published=True, publisher_is_draft=False)
titles = titles.filter(slug=slug)
for title in titles.iterator():
if published_only and not _page_is_published(title.article):
continue
title.article.title_cache = {title.language: title}
return title.article
return |
<SYSTEM_TASK:>
Allows custom request to method routing based on given ``action_map`` kwarg.
<END_TASK>
<USER_TASK:>
Description:
def as_view(cls, action_map=None, **initkwargs):
"""
Allows custom request to method routing based on given ``action_map`` kwarg.
""" |
# Needs to re-implement the method but contains all the things the parent does.
if not action_map: # actions must not be empty
raise TypeError("action_map is a required argument.")
def view(request):
self = cls(**initkwargs)
self.request = request
self.lookup_url_kwargs = self.request.matchdict
self.action_map = action_map
self.action = self.action_map.get(self.request.method.lower())
for method, action in action_map.items():
handler = getattr(self, action)
setattr(self, method, handler)
return self.dispatch(self.request, **self.request.matchdict)
return view |
<SYSTEM_TASK:>
Example HTTP Get response method.
<END_TASK>
<USER_TASK:>
Description:
def get(self, *args, **kwargs):
"""Example HTTP Get response method.
:param args: positional args
:param kwargs: keyword args
""" |
self.session.username = 'gmr'
session = self.session.as_dict()
if session['last_request_at']:
session['last_request_at'] = str(date.fromtimestamp(
session['last_request_at']))
# Send a JSON string for our test
self.write({'message': 'Hello World',
'request': {'method': self.request.method,
'protocol': self.request.protocol,
'path': self.request.path,
'query': self.request.query,
'remote_ip': self.request.remote_ip,
'version': self.request.version},
'session': session,
'tinman': {'version': __version__}})
self.finish() |
<SYSTEM_TASK:>
Take any values coming in as a datetime and deserialize them
<END_TASK>
<USER_TASK:>
Description:
def _deserialize_datetime(self, data):
"""Take any values coming in as a datetime and deserialize them
""" |
for key in data:
if isinstance(data[key], dict):
if data[key].get('type') == 'datetime':
data[key] = \
datetime.datetime.fromtimestamp(data[key]['value'])
return data |
<SYSTEM_TASK:>
Return the deserialized data.
<END_TASK>
<USER_TASK:>
Description:
def deserialize(self, data):
"""Return the deserialized data.
:param str data: The data to deserialize
:rtype: dict
""" |
if not data:
return dict()
return self._deserialize_datetime(pickle.loads(data)) |
<SYSTEM_TASK:>
Return the data as serialized string.
<END_TASK>
<USER_TASK:>
Description:
def serialize(self, data):
"""Return the data as serialized string.
:param dict data: The data to serialize
:rtype: str
""" |
return json.dumps(self._serialize_datetime(data), ensure_ascii=False) |
<SYSTEM_TASK:>
Get lock object for given URL host.
<END_TASK>
<USER_TASK:>
Description:
def get_host_lock(url):
"""Get lock object for given URL host.""" |
hostname = get_hostname(url)
return host_locks.setdefault(hostname, threading.Lock()) |
<SYSTEM_TASK:>
Print warning about interrupt and empty the job queue.
<END_TASK>
<USER_TASK:>
Description:
def finish():
"""Print warning about interrupt and empty the job queue.""" |
out.warn("Interrupted!")
for t in threads:
t.stop()
jobs.clear()
out.warn("Waiting for download threads to finish.") |
<SYSTEM_TASK:>
Get scraper objects for the given comics.
<END_TASK>
<USER_TASK:>
Description:
def getScrapers(comics, basepath=None, adult=True, multiple_allowed=False, listing=False):
"""Get scraper objects for the given comics.""" |
if '@' in comics:
# only scrapers whose directory already exists
if len(comics) > 1:
out.warn(u"using '@' as comic name ignores all other specified comics.")
for scraperclass in scraper.get_scraperclasses():
dirname = getDirname(scraperclass.getName())
if os.path.isdir(os.path.join(basepath, dirname)):
if shouldRunScraper(scraperclass, adult, listing):
yield scraperclass()
elif '@@' in comics:
# all scrapers
for scraperclass in scraper.get_scraperclasses():
if shouldRunScraper(scraperclass, adult, listing):
yield scraperclass()
else:
# get only selected comic scrapers
# store them in a set to eliminate duplicates
scrapers = set()
for comic in comics:
# Helpful when using shell completion to pick comics to get
comic = comic.rstrip(os.path.sep)
if basepath and comic.startswith(basepath):
# make the following command work:
# find Comics -type d | xargs -n1 -P10 dosage -b Comics
comic = comic[len(basepath):].lstrip(os.sep)
if ':' in comic:
name, index = comic.split(':', 1)
indexes = index.split(',')
else:
name = comic
indexes = None
scraperclasses = scraper.find_scraperclasses(name, multiple_allowed=multiple_allowed)
for scraperclass in scraperclasses:
if shouldRunScraper(scraperclass, adult, listing):
scraperobj = scraperclass(indexes=indexes)
if scraperobj not in scrapers:
scrapers.add(scraperobj)
yield scraperobj |
<SYSTEM_TASK:>
Print warning about disabled comic modules.
<END_TASK>
<USER_TASK:>
Description:
def warn_disabled(scraperclass, reasons):
"""Print warning about disabled comic modules.""" |
out.warn(u"Skipping comic %s: %s" % (scraperclass.getName(), ' '.join(reasons.values()))) |
<SYSTEM_TASK:>
Process from queue until it is empty.
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Process from queue until it is empty.""" |
try:
while not self.stopped:
scraperobj = jobs.get(False)
self.setName(scraperobj.getName())
try:
self.getStrips(scraperobj)
finally:
jobs.task_done()
self.setName(self.origname)
except Empty:
pass
except KeyboardInterrupt:
thread.interrupt_main() |
<SYSTEM_TASK:>
Get all strips from a scraper.
<END_TASK>
<USER_TASK:>
Description:
def _getStrips(self, scraperobj):
"""Get all strips from a scraper.""" |
if self.options.all or self.options.cont:
numstrips = None
elif self.options.numstrips:
numstrips = self.options.numstrips
else:
# get current strip
numstrips = 1
try:
if scraperobj.isComplete(self.options.basepath):
out.info(u"All comics are already downloaded.")
return 0
for strip in scraperobj.getStrips(numstrips):
skipped = self.saveComicStrip(strip)
if skipped and self.options.cont:
# stop when retrieval skipped an image for one comic strip
out.info(u"Stop retrieval because image file already exists")
break
if self.stopped:
break
if self.options.all and not (self.errors or self.options.dry_run or
self.options.cont or scraperobj.indexes):
scraperobj.setComplete(self.options.basepath)
except Exception as msg:
out.exception(msg)
self.errors += 1 |
<SYSTEM_TASK:>
Save a comic strip which can consist of multiple images.
<END_TASK>
<USER_TASK:>
Description:
def saveComicStrip(self, strip):
"""Save a comic strip which can consist of multiple images.""" |
allskipped = True
for image in strip.getImages():
try:
if self.options.dry_run:
filename, saved = "", False
else:
filename, saved = image.save(self.options.basepath)
if saved:
allskipped = False
if self.stopped:
break
except Exception as msg:
out.exception('Could not save image at %s to %s: %r' % (image.referrer, image.filename, msg))
self.errors += 1
return allskipped |
<SYSTEM_TASK:>
Take two copies of a variable and reconcile them. var1 is assumed
<END_TASK>
<USER_TASK:>
Description:
def merge(var1, var2):
"""
Take two copies of a variable and reconcile them. var1 is assumed
to be the higher-level variable, and so will be overridden by var2
where such becomes necessary.
""" |
out = {}
out['value'] = var2.get('value', var1.get('value', None))
out['mimetype'] = var2.get('mimetype', var1.get('mimetype', None))
out['types'] = var2.get('types') + [x for x in var1.get('types') if x not in var2.get('types')]
out['optional'] = var2.get('optional', var1.get('optional', False))
out['filename'] = var2.get('filename', var2.get('filename', None))
return Variable(var1.default_type, **out) |
<SYSTEM_TASK:>
Does the variable both have the given type and
<END_TASK>
<USER_TASK:>
Description:
def has_value_of_type(self, var_type):
"""
Does the variable both have the given type and
have a variable value we can use?
""" |
if self.has_value() and self.has_type(var_type):
return True
return False |
<SYSTEM_TASK:>
Get a list of the variables that are defined, but not required
<END_TASK>
<USER_TASK:>
Description:
def optional_names(self):
"""
Get a list of the variables that are defined, but not required
""" |
for name, var in self.items():
if var.get('optional', False):
yield name |
<SYSTEM_TASK:>
Return a list of all the variable types that exist in the
<END_TASK>
<USER_TASK:>
Description:
def types(self):
"""
Return a list of all the variable types that exist in the
Variables object.
""" |
output = set()
for var in self.values():
if var.has_value():
output.update(var.types())
return list(output) |
<SYSTEM_TASK:>
Add additional single Variable objects to the Variables
<END_TASK>
<USER_TASK:>
Description:
def add(self, **kwargs):
"""
Add additional single Variable objects to the Variables
object.
""" |
for name, var in kwargs.items():
if iskeyword(name):
var['name'] = name
name = '_' + name
if name in self:
self[name] = merge(self[name], Variable(self.default_type, **var))
else:
self[name] = Variable(self.default_type, **var)
return self |
<SYSTEM_TASK:>
If we get a single positional argument, and only a single
<END_TASK>
<USER_TASK:>
Description:
def fill_arg(self, *args):
"""
If we get a single positional argument, and only a single
variable needs to be filled, fill that variable with
the value from that positional argument.
""" |
missing = self.missing_vars()
if len(args) == len(missing) == 1:
self.setval(missing[0], args[0]) |
<SYSTEM_TASK:>
Fill empty variable objects by name with the values from
<END_TASK>
<USER_TASK:>
Description:
def fill_kwargs(self, **kwargs):
"""
Fill empty variable objects by name with the values from
any present keyword arguments.
""" |
for var, val in kwargs.items():
self.setval(var, val) |
<SYSTEM_TASK:>
Take args and kwargs and fill up any variables that
<END_TASK>
<USER_TASK:>
Description:
def fill(self, *args, **kwargs):
"""
Take args and kwargs and fill up any variables that
don't have a value yet.
""" |
self.fill_kwargs(**kwargs)
self.fill_arg(*args)
self.assert_full()
return self |
<SYSTEM_TASK:>
Set the value of the variable with the given name.
<END_TASK>
<USER_TASK:>
Description:
def setval(self, varname, value):
"""
Set the value of the variable with the given name.
""" |
if varname in self:
self[varname]['value'] = value
else:
self[varname] = Variable(self.default_type, value=value) |
<SYSTEM_TASK:>
Get a moving average curve chart to smooth between points
<END_TASK>
<USER_TASK:>
Description:
def sline_(self, window_size=5,
y_label="Moving average", chart_label=None):
"""
Get a moving average curve chart to smooth between points
""" |
options = dict(window_size=window_size, y_label=y_label)
try:
return self._get_chart("sline", style=self.chart_style,
opts=self.chart_opts, label=chart_label,
options=options)
except Exception as e:
self.err(e, self.sline_, "Can not draw smooth curve chart") |
<SYSTEM_TASK:>
Get an stacked area chart
<END_TASK>
<USER_TASK:>
Description:
def sarea_(self, col, x=None, y=None, rsum=None, rmean=None):
"""
Get an stacked area chart
""" |
try:
charts = self._multiseries(col, x, y, "area", rsum, rmean)
return hv.Area.stack(charts)
except Exception as e:
self.err(e, self.sarea_, "Can not draw stacked area chart") |
<SYSTEM_TASK:>
Get a line and point chart
<END_TASK>
<USER_TASK:>
Description:
def line_point_(self, label=None, style=None, opts=None, options={},
colors={"line": "orange", "point": "#30A2DA"}):
"""
Get a line and point chart
""" |
try:
if style is None:
style = self.chart_style
if "size" not in style:
style["size"] = 10
style["color"] = colors["line"]
c = self._get_chart("line", style=style, opts=opts,
label=label, options=options)
style["color"] = colors["point"]
c2 = self._get_chart("point", style=style, opts=opts,
label=label, options=options)
return c * c2
except Exception as e:
self.err(e, self.line_point_, "Can not draw line_point chart") |
<SYSTEM_TASK:>
Chart multiple series from a column distinct values
<END_TASK>
<USER_TASK:>
Description:
def _multiseries(self, col, x, y, ctype, rsum, rmean):
"""
Chart multiple series from a column distinct values
""" |
self.autoprint = False
x, y = self._check_fields(x, y)
chart = None
series = self.split_(col)
for key in series:
instance = series[key]
if rsum is not None:
instance.rsum(rsum, index_col=x)
if rmean is not None:
instance.rmean(rmean, index_col=x)
instance.chart(x, y)
self.scolor()
c = None
label = str(key)
if ctype == "point":
c = instance.point_(label)
if ctype == "line":
instance.zero_nan(y)
c = instance.line_(label)
if ctype == "bar":
c = instance.bar_(label)
if ctype == "area":
c = instance.area_(label)
if c is None:
self.warning("Chart type " + ctype +
" not supported, aborting")
return
if chart is None:
chart = c
else:
chart = chart * c
return chart |
<SYSTEM_TASK:>
Get a Seaborn distribution chart
<END_TASK>
<USER_TASK:>
Description:
def distrib_(self, label=None, style=None, opts=None):
"""
Get a Seaborn distribution chart
""" |
try:
return self._get_chart("distribution", style=style, opts=opts, label=label)
except Exception as e:
self.err(e, "Can not draw distrinution chart") |
<SYSTEM_TASK:>
Reset the chart options and style to defaults
<END_TASK>
<USER_TASK:>
Description:
def defaults(self):
"""
Reset the chart options and style to defaults
""" |
self.chart_style = {}
self.chart_opts = {}
self.style("color", "#30A2DA")
self.width(900)
self.height(250) |
<SYSTEM_TASK:>
Check x and y fields parameters and initialize
<END_TASK>
<USER_TASK:>
Description:
def _check_fields(self, x, y):
"""
Check x and y fields parameters and initialize
""" |
if x is None:
if self.x is None:
self.err(
self._check_fields,
"X field is not set: please specify a parameter")
return
x = self.x
if y is None:
if self.y is None:
self.err(
self._check_fields,
"Y field is not set: please specify a parameter")
return
y = self.y
return x, y |
<SYSTEM_TASK:>
Get a full chart object
<END_TASK>
<USER_TASK:>
Description:
def _get_chart(self, chart_type, x=None, y=None, style=None, opts=None,
label=None, options={}, **kwargs):
"""
Get a full chart object
""" |
sbcharts = ["density", "distribution", "dlinear"]
acharts = ["tick", "circle", "text", "line_num", "bar_num"]
if chart_type in sbcharts:
self._set_seaborn_engine()
if chart_type in acharts:
self._set_altair_engine()
if chart_type != "sline":
x, y = self._check_fields(x, y)
if opts is None:
opts = self.chart_opts
if style is None:
style = self.chart_style
if self.engine == "bokeh":
func = self._get_bokeh_chart
elif self.engine == "altair":
func = self._get_altair_chart
elif self.engine == "chartjs":
func = self._get_chartjs_chart
elif self.engine == "seaborn":
func = self._get_seaborn_chart
else:
self.err("Engine " + self.engine + " unknown")
return
try:
chart = func(
x, y, chart_type, label, opts, style,
options=options, **kwargs)
return chart
except Exception as e:
self.err(e) |
<SYSTEM_TASK:>
Checks if charts defaults are set
<END_TASK>
<USER_TASK:>
Description:
def _check_defaults(self, x_only=True):
"""
Checks if charts defaults are set
""" |
if self.x is None:
self.err(self._check_defaults,
"X field is not set: please specify a parameter")
return
if x_only is True:
return
if self.y is None:
self.err(self._check_defaults,
"Y field is not set: please specify a parameter")
return |
<SYSTEM_TASK:>
Adds one or more flags to the query.
<END_TASK>
<USER_TASK:>
Description:
def add_flags(self, *flags):
"""Adds one or more flags to the query.
For example:
current-patch-set -> --current-patch-set
""" |
if not isinstance(flags, (list, tuple)):
flags = [str(flags)]
self.extend(["--%s" % f for f in flags])
return self |
<SYSTEM_TASK:>
Gets the latest content for a particular article and language. Falls back
<END_TASK>
<USER_TASK:>
Description:
def get_title(self, article, language, language_fallback=False):
"""
Gets the latest content for a particular article and language. Falls back
to another language if wanted.
""" |
try:
title = self.get(language=language, article=article)
return title
except self.model.DoesNotExist:
if language_fallback:
try:
titles = self.filter(article=article)
fallbacks = get_fallback_languages(language)
for lang in fallbacks:
for title in titles:
if lang == title.language:
return title
return None
except self.model.DoesNotExist:
pass
else:
raise
return None |
<SYSTEM_TASK:>
set or create a title for a particular article and language
<END_TASK>
<USER_TASK:>
Description:
def set_or_create(self, request, article, form, language):
"""
set or create a title for a particular article and language
""" |
base_fields = [
'slug',
'title',
'description',
'meta_description',
'page_title',
'menu_title',
'image',
]
cleaned_data = form.cleaned_data
try:
obj = self.get(article=article, language=language)
except self.model.DoesNotExist:
data = {}
for name in base_fields:
if name in cleaned_data:
data[name] = cleaned_data[name]
data['article'] = article
data['language'] = language
return self.create(**data)
for name in base_fields:
if name in form.base_fields:
value = cleaned_data.get(name, None)
setattr(obj, name, value)
obj.save()
return obj |
<SYSTEM_TASK:>
Try to construct a nicely-formatted string for a list of matcher
<END_TASK>
<USER_TASK:>
Description:
def prettyMatcherList(things):
"""Try to construct a nicely-formatted string for a list of matcher
objects. Those may be compiled regular expressions or strings...""" |
norm = []
for x in makeSequence(things):
if hasattr(x, 'pattern'):
norm.append(x.pattern)
else:
norm.append(x)
return "('%s')" % "', '".join(norm) |
<SYSTEM_TASK:>
Normalising
<END_TASK>
<USER_TASK:>
Description:
def normaliseURL(url):
"""Normalising
- strips and leading or trailing whitespace,
- replaces HTML entities and character references,
- removes any leading empty segments to avoid breaking urllib2.
""" |
url = unicode_safe(url).strip()
# XXX: brutal hack
url = unescape(url)
pu = list(urlparse(url))
segments = pu[2].split('/')
while segments and segments[0] in ('', '..'):
del segments[0]
pu[2] = '/' + '/'.join(segments)
# remove leading '&' from query
if pu[4].startswith('&'):
pu[4] = pu[4][1:]
# remove anchor
pu[5] = ""
return urlunparse(pu) |
<SYSTEM_TASK:>
Check if robots.txt allows our user agent for the given URL.
<END_TASK>
<USER_TASK:>
Description:
def check_robotstxt(url, session):
"""Check if robots.txt allows our user agent for the given URL.
@raises: IOError if URL is not allowed
""" |
roboturl = get_roboturl(url)
rp = get_robotstxt_parser(roboturl, session=session)
if not rp.can_fetch(UserAgent, str(url)):
raise IOError("%s is disallowed by %s" % (url, roboturl)) |
<SYSTEM_TASK:>
Check that content length in URL response headers do not exceed the
<END_TASK>
<USER_TASK:>
Description:
def check_content_size(url, headers, max_content_bytes):
"""Check that content length in URL response headers do not exceed the
given maximum bytes.
""" |
if not max_content_bytes:
return
if 'content-length' in headers:
size = int(headers['content-length'])
if size > max_content_bytes:
msg = 'URL content of %s with %d bytes exceeds %d bytes.' % (url, size, max_content_bytes)
raise IOError(msg) |
<SYSTEM_TASK:>
Split a path in its components.
<END_TASK>
<USER_TASK:>
Description:
def splitpath(path):
"""Split a path in its components.""" |
c = []
head, tail = os.path.split(path)
while tail:
c.insert(0, tail)
head, tail = os.path.split(head)
return c |
<SYSTEM_TASK:>
Get a path that is relative to the given base path.
<END_TASK>
<USER_TASK:>
Description:
def getRelativePath(basepath, path):
"""Get a path that is relative to the given base path.""" |
basepath = splitpath(os.path.abspath(basepath))
path = splitpath(os.path.abspath(path))
afterCommon = False
for c in basepath:
if afterCommon or path[0] != c:
path.insert(0, os.path.pardir)
afterCommon = True
else:
del path[0]
return os.path.join(*path) |
<SYSTEM_TASK:>
Replace all percent-encoded entities in text.
<END_TASK>
<USER_TASK:>
Description:
def unquote(text):
"""Replace all percent-encoded entities in text.""" |
while '%' in text:
newtext = url_unquote(text)
if newtext == text:
break
text = newtext
return text |
<SYSTEM_TASK:>
Get a filename from given name without dangerous or incompatible characters.
<END_TASK>
<USER_TASK:>
Description:
def getFilename(name):
"""Get a filename from given name without dangerous or incompatible characters.""" |
# first replace all illegal chars
name = re.sub(r"[^0-9a-zA-Z_\-\.]", "_", name)
# then remove double dots and underscores
while ".." in name:
name = name.replace('..', '.')
while "__" in name:
name = name.replace('__', '_')
# remove a leading dot or minus
if name.startswith((".", "-")):
name = name[1:]
return name |
<SYSTEM_TASK:>
Add filename suffix until file exists
<END_TASK>
<USER_TASK:>
Description:
def getExistingFile(name, max_suffix=1000):
"""Add filename suffix until file exists
@return: filename if file is found
@raise: ValueError if maximum suffix number is reached while searching
""" |
num = 1
stem, ext = os.path.splitext(name)
filename = name
while not os.path.exists(filename):
suffix = "-%d" % num
filename = stem + suffix + ext
num += 1
if num >= max_suffix:
raise ValueError("No file %r found" % name)
return filename |
<SYSTEM_TASK:>
Add filename suffix until file not exists
<END_TASK>
<USER_TASK:>
Description:
def getNonexistingFile(name):
"""Add filename suffix until file not exists
@return: filename
""" |
num = 1
stem, ext = os.path.splitext(name)
filename = name
while os.path.exists(filename):
suffix = "-%d" % num
filename = stem + suffix + ext
num += 1
return filename |
<SYSTEM_TASK:>
Test if comic name already exists.
<END_TASK>
<USER_TASK:>
Description:
def has_gocomics_comic(name):
"""Test if comic name already exists.""" |
cname = "Gocomics/%s" % name
for scraperclass in get_scraperclasses():
lname = scraperclass.getName().lower()
if lname == cname.lower():
return True
return False |
<SYSTEM_TASK:>
Search the list of available products.
<END_TASK>
<USER_TASK:>
Description:
def search_product(self, limit=100, offset=0, with_price=0, with_supported_software=0,
with_description=0):
"""Search the list of available products.""" |
response = self.request(E.searchProductSslCertRequest(
E.limit(limit),
E.offset(offset),
E.withPrice(int(with_price)),
E.withSupportedSoftware(int(with_supported_software)),
E.withDescription(int(with_description)),
))
return response.as_models(SSLProduct) |
<SYSTEM_TASK:>
Modify an ordered SSL certificate.
<END_TASK>
<USER_TASK:>
Description:
def modify(self, order_id, approver_email=None, domain_validation_methods=None):
"""Modify an ordered SSL certificate.""" |
response = self.request(E.modifySslCertRequest(
E.id(order_id),
OE('approverEmail', approver_email),
OE('domainValidationMethods', domain_validation_methods, transform=_domain_validation_methods),
))
return response.data |
<SYSTEM_TASK:>
Resend the activation email to the approver.
<END_TASK>
<USER_TASK:>
Description:
def resend_approver_email(self, order_id):
"""Resend the activation email to the approver.""" |
response = self.request(E.resendApproverEmailSslCertRequest(
E.id(order_id)
))
return int(response.data.id) |
<SYSTEM_TASK:>
Change the approver email address for an ordered SSL certificate.
<END_TASK>
<USER_TASK:>
Description:
def change_approver_email_address(self, order_id, approver_email):
"""Change the approver email address for an ordered SSL certificate.""" |
response = self.request(
E.changeApproverEmailAddressSslCertRequest(
E.id(order_id),
E.approverEmail(approver_email)
)
)
return int(response.data.id) |
<SYSTEM_TASK:>
Try and import the specified namespaced class.
<END_TASK>
<USER_TASK:>
Description:
def _import_class(self, class_path):
"""Try and import the specified namespaced class.
:param str class_path: The full path to the class (foo.bar.Baz)
:rtype: class
""" |
LOGGER.debug('Importing %s', class_path)
try:
return utils.import_namespaced_class(class_path)
except ImportError as error:
LOGGER.critical('Could not import %s: %s', class_path, error)
return None |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.