_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q41700 | DynamoDBManager._update_metadata | train | def _update_metadata(self, archive_name, archive_metadata):
"""
Appends the updated_metada dict to the Metadata Attribute list
Parameters
----------
archive_name: str
ID of archive to update
updated_metadata: dict
dictionary of metadata keys an... | python | {
"resource": ""
} |
q41701 | DynamoDBManager._create_archive | train | def _create_archive(
self,
archive_name,
metadata):
'''
This adds an item in a DynamoDB table corresponding to a S3 object
Args
----
arhive_name: str
corresponds to the name of the Archive (e.g. )
Returns
-------
... | python | {
"resource": ""
} |
q41702 | load_backend | train | def load_backend(backend_name):
""" load pool backend."""
try:
if len(backend_name.split(".")) > 1:
mod = import_module(backend_name)
else:
mod = import_module("spamc.backend_%s" % backend_name)
return mod
except ImportError:
error_msg = "%s isn't a sp... | python | {
"resource": ""
} |
q41703 | Voevent | train | def Voevent(stream, stream_id, role):
"""Create a new VOEvent element tree, with specified IVORN and role.
Args:
stream (str): used to construct the IVORN like so::
ivorn = 'ivo://' + stream + '#' + stream_id
(N.B. ``stream_id`` is converted to string if required.)
... | python | {
"resource": ""
} |
q41704 | loads | train | def loads(s, check_version=True):
"""
Load VOEvent from bytes.
This parses a VOEvent XML packet string, taking care of some subtleties.
For Python 3 users, ``s`` should be a bytes object - see also
http://lxml.de/FAQ.html,
"Why can't lxml parse my XML from unicode strings?"
(Python 2 users ... | python | {
"resource": ""
} |
q41705 | load | train | def load(file, check_version=True):
"""Load VOEvent from file object.
A simple wrapper to read a file before passing the contents to
:py:func:`.loads`. Use with an open file object, e.g.::
with open('/path/to/voevent.xml', 'rb') as f:
v = vp.load(f)
Args:
file (io.IOBase):... | python | {
"resource": ""
} |
q41706 | dumps | train | def dumps(voevent, pretty_print=False, xml_declaration=True, encoding='UTF-8'):
"""Converts voevent to string.
.. note:: Default encoding is UTF-8, in line with VOE2.0 schema.
Declaring the encoding can cause diffs with the original loaded VOEvent,
but I think it's probably the right thing to d... | python | {
"resource": ""
} |
q41707 | dump | train | def dump(voevent, file, pretty_print=True, xml_declaration=True):
"""Writes the voevent to the file object.
e.g.::
with open('/tmp/myvoevent.xml','wb') as f:
voeventparse.dump(v, f)
Args:
voevent(:class:`Voevent`): Root node of the VOevent etree.
file (io.IOBase): An o... | python | {
"resource": ""
} |
q41708 | valid_as_v2_0 | train | def valid_as_v2_0(voevent):
"""Tests if a voevent conforms to the schema.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
Returns:
bool: Whether VOEvent is valid
"""
_return_to_standard_xml(voevent)
valid_bool = voevent_v2_0_schema.validate(voevent)
_remove_ro... | python | {
"resource": ""
} |
q41709 | set_author | train | def set_author(voevent, title=None, shortName=None, logoURL=None,
contactName=None, contactEmail=None, contactPhone=None,
contributor=None):
"""For setting fields in the detailed author description.
This can optionally be neglected if a well defined AuthorIVORN is supplied.
.... | python | {
"resource": ""
} |
q41710 | add_where_when | train | def add_where_when(voevent, coords, obs_time, observatory_location,
allow_tz_naive_datetime=False):
"""
Add details of an observation to the WhereWhen section.
We
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
coords(:class:`.Position2D`): Sky co-ordi... | python | {
"resource": ""
} |
q41711 | add_how | train | def add_how(voevent, descriptions=None, references=None):
"""Add descriptions or references to the How section.
Args:
voevent(:class:`Voevent`): Root node of a VOEvent etree.
descriptions(str): Description string, or list of description
strings.
references(:py:class:`voevent... | python | {
"resource": ""
} |
q41712 | add_citations | train | def add_citations(voevent, event_ivorns):
"""Add citations to other voevents.
The schema mandates that the 'Citations' section must either be entirely
absent, or non-empty - hence we require this wrapper function for its
creation prior to listing the first citation.
Args:
voevent(:class:`V... | python | {
"resource": ""
} |
q41713 | _remove_root_tag_prefix | train | def _remove_root_tag_prefix(v):
"""
Removes 'voe' namespace prefix from root tag.
When we load in a VOEvent, the root element has a tag prefixed by
the VOE namespace, e.g. {http://www.ivoa.net/xml/VOEvent/v2.0}VOEvent
Because objectify expects child elements to have the same namespace as
their... | python | {
"resource": ""
} |
q41714 | _reinsert_root_tag_prefix | train | def _reinsert_root_tag_prefix(v):
"""
Returns namespace prefix to root tag, if it had one.
"""
if hasattr(v, 'original_prefix'):
original_prefix = v.original_prefix
del v.original_prefix
v.tag = ''.join(('{', v.nsmap[original_prefix], '}VOEvent'))
return | python | {
"resource": ""
} |
q41715 | _listify | train | def _listify(x):
"""Ensure x is iterable; if not then enclose it in a list and return it."""
if isinstance(x, string_types):
return [x]
elif isinstance(x, collections.Iterable):
return x
else:
return [x] | python | {
"resource": ""
} |
q41716 | Identity.list | train | def list(self, label=None, per_page=20, page=1):
""" Get a list of identities that have been created
:param per_page: The number of results per page returned
:type per_page: int
:param page: The page number of the results
:type page: int
:return: dict... | python | {
"resource": ""
} |
q41717 | Identity.update | train | def update(self, id, label=None, status=None, master=None):
""" Update an Identity
:param label: The label to give this new identity
:param status: The status of this identity. Default: 'active'
:param master: Represents whether this identity is a master.
Def... | python | {
"resource": ""
} |
q41718 | PylonTask.get | train | def get(self, id, service='facebook', type='analysis'):
""" Get a given Pylon task
:param id: The ID of the task
:type id: str
:param service: The PYLON service (facebook)
:type service: str
:return: dict of REST API output with headers attached
... | python | {
"resource": ""
} |
q41719 | PylonTask.list | train | def list(self, per_page=None, page=None, status=None, service='facebook'):
""" Get a list of Pylon tasks
:param per_page: How many tasks to display per page
:type per_page: int
:param page: Which page of tasks to display
:type page: int
:param status:... | python | {
"resource": ""
} |
q41720 | PylonTask.create | train | def create(self, subscription_id, name, parameters, type='analysis', service='facebook'):
""" Create a PYLON task
:param subscription_id: The ID of the recording to create the task for
:type subscription_id: str
:param name: The name of the new task
:type name: s... | python | {
"resource": ""
} |
q41721 | StickyUploadWidget.value_from_datadict | train | def value_from_datadict(self, data, files, name):
"""Returns uploaded file from serialized value."""
upload = super(StickyUploadWidget, self).value_from_datadict(data, files, name)
if upload is not None:
# File was posted or cleared as normal
return upload
else:
... | python | {
"resource": ""
} |
q41722 | StickyUploadWidget.render | train | def render(self, name, value, attrs=None, renderer=None):
"""Include a hidden input to store the serialized upload value."""
location = getattr(value, '_seralized_location', '')
if location and not hasattr(value, 'url'):
value.url = '#'
if hasattr(self, 'get_template_subs... | python | {
"resource": ""
} |
q41723 | configure | train | def configure(config={}, datastore=None, nested=False):
"""
Useful for when you need to control Switchboard's setup
"""
if nested:
config = nested_config(config)
# Re-read settings to make sure we have everything.
# XXX It would be really nice if we didn't need to do this.
Settings.i... | python | {
"resource": ""
} |
q41724 | DupePredictor.get_dupe_prob | train | def get_dupe_prob(self, url):
""" A probability of given url being a duplicate of some content
that has already been seem.
"""
path, query = _parse_url(url)
dupestats = []
extend_ds = lambda x: dupestats.extend(filter(None, (
ds_dict.get(key) for ds_dict, key ... | python | {
"resource": ""
} |
q41725 | DupePredictor._nodup_filter | train | def _nodup_filter(self, min_hash, all_urls, max_sample=200):
""" This filters results that are considered not duplicates.
But we really need to check that, because lsh.query does not always
return ALL duplicates, esp. when there are a lot of them, so
here we double-check and return only ... | python | {
"resource": ""
} |
q41726 | UnrenderedAdmin.get_queryset | train | def get_queryset(self, request):
""" Remove ``show_rendered`` from the context, if it's there. """
qs = super(UnrenderedAdmin, self).get_queryset(request)
if 'show_rendered' in qs.query.context:
del qs.query.context['show_rendered']
return qs | python | {
"resource": ""
} |
q41727 | Cases.get_one | train | def get_one(self, cls=None, **kwargs):
"""Returns a one case."""
case = cls() if cls else self._CasesClass()
for attr, value in kwargs.iteritems():
setattr(case, attr, value)
return case | python | {
"resource": ""
} |
q41728 | Cases.get_each_choice | train | def get_each_choice(self, cls=None, **kwargs):
"""Returns a generator that generates positive cases by
"each choice" algorithm.
"""
defaults = {attr: kwargs[attr][0] for attr in kwargs}
for set_of_values in izip_longest(*kwargs.values()):
case = cls() if cls else self... | python | {
"resource": ""
} |
q41729 | Cases.get_pairwise | train | def get_pairwise(self, cls=None, **kwargs):
"""Returns a generator that generates positive cases by
"pairwise" algorithm.
"""
for set_of_values in allpairs(kwargs.values()):
case = cls() if cls else self._CasesClass()
for attr, value in izip(kwargs.keys(), set_of_... | python | {
"resource": ""
} |
q41730 | Cases.get_negative | train | def get_negative(self, cls=None, **kwargs):
"""Returns a generator that generates negative cases by
"each negative value in separate case" algorithm.
"""
for attr, set_of_values in kwargs.iteritems():
defaults = {key: kwargs[key][-1]["default"] for key in kwargs}
... | python | {
"resource": ""
} |
q41731 | Cases.get_mix_gen | train | def get_mix_gen(self, sample):
"""Returns function that returns sequence of characters of a
given length from a given sample
"""
def mix(length):
result = "".join(random.choice(sample) for _ in xrange(length)).strip()
if len(result) == length:
retu... | python | {
"resource": ""
} |
q41732 | set_mysql_connection | train | def set_mysql_connection(host='localhost', user='pyctd_user', password='pyctd_passwd', db='pyctd', charset='utf8'):
"""Sets the connection using MySQL Parameters"""
set_connection('mysql+pymysql://{user}:{passwd}@{host}/{db}?charset={charset}'.format(
host=host,
user=user,
passwd=passwor... | python | {
"resource": ""
} |
q41733 | set_connection | train | def set_connection(connection=defaults.sqlalchemy_connection_string_default):
"""Set the connection string for SQLAlchemy
:param str connection: SQLAlchemy connection string
"""
cfp = defaults.config_file_path
config = RawConfigParser()
if not os.path.exists(cfp):
with open(cfp, 'w') a... | python | {
"resource": ""
} |
q41734 | BaseDbManager.set_connection_string_by_user_input | train | def set_connection_string_by_user_input(self):
"""Prompts the user to input a connection string"""
user_connection = input(
bcolors.WARNING + "\nFor any reason connection to " + bcolors.ENDC +
bcolors.FAIL + "{}".format(self.connection) + bcolors.ENDC +
bcolors.WARNIN... | python | {
"resource": ""
} |
q41735 | BaseDbManager.drop_all | train | def drop_all(self):
"""Drops all tables in the database"""
log.info('dropping tables in %s', self.engine.url)
self.session.commit()
models.Base.metadata.drop_all(self.engine)
self.session.commit() | python | {
"resource": ""
} |
q41736 | DbManager.import_tables | train | def import_tables(self, only_tables=None, exclude_tables=None):
"""Imports all data in database tables
:param set[str] only_tables: names of tables to be imported
:param set[str] exclude_tables: names of tables to be excluded
"""
for table in self.tables:
if only_tab... | python | {
"resource": ""
} |
q41737 | DbManager.get_column_names_from_file | train | def get_column_names_from_file(file_path):
"""returns column names from CTD download file
:param str file_path: path to CTD download file
"""
if file_path.endswith('.gz'):
file_handler = io.TextIOWrapper(io.BufferedReader(gzip.open(file_path)))
else:
file... | python | {
"resource": ""
} |
q41738 | comma_join | train | def comma_join(fields, oxford=True):
""" Join together words. """
def fmt(field):
return "'%s'" % field
if not fields:
return "nothing"
elif len(fields) == 1:
return fmt(fields[0])
elif len(fields) == 2:
return " and ".join([fmt(f) for f in fields])
else:
... | python | {
"resource": ""
} |
q41739 | ThreadHandler.run | train | def run(self, target, args=()):
""" Run a function in a separate thread.
:param target: the function to run.
:param args: the parameters to pass to the function.
"""
run_event = threading.Event()
run_event.set()
thread = threading.Thread(target=target, args=args ... | python | {
"resource": ""
} |
q41740 | ThreadHandler.stop | train | def stop(self):
""" Stop all functions running in the thread handler."""
for run_event in self.run_events:
run_event.clear()
for thread in self.thread_pool:
thread.join() | python | {
"resource": ""
} |
q41741 | NoiseGenerator.generate | train | def generate(self, labels, split_idx):
"""Generate peak-specific noise abstract method, must be reimplemented in a subclass.
:param tuple labels: Dimension labels of a peak.
:param int split_idx: Index specifying which peak list split parameters to use.
:return: List of noise values for... | python | {
"resource": ""
} |
q41742 | version_diff | train | def version_diff(version1, version2):
"""Return string representing the diff between package versions.
We're interested in whether this is a major, minor, patch or 'other'
update. This method will compare the two versions and return None if
they are the same, else it will return a string value indicati... | python | {
"resource": ""
} |
q41743 | Package.data | train | def data(self):
"""Fetch latest data from PyPI, and cache for 30s."""
key = cache_key(self.name)
data = cache.get(key)
if data is None:
logger.debug("Updating package info for %s from PyPI.", self.name)
data = requests.get(self.url).json()
cache.set(ke... | python | {
"resource": ""
} |
q41744 | _query_wrap | train | def _query_wrap(fun, *args, **kwargs):
"""Wait until at least QUERY_WAIT_TIME seconds have passed
since the last invocation of this function, then call the given
function with the given arguments.
"""
with _query_lock:
global _last_query_time
since_last_query = time.time() - _last_qu... | python | {
"resource": ""
} |
q41745 | extract | train | def extract(pcmiter, samplerate, channels, duration = -1):
"""Given a PCM data stream, extract fingerprint data from the
audio. Returns a byte string of fingerprint data. Raises an
ExtractionError if fingerprinting fails.
"""
extractor = _fplib.Extractor(samplerate, channels, duration)
# Get fi... | python | {
"resource": ""
} |
q41746 | match_file | train | def match_file(apikey, path, metadata=None):
"""Uses the audioread library to decode an audio file and match it.
"""
import audioread
with audioread.audio_open(path) as f:
return match(apikey, iter(f), f.samplerate, int(f.duration),
f.channels, metadata) | python | {
"resource": ""
} |
q41747 | update_constants | train | def update_constants(nmrstar2cfg="", nmrstar3cfg="", resonance_classes_cfg="", spectrum_descriptions_cfg=""):
"""Update constant variables.
:return: None
:rtype: :py:obj:`None`
"""
nmrstar_constants = {}
resonance_classes = {}
spectrum_descriptions = {}
this_directory = os.path.dirname... | python | {
"resource": ""
} |
q41748 | list_spectrum_descriptions | train | def list_spectrum_descriptions(*args):
"""List all available spectrum descriptions that can be used for peak list simulation.
:param str args: Spectrum name(s), e.g. list_spectrum_descriptions("HNCO", "HNcoCACB"), leave empty to list everything.
:return: None
:rtype: :py:obj:`None`
"""
if args:... | python | {
"resource": ""
} |
q41749 | StarFile._is_nmrstar | train | def _is_nmrstar(string):
"""Test if input string is in NMR-STAR format.
:param string: Input string.
:type string: :py:class:`str` or :py:class:`bytes`
:return: Input string if in NMR-STAR format or False otherwise.
:rtype: :py:class:`str` or :py:obj:`False`
"""
... | python | {
"resource": ""
} |
q41750 | NMRStarFile._build_saveframe | train | def _build_saveframe(self, lexer):
"""Build NMR-STAR file saveframe.
:param lexer: instance of the lexical analyzer.
:type lexer: :func:`~nmrstarlib.bmrblex.bmrblex`
:return: Saveframe dictionary.
:rtype: :py:class:`collections.OrderedDict`
"""
odict = OrderedDic... | python | {
"resource": ""
} |
q41751 | NMRStarFile._build_loop | train | def _build_loop(self, lexer):
"""Build saveframe loop.
:param lexer: instance of lexical analyzer.
:type lexer: :func:`~nmrstarlib.bmrblex.bmrblex`
:return: Fields and values of the loop.
:rtype: :py:class:`tuple`
"""
fields = []
values = []
toke... | python | {
"resource": ""
} |
q41752 | NMRStarFile._skip_saveframe | train | def _skip_saveframe(self, lexer):
"""Skip entire saveframe - keep emitting tokens until the end of saveframe.
:param lexer: instance of the lexical analyzer class.
:type lexer: :class:`~nmrstarlib.bmrblex.bmrblex`
:return: None
:rtype: :py:obj:`None`
"""
token = ... | python | {
"resource": ""
} |
q41753 | NMRStarFile.print_saveframe | train | def print_saveframe(self, sf, f=sys.stdout, file_format="nmrstar", tw=3):
"""Print saveframe into a file or stdout.
We need to keep track of how far over everything is tabbed. The "tab width"
variable tw does this for us.
:param str sf: Saveframe name.
:param io.StringIO f: writ... | python | {
"resource": ""
} |
q41754 | NMRStarFile.print_loop | train | def print_loop(self, sf, sftag, f=sys.stdout, file_format="nmrstar", tw=3):
"""Print loop into a file or stdout.
:param str sf: Saveframe name.
:param str sftag: Saveframe tag, i.e. field name.
:param io.StringIO f: writable file-like stream.
:param str file_format: Format to us... | python | {
"resource": ""
} |
q41755 | NMRStarFile.chem_shifts_by_residue | train | def chem_shifts_by_residue(self, amino_acids=None, atoms=None, amino_acids_and_atoms=None, nmrstar_version="3"):
"""Organize chemical shifts by amino acid residue.
:param list amino_acids: List of amino acids three-letter codes.
:param list atoms: List of BMRB atom type codes.
:param di... | python | {
"resource": ""
} |
q41756 | Ndrive.GET | train | def GET(self, func, data):
"""Send GET request to execute Ndrive API
:param func: The function name you want to execute in Ndrive API.
:param params: Parameter data for HTTP request.
:returns: metadata when success or False when failed
"""
if func not in ['getRegisterUs... | python | {
"resource": ""
} |
q41757 | Ndrive.POST | train | def POST(self, func, data):
"""Send POST request to execute Ndrive API
:param func: The function name you want to execute in Ndrive API.
:param params: Parameter data for HTTP request.
:returns: ``metadata`` when success or ``False`` when failed
"""
s, message = self.ch... | python | {
"resource": ""
} |
q41758 | Ndrive.getRegisterUserInfo | train | def getRegisterUserInfo(self, svctype = "Android NDrive App ver", auth = 0):
"""Retrieve information about useridx
:param svctype: Information about the platform you are using right now.
:param auth: Authentication type
:return: ``True`` when success or ``False`` when failed
""... | python | {
"resource": ""
} |
q41759 | Ndrive.uploadFile | train | def uploadFile(self, file_obj, full_path, overwrite = False):
"""Upload a file as Ndrive really do.
>>> nd.uploadFile('~/flower.png','/Picture/flower.png',True)
This function imitates the process when Ndrive uploads a local file to its server. The process follows 7 steps:
1. ... | python | {
"resource": ""
} |
q41760 | Ndrive.getDiskSpace | train | def getDiskSpace(self):
"""Get disk space information.
>>> disk_info = nd.getDiskSpace()
:return: ``metadata`` if success or ``error message``
:metadata:
- expandablespace
- filemaxsize
- largefileminsize
- largefileunusedspa... | python | {
"resource": ""
} |
q41761 | Ndrive.checkUpload | train | def checkUpload(self, file_obj, full_path = '/', overwrite = False):
"""Check whether it is possible to upload a file.
>>> s = nd.checkUpload('~/flower.png','/Picture/flower.png')
:param file_obj: A file-like object to check whether possible to upload. You can pass a string as a file_obj o... | python | {
"resource": ""
} |
q41762 | Ndrive.put | train | def put(self, file_obj, full_path, overwrite = False):
"""Upload a file.
>>> nd.put('./flower.png','/Picture/flower.png')
>>> nd.put(open('./flower.png','r'),'/Picture/flower.png')
:param file_obj: A file-like object to check whether possible to upload. You can pass a string as... | python | {
"resource": ""
} |
q41763 | Ndrive.delete | train | def delete(self, full_path):
"""Delete a file in full_path
>>> nd.delete('/Picture/flower.png')
:param full_path: The full path to delete the file to, *including the file name*.
:return: ``True`` if success to delete the file or ``False``
"""
now = datetime.datetim... | python | {
"resource": ""
} |
q41764 | Ndrive.getList | train | def getList(self, full_path, type = 1, dept = 0, sort = 'name', order = 'asc', startnum = 0, pagingrow = 1000, dummy = 56184):
"""Get a list of files
>>> nd_list = nd.getList('/', type=3)
>>> print nd_list
There are 5 kinds of ``type``:
- 1 => only directories with ... | python | {
"resource": ""
} |
q41765 | Ndrive.makeDirectory | train | def makeDirectory(self, full_path, dummy = 40841):
"""Make a directory
>>> nd.makeDirectory('/test')
:param full_path: The full path to get the directory property. Should be end with '/'.
:return: ``True`` when success to make a directory or ``False``
"""
i... | python | {
"resource": ""
} |
q41766 | Ndrive.makeShareUrl | train | def makeShareUrl(self, full_path, passwd):
"""Make a share url of directory
>>> nd.makeShareUrl('/Picture/flower.png', PASSWORD)
Args:
full_path:
The full path of directory to get share url.
Should be end with '/'.
ex) /folder/
... | python | {
"resource": ""
} |
q41767 | Ndrive.getFileLink | train | def getFileLink(self, full_path):
"""Get a link of file
>>> file_link = nd.getFileLink('/Picture/flower.png')
:param full_path: The full path of file to get file link. Path should start and end with '/'.
:return: ``Shared url`` or ``False`` if failed to share a file or di... | python | {
"resource": ""
} |
q41768 | Ndrive.createFileLink | train | def createFileLink(self, resourceno):
"""Make a link of file
If you don't know ``resourceno``, you'd better use ``getFileLink``.
:param resourceno: Resource number of a file to create link
:return: ``Shared url`` or ``False`` when failed to share a file
"""
data = {'_c... | python | {
"resource": ""
} |
q41769 | Ndrive.getProperty | train | def getProperty(self, full_path, dummy = 56184):
"""Get a file property
:param full_path: The full path to get the file or directory property.
:return: ``metadata`` if success or ``False`` if failed to get property
:metadata:
- creationdate
- exif
... | python | {
"resource": ""
} |
q41770 | Ndrive.getVersionList | train | def getVersionList(self, full_path, startnum = 0, pagingrow = 50, dummy = 54213):
"""Get a version list of a file or dierectory.
:param full_path: The full path to get the file or directory property. Path should start with '/'
:param startnum: Start version index.
:param pagingrow: Max ... | python | {
"resource": ""
} |
q41771 | Ndrive.setProperty | train | def setProperty(self, full_path, protect, dummy = 7046):
"""Set property of a file.
:param full_path: The full path to get the file or directory property.
:param protect: 'Y' or 'N', 중요 표시
:return: ``True`` when success to set property or ``False``
"""
data = {'orgresou... | python | {
"resource": ""
} |
q41772 | _choose_read_fs | train | def _choose_read_fs(authority, cache, read_path, version_check, hasher):
'''
Context manager returning the appropriate up-to-date readable filesystem
Use ``cache`` if it is a valid filessystem and has a file at
``read_path``, otherwise use ``authority``. If the file at
``read_path`` is out of date,... | python | {
"resource": ""
} |
q41773 | _get_write_fs | train | def _get_write_fs():
'''
Context manager returning a writable filesystem
Use a temporary directory and clean on exit.
.. todo::
Evaluate options for using a cached memoryFS or streaming object
instead of an OSFS(tmp). This could offer significant performance
improvements. Writ... | python | {
"resource": ""
} |
q41774 | _prepare_write_fs | train | def _prepare_write_fs(read_fs, cache, read_path, readwrite_mode=True):
'''
Prepare a temporary filesystem for writing to read_path
The file will be moved to write_path on close if modified.
'''
with _get_write_fs() as write_fs:
# If opening in read/write or append mode, make sure file dat... | python | {
"resource": ""
} |
q41775 | text_cleanup | train | def text_cleanup(data, key, last_type):
""" I strip extra whitespace off multi-line strings if they are ready to be stripped!"""
if key in data and last_type == STRING_TYPE:
data[key] = data[key].strip()
return data | python | {
"resource": ""
} |
q41776 | rst_to_json | train | def rst_to_json(text):
""" I convert Restructured Text with field lists into Dictionaries!
TODO: Convert to text node approach.
"""
records = []
last_type = None
key = None
data = {}
directive = False
lines = text.splitlines()
for index, line in enumerate(lines):
#... | python | {
"resource": ""
} |
q41777 | type_converter | train | def type_converter(text):
""" I convert strings into integers, floats, and strings! """
if text.isdigit():
return int(text), int
try:
return float(text), float
except ValueError:
return text, STRING_TYPE | python | {
"resource": ""
} |
q41778 | command_line_runner | train | def command_line_runner():
""" I run functions from the command-line! """
filename = sys.argv[-1]
if not filename.endswith(".rst"):
print("ERROR! Please enter a ReStructuredText filename!")
sys.exit()
print(rst_to_json(file_opener(filename))) | python | {
"resource": ""
} |
q41779 | packb | train | def packb(obj, **kwargs):
"""wrap msgpack.packb, setting use_bin_type=True by default"""
kwargs.setdefault('use_bin_type', True)
return msgpack.packb(obj, **kwargs) | python | {
"resource": ""
} |
q41780 | AudioPlayer.play | train | def play(cls, file_path, on_done=None, logger=None):
""" Play an audio file.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback completes.
"""
pygame.mixer.init()
try:
pygame.mixer.music.load(file_path)
except... | python | {
"resource": ""
} |
q41781 | AudioPlayer.play_async | train | def play_async(cls, file_path, on_done=None):
""" Play an audio file asynchronously.
:param file_path: the path to the file to play.
:param on_done: callback when audio playback completes.
"""
thread = threading.Thread(
target=AudioPlayer.play, args=(file_path, on_do... | python | {
"resource": ""
} |
q41782 | LiquidCrystal.left_to_right | train | def left_to_right(self):
"""This is for text that flows Left to Right"""
self._entry_mode |= Command.MODE_INCREMENT
self.command(self._entry_mode) | python | {
"resource": ""
} |
q41783 | LiquidCrystal.right_to_left | train | def right_to_left(self):
"""This is for text that flows Right to Left"""
self._entry_mode &= ~Command.MODE_INCREMENT
self.command(self._entry_mode) | python | {
"resource": ""
} |
q41784 | TempFileSystemStorage.get_available_name | train | def get_available_name(self, name, max_length=None):
"""Return relative path to name placed in random directory"""
tempdir = tempfile.mkdtemp(dir=self.base_location)
name = os.path.join(
os.path.basename(tempdir),
os.path.basename(name),
)
method = super(T... | python | {
"resource": ""
} |
q41785 | yn_prompt | train | def yn_prompt(text):
'''
Takes the text prompt, and presents it, takes only "y" or "n" for
answers, and returns True or False. Repeats itself on bad input.
'''
text = "\n"+ text + "\n('y' or 'n'): "
while True:
answer = input(text).strip()
if answer != 'y' and answer !... | python | {
"resource": ""
} |
q41786 | underline | train | def underline(text):
'''Takes a string, and returns it underscored.'''
text += "\n"
for i in range(len(text)-1):
text += "="
text += "\n"
return text | python | {
"resource": ""
} |
q41787 | get_event_time_as_utc | train | def get_event_time_as_utc(voevent, index=0):
"""
Extracts the event time from a given `WhereWhen.ObsDataLocation`.
Returns a datetime (timezone-aware, UTC).
Accesses a `WhereWhere.ObsDataLocation.ObservationLocation`
element and returns the AstroCoords.Time.TimeInstant.ISOTime element,
convert... | python | {
"resource": ""
} |
q41788 | get_event_position | train | def get_event_position(voevent, index=0):
"""Extracts the `AstroCoords` from a given `WhereWhen.ObsDataLocation`.
Note that a packet may include multiple 'ObsDataLocation' entries
under the 'WhereWhen' section, for example giving locations of an object
moving over time. Most packets will have only one,... | python | {
"resource": ""
} |
q41789 | get_grouped_params | train | def get_grouped_params(voevent):
"""
Fetch grouped Params from the `What` section of a voevent as an omdict.
This fetches 'grouped' Params, i.e. those enclosed in a Group element,
and returns them as a nested dict-like structure, keyed by
GroupName->ParamName->AttribName.
Note that since multi... | python | {
"resource": ""
} |
q41790 | get_toplevel_params | train | def get_toplevel_params(voevent):
"""
Fetch ungrouped Params from the `What` section of a voevent as an omdict.
This fetches 'toplevel' Params, i.e. those not enclosed in a Group element,
and returns them as a nested dict-like structure, keyed like
ParamName->AttribName.
Note that since multip... | python | {
"resource": ""
} |
q41791 | prettystr | train | def prettystr(subtree):
"""Print an element tree with nice indentation.
Prettyprinting a whole VOEvent often doesn't seem to work, probably for
issues relating to whitespace cf.
http://lxml.de/FAQ.html#why-doesn-t-the-pretty-print-option-reformat-my-xml-output
This function is a quick workaround fo... | python | {
"resource": ""
} |
q41792 | Server.start | train | def start(self):
""" Start the MQTT client. """
self.thread_handler.run(target=self.start_blocking)
self.thread_handler.start_run_loop() | python | {
"resource": ""
} |
q41793 | Server.start_blocking | train | def start_blocking(self, run_event):
""" Start the MQTT client, as a blocking method.
:param run_event: a run event object provided by the thread handler.
"""
topics = [("hermes/intent/#", 0), ("hermes/hotword/#", 0), ("hermes/asr/#", 0), ("hermes/nlu/#", 0),
("snipsma... | python | {
"resource": ""
} |
q41794 | Server.on_connect | train | def on_connect(self, client, userdata, flags, result_code):
""" Callback when the MQTT client is connected.
:param client: the client being connected.
:param userdata: unused.
:param flags: unused.
:param result_code: result code.
"""
self.log_info("Connected wit... | python | {
"resource": ""
} |
q41795 | Server.on_disconnect | train | def on_disconnect(self, client, userdata, result_code):
""" Callback when the MQTT client is disconnected. In this case,
the server waits five seconds before trying to reconnected.
:param client: the client being disconnected.
:param userdata: unused.
:param result_code: res... | python | {
"resource": ""
} |
q41796 | Token.list | train | def list(self, identity_id, per_page=20, page=1):
""" Get a list of tokens
:param identity_id: The ID of the identity to retrieve tokens for
:param per_page: The number of results per page returned
:param page: The page number of the results
:return: dict of REST... | python | {
"resource": ""
} |
q41797 | Token.create | train | def create(self, identity_id, service, token):
""" Create the token
:param identity_id: The ID of the identity to retrieve
:param service: The service that the token is linked to
:param token: The token provided by the the service
:param expires_at: Set an expiry... | python | {
"resource": ""
} |
q41798 | Token.update | train | def update(self, identity_id, service, token=None):
""" Update the token
:param identity_id: The ID of the identity to retrieve
:return: dict of REST API output with headers attached
:rtype: :class:`~datasift.request.DictResponse`
:raises: :class:`~datasift.excep... | python | {
"resource": ""
} |
q41799 | AutoCloudProcessor._func_router | train | def _func_router(self, msg, fname, **config):
"""
This method routes the messages based on the params and calls the
appropriate method to process the message. The utility of the method is
to cope up with the major message change during different releases.
"""
FNAME = 'han... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.