INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Return operations suitable for serializing as part of a MacaroonId. | def _macaroon_id_ops(ops):
'''Return operations suitable for serializing as part of a MacaroonId.
It assumes that ops has been canonicalized and that there's at least
one operation.
'''
id_ops = []
for entity, entity_ops in itertools.groupby(ops, lambda x: x.entity):
actions = map(lambd... |
Takes a macaroon with the given version from the oven associates it with the given operations and attaches the given caveats. There must be at least one operation specified. The macaroon will expire at the given time - a time_before first party caveat will be added with that time. | def macaroon(self, version, expiry, caveats, ops):
''' Takes a macaroon with the given version from the oven,
associates it with the given operations and attaches the given caveats.
There must be at least one operation specified.
The macaroon will expire at the given time - a time_before... |
Returns a new multi - op entity name string that represents all the given operations and caveats. It returns the same value regardless of the ordering of the operations. It assumes that the operations have been canonicalized and that there s at least one operation. | def ops_entity(self, ops):
''' Returns a new multi-op entity name string that represents
all the given operations and caveats. It returns the same value
regardless of the ordering of the operations. It assumes that the
operations have been canonicalized and that there's at least one
... |
This method makes the oven satisfy the MacaroonOpStore protocol required by the Checker class. | def macaroon_ops(self, macaroons):
''' This method makes the oven satisfy the MacaroonOpStore protocol
required by the Checker class.
For macaroons minted with previous bakery versions, it always
returns a single LoginOp operation.
:param macaroons:
:return:
'''... |
Add an item to the end of the list. | def append(self, value):
"""Add an item to the end of the list."""
return super(Collection, self).append(
self._ensure_value_is_valid(value)) |
Extend the list by appending all the items in the given list. | def extend(self, iterable):
"""Extend the list by appending all the items in the given list."""
return super(Collection, self).extend(
self._ensure_iterable_is_valid(iterable)) |
Insert an item at a given position. | def insert(self, index, value):
"""Insert an item at a given position."""
return super(Collection, self).insert(
index, self._ensure_value_is_valid(value)) |
Ensure that value is a valid collection s value. | def _ensure_value_is_valid(self, value):
"""Ensure that value is a valid collection's value."""
if not isinstance(value, self.__class__.value_type):
raise TypeError('{0} is not valid collection value, instance '
'of {1} required'.format(
... |
Returns container element type | def container_elem_type(container_type, params):
"""
Returns container element type
:param container_type:
:param params:
:return:
"""
elem_type = params[0] if params else None
if elem_type is None:
elem_type = container_type.ELEM_TYPE
return elem_type |
Generates element array of given size and initializes with given type. Supports container type used for pre - allocation before deserialization.: param size:: param elem_type:: return: | def gen_elem_array(size, elem_type=None):
"""
Generates element array of given size and initializes with given type.
Supports container type, used for pre-allocation before deserialization.
:param size:
:param elem_type:
:return:
"""
if elem_type is None or not callable(elem_type):
... |
Check that a given DOI is a valid canonical DOI. | def is_valid(doi):
"""
Check that a given DOI is a valid canonical DOI.
:param doi: The DOI to be checked.
:returns: Boolean indicating whether the DOI is valid or not.
>>> is_valid('10.1209/0295-5075/111/40005')
True
>>> is_valid('10.1016.12.31/nature.S0735-1097(98)2000/12/31/34:7-7')
... |
Convert a list of canonical DOIs to a list of DOIs URLs. | def to_url(dois):
"""
Convert a list of canonical DOIs to a list of DOIs URLs.
:param dois: List of canonical DOIs. Can also be a single canonical DOI.
:returns: A list of DOIs URLs (resp. a single value).
>>> to_url(['10.1209/0295-5075/111/40005'])
['http://dx.doi.org/10.1209/0295-5075/111/40... |
Get an OA version for a given DOI. | def get_oa_version(doi):
"""
Get an OA version for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The URL of the OA version of the given DOI, or ``None``.
>>> get_oa_version('10.1209/0295-5075/111/40005')
'http://arxiv.org/abs/1506.06690'
... |
Get OA policy for a given DOI. | def get_oa_policy(doi):
"""
Get OA policy for a given DOI.
.. note::
Uses beta.dissem.in API.
:param doi: A canonical DOI.
:returns: The OpenAccess policy for the associated publications, or \
``None`` if unknown.
>>> tmp = get_oa_policy('10.1209/0295-5075/111/40005'); (t... |
Get the original link behind the DOI. | def get_linked_version(doi):
"""
Get the original link behind the DOI.
:param doi: A canonical DOI.
:returns: The canonical URL behind the DOI, or ``None``.
>>> get_linked_version('10.1209/0295-5075/111/40005')
'http://stacks.iop.org/0295-5075/111/i=4/a=40005?key=crossref.9ad851948a976ecdf216d... |
Get a BibTeX entry for a given DOI. | def get_bibtex(doi):
"""
Get a BibTeX entry for a given DOI.
.. note::
Adapted from https://gist.github.com/jrsmith3/5513926.
:param doi: The canonical DOI to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('10.1209/0295-5075/111/40005')
'@article{Verney_20... |
Configures the logging module with a given dictionary which in most cases was loaded from a configuration file. | def _configure_logging(self, logger_dict=None):
"""
Configures the logging module with a given dictionary, which in most cases was loaded from a configuration
file.
If no dictionary is provided, it falls back to a default configuration.
See `Python docs
<https://docs.py... |
Dumps blob message to the writer. Supports both blob and raw value. | async def dump_blob(writer, elem, elem_type, params=None):
"""
Dumps blob message to the writer.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, BlobType)
elem_params = elem if elem_i... |
Loads blob from reader to the element. Returns the loaded blob. | async def load_blob(reader, elem_type, params=None, elem=None):
"""
Loads blob from reader to the element. Returns the loaded blob.
:param reader:
:param elem_type:
:param params:
:param elem:
:return:
"""
ivalue = elem_type.SIZE if elem_type.FIX_SIZE else await load_uvarint(reader)... |
Dumps string as UTF8 encoded string: param writer:: param elem:: return: | async def dump_unicode(writer, elem):
"""
Dumps string as UTF8 encoded string
:param writer:
:param elem:
:return:
"""
await dump_uvarint(writer, len(elem))
await writer.awrite(bytes(elem, 'utf8')) |
Loads UTF8 string: param reader:: return: | async def load_unicode(reader):
"""
Loads UTF8 string
:param reader:
:return:
"""
ivalue = await load_uvarint(reader)
fvalue = bytearray(ivalue)
await reader.areadinto(fvalue)
return str(fvalue, 'utf8') |
Prepares container for serialization: param size:: param container:: return: | async def prepare_container(self, size, container, elem_type=None):
"""
Prepares container for serialization
:param size:
:param container:
:return:
"""
if not self.writing:
if container is None:
return gen_elem_array(size, elem_type)
... |
Loads/ dumps blob: return: | async def blob(self, elem=None, elem_type=None, params=None):
"""
Loads/dumps blob
:return:
"""
elem_type = elem_type if elem_type else elem.__class__
if hasattr(elem_type, "serialize_archive"):
elem = elem_type() if elem is None else elem
return a... |
Loads/ dumps container: return: | async def container(self, container=None, container_type=None, params=None):
"""
Loads/dumps container
:return:
"""
if hasattr(container_type, "serialize_archive"):
container = container_type() if container is None else container
return await container.ser... |
Container size: param container_len:: param container_type:: param params:: return: | async def container_size(
self, container_len=None, container_type=None, params=None
):
"""
Container size
:param container_len:
:param container_type:
:param params:
:return:
"""
if hasattr(container_type, "serialize_archive"):
... |
Single cont value: param elem:: param container_type:: param params:: return: | async def container_val(self, elem, container_type, params=None):
"""
Single cont value
:param elem:
:param container_type:
:param params:
:return:
"""
if hasattr(container_type, "serialize_archive"):
raise ValueError("not supported")
i... |
Loads/ dumps tuple: return: | async def tuple(self, elem=None, elem_type=None, params=None):
"""
Loads/dumps tuple
:return:
"""
if hasattr(elem_type, "serialize_archive"):
container = elem_type() if elem is None else elem
return await container.serialize_archive(
self, ... |
Loads/ dumps variant type: param elem:: param elem_type:: param params:: return: | async def variant(self, elem=None, elem_type=None, params=None, wrapped=None):
"""
Loads/dumps variant type
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_type = elem_type if elem_type else elem.__class__
if hasattr(elem_type, "ser... |
Loads/ dumps message: param msg:: param msg_type:: param use_version:: return: | async def message(self, msg, msg_type=None, use_version=None):
"""
Loads/dumps message
:param msg:
:param msg_type:
:param use_version:
:return:
"""
elem_type = msg_type if msg_type is not None else msg.__class__
msg = elem_type() if msg is None el... |
Dumps/ Loads message field: param msg:: param field:: param fvalue: explicit value for dump: return: | async def message_field(self, msg, field, fvalue=None):
"""
Dumps/Loads message field
:param msg:
:param field:
:param fvalue: explicit value for dump
:return:
"""
fname, ftype, params = field[0], field[1], field[2:]
try:
self.tracker.p... |
Archive field: param elem:: param elem_type:: param params:: return: | async def field(self, elem=None, elem_type=None, params=None):
"""
Archive field
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_type = elem_type if elem_type else elem.__class__
fvalue = None
etype = self._get_type(elem_ty... |
Dumps container size - per element streaming: param writer:: param container_len:: param container_type:: param params:: return: | async def _dump_container_size(
self, writer, container_len, container_type, params=None
):
"""
Dumps container size - per element streaming
:param writer:
:param container_len:
:param container_type:
:param params:
:return:
"""
if ... |
Single elem dump: param writer:: param elem:: param container_type:: param params:: return: | async def _dump_container_val(self, writer, elem, container_type, params=None):
"""
Single elem dump
:param writer:
:param elem:
:param container_type:
:param params:
:return:
"""
elem_type = container_elem_type(container_type, params)
awai... |
Dumps container of elements to the writer. | async def _dump_container(self, writer, container, container_type, params=None):
"""
Dumps container of elements to the writer.
:param writer:
:param container:
:param container_type:
:param params:
:return:
"""
await self._dump_container_size(wri... |
Loads container of elements from the reader. Supports the container ref. Returns loaded container. | async def _load_container(
self, reader, container_type, params=None, container=None
):
"""
Loads container of elements from the reader. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:pa... |
Dumps tuple of elements to the writer. | async def _dump_tuple(self, writer, elem, elem_type, params=None):
"""
Dumps tuple of elements to the writer.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
if len(elem) != len(elem_type.f_specs()):
raise Val... |
Loads tuple of elements from the reader. Supports the tuple ref. Returns loaded tuple. | async def _load_tuple(self, reader, elem_type, params=None, elem=None):
"""
Loads tuple of elements from the reader. Supports the tuple ref.
Returns loaded tuple.
:param reader:
:param elem_type:
:param params:
:param container:
:return:
"""
... |
Dumps a message field to the writer. Field is defined by the message field specification. | async def _dump_message_field(self, writer, msg, field, fvalue=None):
"""
Dumps a message field to the writer. Field is defined by the message field specification.
:param writer:
:param msg:
:param field:
:param fvalue:
:return:
"""
fname, ftype, ... |
Loads message field from the reader. Field is defined by the message field specification. Returns loaded value supports field reference. | async def _load_message_field(self, reader, msg, field):
"""
Loads message field from the reader. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:return:
"""
... |
Dumps variant type to the writer. Supports both wrapped and raw variant. | async def _dump_variant(self, writer, elem, elem_type=None, params=None):
"""
Dumps variant type to the writer.
Supports both wrapped and raw variant.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
if isinstance(... |
Loads variant type from the reader. Supports both wrapped and raw variant. | async def _load_variant(
self, reader, elem_type, params=None, elem=None, wrapped=None
):
"""
Loads variant type from the reader.
Supports both wrapped and raw variant.
:param reader:
:param elem_type:
:param params:
:param elem:
:param wr... |
Manually starts timer with the message. | def start(self, message):
"""
Manually starts timer with the message.
:param message: The display message.
"""
self._start = time.clock()
VSGLogger.info("{0:<20} - Started".format(message)) |
Manually stops timer with the message. | def stop(self, message):
"""
Manually stops timer with the message.
:param message: The display message.
"""
self._stop = time.clock()
VSGLogger.info("{0:<20} - Finished [{1}s]".format(message, self.pprint(self._stop - self._start))) |
Pretty Prints seconds as Hours: Minutes: Seconds. MilliSeconds | def pprint(self, seconds):
"""
Pretty Prints seconds as Hours:Minutes:Seconds.MilliSeconds
:param seconds: The time in seconds.
"""
return ("%d:%02d:%02d.%03d", reduce(lambda ll, b: divmod(ll[0], b) + ll[1:], [(seconds * 1000,), 1000, 60, 60])) |
Search for a valid identifier ( DOI ISBN arXiv HAL ) in a given file. | def find_identifiers(src):
"""
Search for a valid identifier (DOI, ISBN, arXiv, HAL) in a given file.
.. note::
This function returns the first matching identifier, that is the most
likely to be relevant for this file. However, it may fail and return an
identifier taken from the re... |
Try to fetch BibTeX from a found identifier. | def get_bibtex(identifier):
"""
Try to fetch BibTeX from a found identifier.
.. note::
Calls the functions in the respective identifiers module.
:param identifier: a tuple (type, identifier) with a valid type.
:returns: A BibTeX string or ``None`` if an error occurred.
# TODO: Should ... |
Only try to parse as JSON if the JSON content type header is set. | def initialize(self,*args,**kwargs):
"""
Only try to parse as JSON if the JSON content type
header is set.
"""
super(JSONHandler,self).initialize(*args,**kwargs)
content_type = self.request.headers.get('Content-Type', '')
if 'application/json' in content_type.lowe... |
Parse a BibTeX file to get a clean list of plaintext citations. | def get_plaintext_citations(bibtex):
"""
Parse a BibTeX file to get a clean list of plaintext citations.
:param bibtex: Either the path to the BibTeX file or the content of a \
BibTeX file.
:returns: A list of cleaned plaintext citations.
"""
parser = BibTexParser()
parser.cust... |
Loads INI configuration into this module s attributes. | def init(filename=ConfigPath):
"""Loads INI configuration into this module's attributes."""
section, parts = "DEFAULT", filename.rsplit(":", 1)
if len(parts) > 1 and os.path.isfile(parts[0]): filename, section = parts
if not os.path.isfile(filename): return
vardict, parser = globals(), config... |
Saves this module s changed attributes to INI configuration. | def save(filename=ConfigPath):
"""Saves this module's changed attributes to INI configuration."""
default_values = defaults()
parser = configparser.RawConfigParser()
parser.optionxform = str # Force case-sensitivity on names
try:
save_types = basestring, int, float, tuple, list, dict, ... |
Returns a once - assembled dict of this module s storable attributes. | def defaults(values={}):
"""Returns a once-assembled dict of this module's storable attributes."""
if values: return values
save_types = basestring, int, float, tuple, list, dict, type(None)
for k, v in globals().items():
if isinstance(v, save_types) and not k.startswith("_"): values[k] = v... |
Fix malformed pdf files when data are present after %%EOF | def fix_pdf(pdf_file, destination):
"""
Fix malformed pdf files when data are present after '%%EOF'
..note ::
Originally from sciunto, https://github.com/sciunto/tear-pages
:param pdfFile: PDF filepath
:param destination: destination
"""
tmp = tempfile.NamedTemporaryFile()
wit... |
Copy filename to a tempfile write pages to filename except the teared one. | def tearpage_backend(filename, teared_pages=None):
"""
Copy filename to a tempfile, write pages to filename except the teared one.
..note ::
Adapted from sciunto's code, https://github.com/sciunto/tear-pages
:param filename: PDF filepath
:param teared_pages: Numbers of the pages to tear. ... |
Check whether a given paper needs some pages to be teared or not. | def tearpage_needed(bibtex):
"""
Check whether a given paper needs some pages to be teared or not.
:params bibtex: The bibtex entry associated to the paper, to guess \
whether tearing is needed.
:returns: A list of pages to tear.
"""
for publisher in BAD_JOURNALS:
if publish... |
Tear some pages of the file if needed. | def tearpage(filename, bibtex=None, force=None):
"""
Tear some pages of the file if needed.
:params filename: Path to the file to handle.
:params bibtex: BibTeX dict associated to this file, as the one given by \
``bibtexparser``. (Mandatory if force is not specified)
:params force: If ... |
Creates or returns a singleton: class:. Connection object | def connect(*args, **kwargs):
"""Creates or returns a singleton :class:`.Connection` object"""
global __CONNECTION
if __CONNECTION is None:
__CONNECTION = Connection(*args, **kwargs)
return __CONNECTION |
Checks out a file into the default changelist | def edit(filename, connection=None):
"""Checks out a file into the default changelist
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
rev = c.ls(filename)
if r... |
Syncs a file | def sync(filename, connection=None):
"""Syncs a file
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
rev = c.ls(filename)
if rev:
rev[0].sync() |
Edits or Adds a filename ensuring the file is in perforce and editable | def open(filename, connection=None):
"""Edits or Adds a filename ensuring the file is in perforce and editable
:param filename: File to check out
:type filename: str
:param connection: Connection object to use
:type connection: :py:class:`Connection`
"""
c = connection or connect()
res ... |
Set name for Faultset: param name: Name of Faultset: param fsObj: ScaleIO FS object: return: POST request response: rtype: Requests POST response object | def set_faultset_name(self, name, fsObj):
"""
Set name for Faultset
:param name: Name of Faultset
:param fsObj: ScaleIO FS object
:return: POST request response
:rtype: Requests POST response object
"""
# Set name of FaultSet
self.conn.connection._... |
Check that a given arXiv ID is a valid one. | def is_valid(arxiv_id):
"""
Check that a given arXiv ID is a valid one.
:param arxiv_id: The arXiv ID to be checked.
:returns: Boolean indicating whether the arXiv ID is valid or not.
>>> is_valid('1506.06690')
True
>>> is_valid('1506.06690v1')
True
>>> is_valid('arXiv:1506.06690... |
Get a BibTeX entry for a given arXiv ID. | def get_bibtex(arxiv_id):
"""
Get a BibTeX entry for a given arXiv ID.
.. note::
Using awesome https://pypi.python.org/pypi/arxiv2bib/ module.
:param arxiv_id: The canonical arXiv id to get BibTeX from.
:returns: A BibTeX string or ``None``.
>>> get_bibtex('1506.06690')
"@article... |
Extract arXiv IDs from a text. | def extract_from_text(text):
"""
Extract arXiv IDs from a text.
:param text: The text to extract arXiv IDs from.
:returns: A list of matching arXiv IDs, in canonical form.
>>> sorted(extract_from_text('1506.06690 1506.06690v1 arXiv:1506.06690 arXiv:1506.06690v1 arxiv:1506.06690 arxiv:1506.06690v1 ... |
Convert a list of canonical DOIs to a list of DOIs URLs. | def to_url(arxiv_ids):
"""
Convert a list of canonical DOIs to a list of DOIs URLs.
:param dois: List of canonical DOIs.
:returns: A list of DOIs URLs.
>>> to_url('1506.06690')
'http://arxiv.org/abs/1506.06690'
>>> to_url('1506.06690v1')
'http://arxiv.org/abs/1506.06690v1'
"""
... |
Get the arXiv eprint id for a given DOI. | def from_doi(doi):
"""
Get the arXiv eprint id for a given DOI.
.. note::
Uses arXiv API. Will not return anything if arXiv is not aware of the
associated DOI.
:param doi: The DOI of the resource to look for.
:returns: The arXiv eprint id, or ``None`` if not found.
>>> from_d... |
Download sources on arXiv for a given preprint. | def get_sources(arxiv_id):
"""
Download sources on arXiv for a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401... |
Get the. bbl files ( if any ) of a given preprint. | def get_bbl(arxiv_id):
"""
Get the .bbl files (if any) of a given preprint.
.. note::
Bulk download of sources from arXiv is not permitted by their API. \
You should have a look at http://arxiv.org/help/bulk_data_s3.
:param arxiv_id: The arXiv id (e.g. ``1401.2910`` or ``1401.... |
Extract semantic date information from an input string. This is a convenience method which would only be used if you d rather not initialize a DateService object. | def extractDates(inp, tz=None, now=None):
"""Extract semantic date information from an input string.
This is a convenience method which would only be used if
you'd rather not initialize a DateService object.
Args:
inp (str): The input string to be parsed.
tz: An optional Pytz timezone. ... |
Extracts all day - related information from an input string. Ignores any information related to the specific time - of - day. | def extractDays(self, inp):
"""Extracts all day-related information from an input string.
Ignores any information related to the specific time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects containing the extracted date f... |
Extracts time - related information from an input string. Ignores any information related to the specific date focusing on the time - of - day. | def extractTimes(self, inp):
"""Extracts time-related information from an input string.
Ignores any information related to the specific date, focusing
on the time-of-day.
Args:
inp (str): Input string to be parsed.
Returns:
A list of datetime objects con... |
Extract semantic date information from an input string. In effect runs both parseDay and parseTime on the input string and merges the results to produce a comprehensive datetime object. | def extractDates(self, inp):
"""Extract semantic date information from an input string.
In effect, runs both parseDay and parseTime on the input
string and merges the results to produce a comprehensive
datetime object.
Args:
inp (str): Input string to be parsed.
... |
Returns the first date found in the input string or None if not found. | def extractDate(self, inp):
"""Returns the first date found in the input string, or None if not
found."""
dates = self.extractDates(inp)
for date in dates:
return date
return None |
Convert a datetime object representing a day into a human - ready string that can be read spoken aloud etc. | def convertDay(self, day, prefix="", weekday=False):
"""Convert a datetime object representing a day into a human-ready
string that can be read, spoken aloud, etc.
Args:
day (datetime.date): A datetime object to be converted into text.
prefix (str): An optional argument ... |
Convert a datetime object representing a time into a human - ready string that can be read spoken aloud etc. | def convertTime(self, time):
"""Convert a datetime object representing a time into a human-ready
string that can be read, spoken aloud, etc.
Args:
time (datetime.date): A datetime object to be converted into text.
Returns:
A string representation of the input ti... |
Convert a datetime object representing into a human - ready string that can be read spoken aloud etc. In effect runs both convertDay and convertTime on the input merging the results. | def convertDate(self, date, prefix="", weekday=False):
"""Convert a datetime object representing into a human-ready
string that can be read, spoken aloud, etc. In effect, runs
both convertDay and convertTime on the input, merging the results.
Args:
date (datetime.date): A da... |
Called during a PUT request where the action specifies a move operation. Returns resource URI of the destination file. | def _move(self):
"""
Called during a PUT request where the action specifies
a move operation. Returns resource URI of the destination file.
"""
newpath = self.action['newpath']
try:
self.fs.move(self.fp,newpath)
except OSError:
raise tornad... |
Called during a PUT request where the action specifies a copy operation. Returns resource URI of the new file. | def _copy(self):
"""
Called during a PUT request where the action specifies
a copy operation. Returns resource URI of the new file.
"""
copypath = self.action['copypath']
try:
self.fs.copy(self.fp,copypath)
except OSError:
raise tornado.web... |
Called during a PUT request where the action specifies a rename operation. Returns resource URI of the renamed file. | def _rename(self):
"""
Called during a PUT request where the action specifies
a rename operation. Returns resource URI of the renamed file.
"""
newname = self.action['newname']
try:
newpath = self.fs.rename(self.fp,newname)
except OSError:
... |
Return details for the filesystem including configured volumes. | def get(self):
"""
Return details for the filesystem, including configured volumes.
"""
res = self.fs.get_filesystem_details()
res = res.to_dict()
self.write(res) |
Provides move copy and rename functionality. An action must be specified when calling this method. | def put(self):
"""
Provides move, copy, and rename functionality. An action must be
specified when calling this method.
"""
self.fp = self.get_body_argument('filepath')
self.action = self.get_body_argument('action')
try:
ptype = self.fs.get_type_from_... |
Start a new filewatcher at the specified path. | def post(self, *args):
"""
Start a new filewatcher at the specified path.
"""
filepath = self.get_body_argument('filepath')
if not self.fs.exists(filepath):
raise tornado.web.HTTPError(404)
Filewatcher.add_directory_to_watch(filepath)
self.write({'msg... |
Stop and delete the specified filewatcher. | def delete(self, filepath):
"""
Stop and delete the specified filewatcher.
"""
Filewatcher.remove_directory_to_watch(filepath)
self.write({'msg':'Watcher deleted for {}'.format(filepath)}) |
Get file details for the specified file. | def get(self, filepath):
"""
Get file details for the specified file.
"""
try:
res = self.fs.get_file_details(filepath)
res = res.to_dict()
self.write(res)
except OSError:
raise tornado.web.HTTPError(404) |
Change the group or permissions of the specified file. Action must be specified when calling this method. | def put(self, filepath):
"""
Change the group or permissions of the specified file. Action
must be specified when calling this method.
"""
action = self.get_body_argument('action')
if action['action'] == 'update_group':
newgrp = action['group']
tr... |
Delete the specified file. | def delete(self, filepath):
"""
Delete the specified file.
"""
try:
self.fs.delete(filepath)
self.write({'msg':'File deleted at {}'.format(filepath)})
except OSError:
raise tornado.web.HTTPError(404) |
Get directory details for the specified file. If contents is set to True ( default ) then the directory contents will be sent along with the directory details. If dir_size is set to True ( default = False ) then du - hs will be run against subdirectories for accurate content sizes. | def get(self, filepath):
"""
Get directory details for the specified file. If contents is
set to True (default) then the directory contents will be sent
along with the directory details. If dir_size is set to True
(default=False) then du -hs will be run against subdirectories
... |
Create a new directory at the specified path. | def post(self):
"""
Create a new directory at the specified path.
"""
filepath = self.get_body_argument('filepath')
try:
self.fs.create_directory(filepath)
encoded_filepath = tornado.escape.url_escape(filepath,plus=True)
resource_uri = self.re... |
Get the contents of the specified file. | def get(self, filepath):
"""
Get the contents of the specified file.
"""
exists = self.fs.exists(filepath)
if exists:
mime = magic.Magic(mime=True)
mime_type = mime.from_file(filepath)
if mime_type in self.unsupported_types:
sel... |
Write the given contents to the specified file. This is not an append all file contents will be replaced by the contents given. | def post(self, filepath):
"""
Write the given contents to the specified file. This is not
an append, all file contents will be replaced by the contents
given.
"""
try:
content = self.get_body_argument('content')
self.fs.write_file(filepath, content... |
Retrieve the content of the requested resource which is located at the given absolute path. This method should either return a byte string or an iterator of byte strings. The latter is preferred for large files as it helps reduce memory fragmentation. | def get_content(self, start=None, end=None):
"""
Retrieve the content of the requested resource which is located
at the given absolute path.
This method should either return a byte string or an iterator
of byte strings. The latter is preferred for large files
as it helps... |
Sets the content headers on the response. | def set_headers(self):
"""
Sets the content headers on the response.
"""
self.set_header("Accept-Ranges", "bytes")
content_type = self.get_content_type()
if content_type:
self.set_header("Content-Type", content_type) |
Returns the Content - Type header to be used for this request. | def get_content_type(self):
"""
Returns the ``Content-Type`` header to be used for this request.
"""
mime_type, encoding = mimetypes.guess_type(self.filepath)
if encoding == "gzip":
return "application/gzip"
elif encoding is not None:
return "appli... |
Callback which gets executed if the signal plugin_deactivate_post was send by the plugin. | def __deactivate_shared_objects(self, plugin, *args, **kwargs):
"""
Callback, which gets executed, if the signal "plugin_deactivate_post" was send by the plugin.
"""
shared_objects = self.get()
for shared_object in shared_objects.keys():
self.unregister(shared_object) |
Registers a new shared object. | def register(self, name, description, obj):
"""
Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared
... |
Returns requested shared objects which were registered by the current plugin. | def get(self, name=None):
"""
Returns requested shared objects, which were registered by the current plugin.
If access to objects of other plugins are needed, use :func:`access` or perform get on application level::
my_app.shared_objects.get(name="...")
:param name: Name o... |
Returns requested shared objects. | def get(self, name=None, plugin=None):
"""
Returns requested shared objects.
:param name: Name of a request shared object
:type name: str or None
:param plugin: Plugin, which has registered the requested shared object
:type plugin: GwBasePattern instance or None
... |
Registers a new shared object. | def register(self, name, description, obj, plugin):
"""
Registers a new shared object.
:param name: Unique name for shared object
:type name: str
:param description: Description of shared object
:type description: str
:param obj: The object, which shall be shared... |
Unregisters an existing shared object so that this shared object is no longer available. | def unregister(self, shared_object):
"""
Unregisters an existing shared object, so that this shared object is no longer available.
This function is mainly used during plugin deactivation.
:param shared_object: Name of the shared_object
"""
if shared_object not in self._... |
Prints a list of all registered signals. Including description and plugin name. | def list_signals(self):
"""
Prints a list of all registered signals. Including description and plugin name.
"""
print("Signal list")
print("***********\n")
for key, signal in self.app.signals.signals.items():
print("%s (%s)\n %s\n" % (signal.name, signal.plug... |
Prints a list of all registered receivers. Including signal plugin name and description. | def list_receivers(self):
"""
Prints a list of all registered receivers. Including signal, plugin name and description.
"""
print("Receiver list")
print("*************\n")
for key, receiver in self.app.signals.receivers.items():
print("%s <-- %s (%s):\n %s\n"... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.