_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q57100 | dump_blob | train | async def dump_blob(elem, elem_type=None):
"""
Dumps blob message.
Supports both blob and raw value.
:param writer:
:param elem:
:param elem_type:
:param params:
:return:
"""
elem_is_blob = isinstance(elem, x.BlobType)
data = getattr(elem, x.BlobType.DATA_ATTR) if elem_is_bl... | python | {
"resource": ""
} |
q57101 | dump_container | train | async def dump_container(obj, container, container_type, params=None, field_archiver=None):
"""
Serializes container as popo
:param obj:
:param container:
:param container_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_archiver ... | python | {
"resource": ""
} |
q57102 | load_container | train | async def load_container(obj, container_type, params=None, container=None, field_archiver=None):
"""
Loads container of elements from the object representation. Supports the container ref.
Returns loaded container.
:param reader:
:param container_type:
:param params:
:param container:
:... | python | {
"resource": ""
} |
q57103 | dump_message_field | train | async def dump_message_field(obj, msg, field, field_archiver=None):
"""
Dumps a message field to the object. Field is defined by the message field specification.
:param obj:
:param msg:
:param field:
:param field_archiver:
:return:
"""
fname, ftype, params = field[0], field[1], fiel... | python | {
"resource": ""
} |
q57104 | load_message_field | train | async def load_message_field(obj, msg, field, field_archiver=None):
"""
Loads message field from the object. Field is defined by the message field specification.
Returns loaded value, supports field reference.
:param reader:
:param msg:
:param field:
:param field_archiver:
:return:
... | python | {
"resource": ""
} |
q57105 | dump_message | train | async def dump_message(obj, msg, field_archiver=None):
"""
Dumps message to the object.
Returns message popo representation.
:param obj:
:param msg:
:param field_archiver:
:return:
"""
mtype = msg.__class__
fields = mtype.f_specs()
obj = collections.OrderedDict() if obj is ... | python | {
"resource": ""
} |
q57106 | load_message | train | async def load_message(obj, msg_type, msg=None, field_archiver=None):
"""
Loads message if the given type from the object.
Supports reading directly to existing message.
:param obj:
:param msg_type:
:param msg:
:param field_archiver:
:return:
"""
msg = msg_type() if msg is None ... | python | {
"resource": ""
} |
q57107 | dump_variant | train | async def dump_variant(obj, elem, elem_type=None, params=None, field_archiver=None):
"""
Transform variant to the popo object representation.
:param obj:
:param elem:
:param elem_type:
:param params:
:param field_archiver:
:return:
"""
field_archiver = field_archiver if field_ar... | python | {
"resource": ""
} |
q57108 | dump_field | train | async def dump_field(obj, elem, elem_type, params=None):
"""
Dumps generic field to the popo object representation, according to the element specification.
General multiplexer.
:param obj:
:param elem:
:param elem_type:
:param params:
:return:
"""
if isinstance(elem, (int, bool)... | python | {
"resource": ""
} |
q57109 | load_field | train | async def load_field(obj, elem_type, params=None, elem=None):
"""
Loads a field from the reader, based on the field type specification. Demultiplexer.
:param obj:
:param elem_type:
:param params:
:param elem:
:return:
"""
if issubclass(elem_type, x.UVarintType) or issubclass(elem_ty... | python | {
"resource": ""
} |
q57110 | instantiate | train | def instantiate(data, blueprint):
"""
Instantiate the given data using the blueprinter.
Arguments
---------
blueprint (collections.Mapping):
a blueprint (JSON Schema with Seep properties)
"""
Validator = jsonschema.validators.validator_for(blueprint)
blueprinter = ext... | python | {
"resource": ""
} |
q57111 | main | train | def main(argv=None):
"""
The entry point of the script.
"""
from vsgen import VSGSuite
from vsgen import VSGLogger
# Special case to use the sys.argv when main called without a list.
if argv is None:
argv = sys.argv
# Initialize the application logger
pylogger = VSGLogger()... | python | {
"resource": ""
} |
q57112 | DomainModelMetaClass.parse_fields | train | def parse_fields(attributes):
"""Parse model fields."""
return tuple(field.bind_name(name)
for name, field in six.iteritems(attributes)
if isinstance(field, fields.Field)) | python | {
"resource": ""
} |
q57113 | DomainModelMetaClass.prepare_fields_attribute | train | def prepare_fields_attribute(attribute_name, attributes, class_name):
"""Prepare model fields attribute."""
attribute = attributes.get(attribute_name)
if not attribute:
attribute = tuple()
elif isinstance(attribute, std_collections.Iterable):
attribute = tuple(att... | python | {
"resource": ""
} |
q57114 | DomainModelMetaClass.bind_fields_to_model_cls | train | def bind_fields_to_model_cls(cls, model_fields):
"""Bind fields to model class."""
return dict(
(field.name, field.bind_model_cls(cls)) for field in model_fields) | python | {
"resource": ""
} |
q57115 | DomainModelMetaClass.bind_collection_to_model_cls | train | def bind_collection_to_model_cls(cls):
"""Bind collection to model's class.
If collection was not specialized in process of model's declaration,
subclass of collection will be created.
"""
cls.Collection = type('{0}.Collection'.format(cls.__name__),
... | python | {
"resource": ""
} |
q57116 | checklist | train | def checklist(ctx):
"""Checklist for releasing this project."""
checklist = """PRE-RELEASE CHECKLIST:
[ ] Everything is checked in
[ ] All tests pass w/ tox
RELEASE CHECKLIST:
[{x1}] Bump version to new-version and tag repository (via bump_version)
[{x2}] Build packages (sdist, bdist_wheel via prepare)
[{x... | python | {
"resource": ""
} |
q57117 | build_packages | train | def build_packages(ctx, hide=False):
"""Build packages for this release."""
print("build_packages:")
ctx.run("python setup.py sdist bdist_wheel", echo=True, hide=hide) | python | {
"resource": ""
} |
q57118 | ThreadsListPlugin.register | train | def register(self, name, function, description=None):
"""
Register a new thread.
:param function: Function, which gets called for the new thread
:type function: function
:param name: Unique name of the thread for documentation purposes.
:param description: Short descript... | python | {
"resource": ""
} |
q57119 | ThreadsListApplication.unregister | train | def unregister(self, thread):
"""
Unregisters an existing thread, so that this thread is no longer available.
This function is mainly used during plugin deactivation.
:param thread: Name of the thread
"""
if thread not in self.threads.keys():
self.log.warnin... | python | {
"resource": ""
} |
q57120 | ThreadsListApplication.get | train | def get(self, thread=None, plugin=None):
"""
Get one or more threads.
:param thread: Name of the thread
:type thread: str
:param plugin: Plugin object, under which the thread was registered
:type plugin: GwBasePattern
"""
if plugin is not None:
... | python | {
"resource": ""
} |
q57121 | create_schema_from_xsd_directory | train | def create_schema_from_xsd_directory(directory, version):
"""Create and fill the schema from a directory which contains xsd
files. It calls fill_schema_from_xsd_file for each xsd file
found.
"""
schema = Schema(version)
for f in _get_xsd_from_directory(directory):
logger.info("Loading s... | python | {
"resource": ""
} |
q57122 | fill_schema_from_xsd_file | train | def fill_schema_from_xsd_file(filename, schema):
"""From an xsd file, it fills the schema by creating needed
Resource. The generateds idl_parser is used to parse ifmap
statements in the xsd file.
"""
ifmap_statements = _parse_xsd_file(filename)
properties_all = []
for v in ifmap_statements... | python | {
"resource": ""
} |
q57123 | split_ls | train | def split_ls(func):
"""Decorator to split files into manageable chunks as not to exceed the windows cmd limit
:param func: Function to call for each chunk
:type func: :py:class:Function
"""
@wraps(func)
def wrapper(self, files, silent=True, exclude_deleted=False):
if not isinstance(file... | python | {
"resource": ""
} |
q57124 | Connection.__getVariables | train | def __getVariables(self):
"""Parses the P4 env vars using 'set p4'"""
try:
startupinfo = None
if os.name == 'nt':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_ou... | python | {
"resource": ""
} |
q57125 | Connection.client | train | def client(self):
"""The client used in perforce queries"""
if isinstance(self._client, six.string_types):
self._client = Client(self._client, self)
return self._client | python | {
"resource": ""
} |
q57126 | Connection.status | train | def status(self):
"""The status of the connection to perforce"""
try:
# -- Check client
res = self.run(['info'])
if res[0]['clientName'] == '*unknown*':
return ConnectionStatus.INVALID_CLIENT
# -- Trigger an auth error if not logged in
... | python | {
"resource": ""
} |
q57127 | Connection.run | train | def run(self, cmd, stdin=None, marshal_output=True, **kwargs):
"""Runs a p4 command and returns a list of dictionary objects
:param cmd: Command to run
:type cmd: list
:param stdin: Standard Input to send to the process
:type stdin: str
:param marshal_output: Whether or ... | python | {
"resource": ""
} |
q57128 | Connection.findChangelist | train | def findChangelist(self, description=None):
"""Gets or creates a Changelist object with a description
:param description: The description to set or lookup
:type description: str
:returns: :class:`.Changelist`
"""
if description is None:
change = Default(self)... | python | {
"resource": ""
} |
q57129 | Connection.add | train | def add(self, filename, change=None):
"""Adds a new file to a changelist
:param filename: File path to add
:type filename: str
:param change: Changelist to add the file to
:type change: int
:returns: :class:`.Revision`
"""
try:
if not self.can... | python | {
"resource": ""
} |
q57130 | Connection.canAdd | train | def canAdd(self, filename):
"""Determines if a filename can be added to the depot under the current client
:param filename: File path to add
:type filename: str
"""
try:
result = self.run(['add', '-n', '-t', 'text', filename])[0]
except errors.CommandError as... | python | {
"resource": ""
} |
q57131 | Changelist.query | train | def query(self, files=True):
"""Queries the depot to get the current status of the changelist"""
if self._change:
cl = str(self._change)
self._p4dict = {camel_case(k): v for k, v in six.iteritems(self._connection.run(['change', '-o', cl])[0])}
if files:
self.... | python | {
"resource": ""
} |
q57132 | Changelist.remove | train | def remove(self, rev, permanent=False):
"""Removes a revision from this changelist
:param rev: Revision to remove
:type rev: :class:`.Revision`
:param permanent: Whether or not we need to set the changelist to default
:type permanent: bool
"""
if not isinstance(r... | python | {
"resource": ""
} |
q57133 | Changelist.revert | train | def revert(self, unchanged_only=False):
"""Revert all files in this changelist
:param unchanged_only: Only revert unchanged files
:type unchanged_only: bool
:raises: :class:`.ChangelistError`
"""
if self._reverted:
raise errors.ChangelistError('This changelis... | python | {
"resource": ""
} |
q57134 | Changelist.submit | train | def submit(self):
"""Submits a chagelist to the depot"""
if self._dirty:
self.save()
self._connection.run(['submit', '-c', str(self._change)], marshal_output=False) | python | {
"resource": ""
} |
q57135 | Changelist.delete | train | def delete(self):
"""Reverts all files in this changelist then deletes the changelist from perforce"""
try:
self.revert()
except errors.ChangelistError:
pass
self._connection.run(['change', '-d', str(self._change)]) | python | {
"resource": ""
} |
q57136 | Changelist.create | train | def create(description='<Created by Python>', connection=None):
"""Creates a new changelist
:param connection: Connection to use to create the changelist
:type connection: :class:`.Connection`
:param description: Description for new changelist
:type description: str
:ret... | python | {
"resource": ""
} |
q57137 | Revision.query | train | def query(self):
"""Runs an fstat for this file and repopulates the data"""
self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0]
self._head = HeadRevision(self._p4dict)
self._filename = self.depotFile | python | {
"resource": ""
} |
q57138 | Revision.edit | train | def edit(self, changelist=0):
"""Checks out the file
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
command = 'reopen' if self.action in ('add', 'edit') else 'edit'
if int(changelist):
self._connect... | python | {
"resource": ""
} |
q57139 | Revision.lock | train | def lock(self, lock=True, changelist=0):
"""Locks or unlocks the file
:param lock: Lock or unlock the file
:type lock: bool
:param changelist: Optional changelist to checkout the file into
:type changelist: :class:`.Changelist`
"""
cmd = 'lock' if lock else 'unl... | python | {
"resource": ""
} |
q57140 | Revision.sync | train | def sync(self, force=False, safe=True, revision=0, changelist=0):
"""Syncs the file at the current revision
:param force: Force the file to sync
:type force: bool
:param safe: Don't sync files that were changed outside perforce
:type safe: bool
:param revision: Sync to a... | python | {
"resource": ""
} |
q57141 | Revision.revert | train | def revert(self, unchanged=False):
"""Reverts any file changes
:param unchanged: Only revert if the file is unchanged
:type unchanged: bool
"""
cmd = ['revert']
if unchanged:
cmd.append('-a')
wasadd = self.action == 'add'
cmd.append(self.dep... | python | {
"resource": ""
} |
q57142 | Revision.shelve | train | def shelve(self, changelist=None):
"""Shelves the file if it is in a changelist
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
if changelist is None and self.changelist.description == 'default':
raise errors.ShelveError('U... | python | {
"resource": ""
} |
q57143 | Revision.delete | train | def delete(self, changelist=0):
"""Marks the file for delete
:param changelist: Changelist to add the move to
:type changelist: :class:`.Changelist`
"""
cmd = ['delete']
if changelist:
cmd += ['-c', str(changelist)]
cmd.append(self.depotFile)
... | python | {
"resource": ""
} |
q57144 | Revision.hash | train | def hash(self):
"""The hash value of the current revision"""
if 'digest' not in self._p4dict:
self._p4dict = self._connection.run(['fstat', '-m', '1', '-Ol', self.depotFile])[0]
return self._p4dict['digest'] | python | {
"resource": ""
} |
q57145 | Client.view | train | def view(self):
"""A list of view specs"""
spec = []
for k, v in six.iteritems(self._p4dict):
if k.startswith('view'):
match = RE_FILESPEC.search(v)
if match:
spec.append(FileSpec(v[:match.end() - 1], v[match.end():]))
retu... | python | {
"resource": ""
} |
q57146 | Client.stream | train | def stream(self):
"""Which stream, if any, the client is under"""
stream = self._p4dict.get('stream')
if stream:
return Stream(stream, self._connection) | python | {
"resource": ""
} |
q57147 | Archive.set_version | train | async def set_version(self, tp, params, version=None, elem=None):
"""
Stores version to the stream if not stored yet
:param tp:
:param params:
:param version:
:param elem:
:return:
"""
self.registry.set_tr(None)
tw = TypeWrapper(tp, params... | python | {
"resource": ""
} |
q57148 | Archive.version | train | async def version(self, tp, params, version=None, elem=None):
"""
Symmetric version management
:param tp:
:param params:
:param version:
:return:
"""
if self.writing:
return await self.set_version(tp, params, version, elem)
else:
... | python | {
"resource": ""
} |
q57149 | Archive.root_message | train | async def root_message(self, msg, msg_type=None):
"""
Root-level message. First entry in the archive.
Archive headers processing
:return:
"""
await self.root()
await self.message(msg, msg_type) | python | {
"resource": ""
} |
q57150 | Archive.dump_message | train | async def dump_message(self, msg, msg_type=None):
"""
Dumps message to the writer.
:param msg:
:param msg_type:
:return:
"""
mtype = msg.__class__ if msg_type is None else msg_type
fields = mtype.f_specs()
for field in fields:
await se... | python | {
"resource": ""
} |
q57151 | Archive.load_message | train | async def load_message(self, msg_type, msg=None):
"""
Loads message if the given type from the reader.
Supports reading directly to existing message.
:param msg_type:
:param msg:
:return:
"""
msg = msg_type() if msg is None else msg
fields = msg_t... | python | {
"resource": ""
} |
q57152 | contrail_error_handler | train | def contrail_error_handler(f):
"""Handle HTTP errors returned by the API server
"""
@wraps(f)
def wrapper(*args, **kwargs):
try:
return f(*args, **kwargs)
except HttpError as e:
# Replace message by details to provide a
# meaningful message
... | python | {
"resource": ""
} |
q57153 | SessionLoader.make | train | def make(self, host="localhost", port=8082, protocol="http", base_uri="", os_auth_type="http", **kwargs):
"""Initialize a session to Contrail API server
:param os_auth_type: auth plugin to use:
- http: basic HTTP authentification
- v2password: keystone v2 auth
- v3pa... | python | {
"resource": ""
} |
q57154 | ContrailAPISession.post_json | train | def post_json(self, url, data, cls=None, **kwargs):
"""
POST data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder
"""
kwargs['data'] = to_json(data, cls=cls)
kw... | python | {
"resource": ""
} |
q57155 | ContrailAPISession.put_json | train | def put_json(self, url, data, cls=None, **kwargs):
"""
PUT data to the api-server
:param url: resource location (eg: "/type/uuid")
:type url: str
:param cls: JSONEncoder class
:type cls: JSONEncoder
"""
kwargs['data'] = to_json(data, cls=cls)
kwar... | python | {
"resource": ""
} |
q57156 | ContrailAPISession.fqname_to_id | train | def fqname_to_id(self, fq_name, type):
"""
Return uuid for fq_name
:param fq_name: resource fq name
:type fq_name: FQName
:param type: resource type
:type type: str
:rtype: UUIDv4 str
:raises HttpError: fq_name not found
"""
data = {
... | python | {
"resource": ""
} |
q57157 | ContrailAPISession.id_to_fqname | train | def id_to_fqname(self, uuid, type=None):
"""
Return fq_name and type for uuid
If `type` is provided check that uuid is actually
a resource of type `type`. Raise HttpError if it's
not the case.
:param uuid: resource uuid
:type uuid: UUIDv4 str
:param type... | python | {
"resource": ""
} |
q57158 | ContrailAPISession.add_kv_store | train | def add_kv_store(self, key, value):
"""Add a key-value store entry.
:param key: string
:param value: string
"""
data = {
'operation': 'STORE',
'key': key,
'value': value
}
return self.post(self.make_url("/useragent-kv"), data=t... | python | {
"resource": ""
} |
q57159 | ContrailAPISession.remove_kv_store | train | def remove_kv_store(self, key):
"""Remove a key-value store entry.
:param key: string
"""
data = {
'operation': 'DELETE',
'key': key
}
return self.post(self.make_url("/useragent-kv"), data=to_json(data),
headers=self.defau... | python | {
"resource": ""
} |
q57160 | canonical_ops | train | def canonical_ops(ops):
''' Returns the given operations array sorted with duplicates removed.
@param ops checker.Ops
@return: checker.Ops
'''
new_ops = sorted(set(ops), key=lambda x: (x.entity, x.action))
return new_ops | python | {
"resource": ""
} |
q57161 | _macaroon_id_ops | train | 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... | python | {
"resource": ""
} |
q57162 | Oven.macaroon | train | 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... | python | {
"resource": ""
} |
q57163 | Oven.ops_entity | train | 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
... | python | {
"resource": ""
} |
q57164 | Oven.macaroon_ops | train | 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:
'''... | python | {
"resource": ""
} |
q57165 | Collection.extend | train | 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)) | python | {
"resource": ""
} |
q57166 | Collection.insert | train | def insert(self, index, value):
"""Insert an item at a given position."""
return super(Collection, self).insert(
index, self._ensure_value_is_valid(value)) | python | {
"resource": ""
} |
q57167 | Collection._ensure_value_is_valid | train | 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(
... | python | {
"resource": ""
} |
q57168 | container_elem_type | train | 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 | python | {
"resource": ""
} |
q57169 | is_valid | train | 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')
... | python | {
"resource": ""
} |
q57170 | get_oa_version | train | 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'
... | python | {
"resource": ""
} |
q57171 | get_oa_policy | train | 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... | python | {
"resource": ""
} |
q57172 | get_linked_version | train | 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... | python | {
"resource": ""
} |
q57173 | get_bibtex | train | 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... | python | {
"resource": ""
} |
q57174 | App._configure_logging | train | 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... | python | {
"resource": ""
} |
q57175 | Archive._dump_message_field | train | 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, ... | python | {
"resource": ""
} |
q57176 | Archive._load_message_field | train | 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:
"""
... | python | {
"resource": ""
} |
q57177 | VSGTimer.start | train | 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)) | python | {
"resource": ""
} |
q57178 | VSGTimer.stop | train | 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))) | python | {
"resource": ""
} |
q57179 | get_bibtex | train | 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 ... | python | {
"resource": ""
} |
q57180 | JSONHandler.initialize | train | 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... | python | {
"resource": ""
} |
q57181 | get_plaintext_citations | train | 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... | python | {
"resource": ""
} |
q57182 | init | train | 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... | python | {
"resource": ""
} |
q57183 | save | train | 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, ... | python | {
"resource": ""
} |
q57184 | defaults | train | 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... | python | {
"resource": ""
} |
q57185 | fix_pdf | train | 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... | python | {
"resource": ""
} |
q57186 | tearpage_backend | train | 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. ... | python | {
"resource": ""
} |
q57187 | tearpage_needed | train | 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... | python | {
"resource": ""
} |
q57188 | tearpage | train | 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 ... | python | {
"resource": ""
} |
q57189 | edit | train | 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... | python | {
"resource": ""
} |
q57190 | sync | train | 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() | python | {
"resource": ""
} |
q57191 | open | train | 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 ... | python | {
"resource": ""
} |
q57192 | is_valid | train | 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... | python | {
"resource": ""
} |
q57193 | get_bibtex | train | 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... | python | {
"resource": ""
} |
q57194 | extract_from_text | train | 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 ... | python | {
"resource": ""
} |
q57195 | from_doi | train | 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... | python | {
"resource": ""
} |
q57196 | get_sources | train | 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... | python | {
"resource": ""
} |
q57197 | extractDates | train | 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. ... | python | {
"resource": ""
} |
q57198 | DateService.extractTimes | train | 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... | python | {
"resource": ""
} |
q57199 | DateService.extractDates | train | 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.
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.