_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q12700 | RemoteFile.close | train | def close(self):
"""in write mode, closing the handle adds the sentinel value into the
queue and joins the thread executing the HTTP request. in read mode,
this clears out the read response object so there are no references
to it, and the resources can be reclaimed.
"""
... | python | {
"resource": ""
} |
q12701 | ChartView.get | train | def get(self, request, *args, **kwargs):
"""
Main entry. This View only responds to GET requests.
"""
context = self.chart_instance.chartjs_configuration(*args, **kwargs)
return self.render_json_response(context) | python | {
"resource": ""
} |
q12702 | BblfshClient.parse | train | def parse(self, filename: str, language: Optional[str]=None,
contents: Optional[str]=None, mode: Optional[ModeType]=None,
timeout: Optional[int]=None) -> ResultContext:
"""
Queries the Babelfish server and receives the UAST response for the specified
file.
:p... | python | {
"resource": ""
} |
q12703 | BblfshClient.close | train | def close(self) -> None:
"""
Close the gRPC channel and free the acquired resources. Using a closed client is
not supported.
"""
self._channel.close()
self._channel = self._stub_v1 = self._stub_v2 = None | python | {
"resource": ""
} |
q12704 | filter_string | train | def filter_string(n: Node, query: str) -> str:
"""
Filter and ensure that the returned value is of string type.
"""
return _scalariter2item(n, query, str) | python | {
"resource": ""
} |
q12705 | filter_bool | train | def filter_bool(n: Node, query: str) -> bool:
"""
Filter and ensure that the returned value is of type bool.
"""
return _scalariter2item(n, query, bool) | python | {
"resource": ""
} |
q12706 | CompatBblfshClient.parse | train | def parse(self, filename: str, language: str = None, contents: str = None,
timeout: float = None) -> CompatParseResponse:
"""
Parse the specified filename or contents and return a CompatParseResponse.
"""
return self._parse(filename, language, contents, timeout,
... | python | {
"resource": ""
} |
q12707 | CompatNodeIterator.filter | train | def filter(self, query: str) -> Optional['CompatNodeIterator']:
"""
Further filter the results using this iterator as base.
"""
if not self._last_node:
return None
return filter(self._last_node, query) | python | {
"resource": ""
} |
q12708 | CompatNodeIterator.properties | train | def properties(self) -> dict:
"""
Returns the properties of the current node in the iteration.
"""
if isinstance(self._last_node, dict):
return self._last_node.keys()
else:
return {} | python | {
"resource": ""
} |
q12709 | create_catalog_by_name | train | def create_catalog_by_name(name, T="general"):
"""
Creates a catalog object, with a given name. Does not check to see if the catalog already exists.
Create a catalog object like
"""
result = util.callm("catalog/create", {}, POST=True,
data={"name":name, "type":T})
r... | python | {
"resource": ""
} |
q12710 | list_catalogs | train | def list_catalogs(results=30, start=0):
"""
Returns list of all catalogs created on this API key
Args:
Kwargs:
results (int): An integer number of results to return
start (int): An integer starting value for the result set
Returns:
A list of catalog objects
Example:
... | python | {
"resource": ""
} |
q12711 | Catalog.update | train | def update(self, items):
"""
Update a catalog object
Args:
items (list): A list of dicts describing update data and action codes (see api docs)
Kwargs:
Returns:
A ticket id
Example:
>>> c = catalog.Catalog('my_songs', type='song')
... | python | {
"resource": ""
} |
q12712 | Catalog.read_items | train | def read_items(self, buckets=None, results=15, start=0,item_ids=None):
"""
Returns data from the catalog; also expanded for the requested buckets.
This method is provided for backwards-compatibility
Args:
Kwargs:
buckets (list): A list of strings specifying which bu... | python | {
"resource": ""
} |
q12713 | Catalog.get_item_dicts | train | def get_item_dicts(self, buckets=None, results=15, start=0,item_ids=None):
"""
Returns data from the catalog; also expanded for the requested buckets
Args:
Kwargs:
buckets (list): A list of strings specifying which buckets to retrieve
results (int): An integer ... | python | {
"resource": ""
} |
q12714 | _show_one | train | def _show_one(audio_file):
"given an audio file, print out the artist, title and some audio attributes of the song"
print 'File: ', audio_file
pytrack = track.track_from_filename(audio_file)
print 'Artist: ', pytrack.artist if hasattr(pytrack, 'artist') else 'Unknown'
print 'Title: ... | python | {
"resource": ""
} |
q12715 | show_attrs | train | def show_attrs(directory):
"print out the tempo for each audio file in the given directory"
for f in os.listdir(directory):
if _is_audio(f):
path = os.path.join(directory, f)
_show_one(path) | python | {
"resource": ""
} |
q12716 | search | train | def search(title=None, artist=None, artist_id=None, combined=None, description=None, style=None, mood=None,
results=None, start=None, max_tempo=None, min_tempo=None,
max_duration=None, min_duration=None, max_loudness=None, min_loudness=None,
artist_max_familiarity=None, artist_min_famil... | python | {
"resource": ""
} |
q12717 | _track_from_response | train | def _track_from_response(result, timeout):
"""
This is the function that actually creates the track object
"""
response = result['response']
status = response['track']['status'].lower()
if status == 'pending':
# Need to wait for async upload or analyze call to finish.
result = _... | python | {
"resource": ""
} |
q12718 | _upload | train | def _upload(param_dict, timeout, data):
"""
Calls upload either with a local audio file,
or a url. Returns a track object.
"""
param_dict['format'] = 'json'
param_dict['wait'] = 'true'
param_dict['bucket'] = 'audio_summary'
result = util.callm('track/upload', param_dict, POST = True, soc... | python | {
"resource": ""
} |
q12719 | track_from_file | train | def track_from_file(file_object, filetype, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
"""
Create a track object from a file-like object.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
file_object: a file-like Python object
... | python | {
"resource": ""
} |
q12720 | track_from_filename | train | def track_from_filename(filename, filetype = None, timeout=DEFAULT_ASYNC_TIMEOUT, force_upload=False):
"""
Create a track object from a filename.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
filename: A string containing the path to t... | python | {
"resource": ""
} |
q12721 | track_from_url | train | def track_from_url(url, timeout=DEFAULT_ASYNC_TIMEOUT):
"""
Create a track object from a public http URL.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
url: A string giving the URL to read from. This must be on a public machine accessi... | python | {
"resource": ""
} |
q12722 | track_from_id | train | def track_from_id(identifier, timeout=DEFAULT_ASYNC_TIMEOUT):
"""
Create a track object from an Echo Nest track ID.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
identifier: A string containing the ID of a previously analyzed track.
... | python | {
"resource": ""
} |
q12723 | track_from_md5 | train | def track_from_md5(md5, timeout=DEFAULT_ASYNC_TIMEOUT):
"""
Create a track object from an md5 hash.
NOTE: Does not create the detailed analysis for the Track. Call
Track.get_analysis() for that.
Args:
md5: A string 32 characters long giving the md5 checksum of a track already analyzed.
... | python | {
"resource": ""
} |
q12724 | Track.get_analysis | train | def get_analysis(self):
""" Retrieve the detailed analysis for the track, if available.
Raises Exception if unable to create the detailed analysis. """
if self.analysis_url:
try:
# Try the existing analysis_url first. This expires shortly
# after ... | python | {
"resource": ""
} |
q12725 | get_tempo | train | def get_tempo(artist, title):
"gets the tempo for a song"
results = song.search(artist=artist, title=title, results=1, buckets=['audio_summary'])
if len(results) > 0:
return results[0].audio_summary['tempo']
else:
return None | python | {
"resource": ""
} |
q12726 | suggest | train | def suggest(q='', results=15, buckets=None, limit=False, max_familiarity=None, min_familiarity=None,
max_hotttnesss=None, min_hotttnesss=None):
"""Suggest artists based upon partial names.
Args:
Kwargs:
q (str): The text to suggest artists from
results (int): An integer nu... | python | {
"resource": ""
} |
q12727 | Artist.get_twitter_id | train | def get_twitter_id(self, cache=True):
"""Get the twitter id for this artist if it exists
Args:
Kwargs:
Returns:
A twitter ID string
Example:
>>> a = artist.Artist('big boi')
>>> a.get_twitter_id()
u'BigBoi'
>>>
"""
... | python | {
"resource": ""
} |
q12728 | run | train | def run(self, bundle,
container_id=None,
log_path=None,
pid_file=None,
log_format="kubernetes"):
''' run is a wrapper to create, start, attach, and delete a container.
Equivalent command line example:
singularity oci run -b ~/bundle m... | python | {
"resource": ""
} |
q12729 | create | train | def create(self, bundle,
container_id=None,
empty_process=False,
log_path=None,
pid_file=None,
sync_socket=None,
log_format="kubernetes"):
''' use the client to create a container from a bundle directory. The bun... | python | {
"resource": ""
} |
q12730 | _run | train | def _run(self, bundle,
container_id=None,
empty_process=False,
log_path=None,
pid_file=None,
sync_socket=None,
command="run",
log_format="kubernetes"):
''' _run is the base function for run and create, the onl... | python | {
"resource": ""
} |
q12731 | delete | train | def delete(self, container_id=None, sudo=None):
'''delete an instance based on container_id.
Parameters
==========
container_id: the container_id to delete
sudo: whether to issue the command with sudo (or not)
a container started with sudo will belong to the root user
... | python | {
"resource": ""
} |
q12732 | attach | train | def attach(self, container_id=None, sudo=False):
'''attach to a container instance based on container_id
Parameters
==========
container_id: the container_id to delete
sudo: whether to issue the command with sudo (or not)
a container started with sudo will belong to the roo... | python | {
"resource": ""
} |
q12733 | execute | train | def execute(self, command=None, container_id=None, sudo=False, stream=False):
'''execute a command to a container instance based on container_id
Parameters
==========
container_id: the container_id to delete
command: the command to execute to the container
sudo: whether to issue ... | python | {
"resource": ""
} |
q12734 | update | train | def update(self, container_id, from_file=None):
'''update container cgroup resources for a specific container_id,
The container must have state "running" or "created."
Singularity Example:
singularity oci update [update options...] <container_ID>
singularity oci update --from-fi... | python | {
"resource": ""
} |
q12735 | get_client | train | def get_client(quiet=False, debug=False):
'''
get the client and perform imports not on init, in case there are any
initialization or import errors.
Parameters
==========
quiet: if True, suppress most output about the client
debug: turn on debugging mode
'''
from... | python | {
"resource": ""
} |
q12736 | start | train | def start(self, image=None, name=None, args=None, sudo=False, options=[], capture=False):
'''start an instance. This is done by default when an instance is created.
Parameters
==========
image: optionally, an image uri (if called as a command from Client)
name: a name for the instance
... | python | {
"resource": ""
} |
q12737 | parse_labels | train | def parse_labels(result):
'''fix up the labels, meaning parse to json if needed, and return
original updated object
Parameters
==========
result: the json object to parse from inspect
'''
if "data" in result:
labels = result['data']['attributes'].get('labels') or {}
... | python | {
"resource": ""
} |
q12738 | ipython | train | def ipython(image):
'''give the user an ipython shell
'''
# The client will announce itself (backend/database) unless it's get
from spython.main import get_client
from spython.main.parse import ( DockerRecipe, SingularityRecipe )
client = get_client()
client.load(image)
# Add recipe p... | python | {
"resource": ""
} |
q12739 | SingularityRecipe._setup | train | def _setup(self, lines):
'''setup required adding content from the host to the rootfs,
so we try to capture with with ADD.
'''
bot.warning('SETUP is error prone, please check output.')
for line in lines:
# For all lines, replace rootfs with actual root /
... | python | {
"resource": ""
} |
q12740 | SingularityRecipe._comments | train | def _comments(self, lines):
''' comments is a wrapper for comment, intended to be given a list
of comments.
Parameters
==========
lines: the list of lines to parse
'''
for line in lines:
comment = self._comment(line)
... | python | {
"resource": ""
} |
q12741 | SingularityRecipe._run | train | def _run(self, lines):
'''_parse the runscript to be the Docker CMD. If we have one line,
call it directly. If not, write the entrypoint into a script.
Parameters
==========
lines: the line from the recipe file to parse for CMD
'''
lines = [x for x ... | python | {
"resource": ""
} |
q12742 | SingularityRecipe._get_mapping | train | def _get_mapping(self, section):
'''mapping will take the section name from a Singularity recipe
and return a map function to add it to the appropriate place.
Any lines that don't cleanly map are assumed to be comments.
Parameters
==========
section: the... | python | {
"resource": ""
} |
q12743 | SingularityRecipe._load_from | train | def _load_from(self, line):
'''load the From section of the recipe for the Dockerfile.
'''
# Remove any comments
line = line.split('#',1)[0]
line = re.sub('(F|f)(R|r)(O|o)(M|m):','', line).strip()
bot.info('FROM %s' %line)
self.config['from'] = line | python | {
"resource": ""
} |
q12744 | SingularityRecipe._load_section | train | def _load_section(self, lines, section):
'''read in a section to a list, and stop when we hit the next section
'''
members = []
while True:
if len(lines) == 0:
break
next_line = lines[0]
# The end of a section
... | python | {
"resource": ""
} |
q12745 | SingularityRecipe.load_recipe | train | def load_recipe(self):
'''load will return a loaded in singularity recipe. The idea
is that these sections can then be parsed into a Dockerfile,
or printed back into their original form.
Returns
=======
config: a parsed recipe Singularity recipe
''... | python | {
"resource": ""
} |
q12746 | OciImage.get_container_id | train | def get_container_id(self, container_id=None):
''' a helper function shared between functions that will return a
container_id. First preference goes to a container_id provided by
the user at runtime. Second preference goes to the container_id
instantiated with the client.
... | python | {
"resource": ""
} |
q12747 | OciImage._init_command | train | def _init_command(self, action, flags=None):
''' a wrapper to the base init_command, ensuring that "oci" is added
to each command
Parameters
==========
action: the main action to perform (e.g., build)
flags: one or more additional flags (e.g, volumes)... | python | {
"resource": ""
} |
q12748 | export | train | def export(self, image_path, tmptar=None):
'''export will export an image, sudo must be used.
Parameters
==========
image_path: full path to image
tmptar: if defined, use custom temporary path for tar export
'''
from spython.utils import check_install
check_install()
... | python | {
"resource": ""
} |
q12749 | parse_table | train | def parse_table(table_string, header, remove_rows=1):
'''parse a table to json from a string, where a header is expected by default.
Return a jsonified table.
Parameters
==========
table_string: the string table, ideally with a header
header: header of expected table, must match ... | python | {
"resource": ""
} |
q12750 | get | train | def get(self, name, return_json=False, quiet=False):
'''get is a list for a single instance. It is assumed to be running,
and we need to look up the PID, etc.
'''
from spython.utils import check_install
check_install()
# Ensure compatible for singularity prior to 3.0, and after 3.0
subgr... | python | {
"resource": ""
} |
q12751 | set_verbosity | train | def set_verbosity(args):
'''determine the message level in the environment to set based on args.
'''
level = "INFO"
if args.debug is True:
level = "DEBUG"
elif args.quiet is True:
level = "QUIET"
os.environ['MESSAGELEVEL'] = level
os.putenv('MESSAGELEVEL', level)
os.env... | python | {
"resource": ""
} |
q12752 | run_command | train | def run_command(self, cmd,
sudo=False,
capture=True,
quiet=None,
return_result=False):
'''run_command is a wrapper for the global run_command, checking first
for sudo and exiting on error if needed. The message is retur... | python | {
"resource": ""
} |
q12753 | Recipe.load | train | def load(self, recipe):
'''load a recipe file into the client, first performing checks, and
then parsing the file.
Parameters
==========
recipe: the original recipe file, parsed by the subclass either
DockerRecipe or SingularityRecipe
'''
... | python | {
"resource": ""
} |
q12754 | Recipe.parse | train | def parse(self):
'''parse is the base function for parsing the recipe, whether it be
a Dockerfile or Singularity recipe. The recipe is read in as lines,
and saved to a list if needed for the future. If the client has
it, the recipe type specific _parse function is called.
... | python | {
"resource": ""
} |
q12755 | Recipe.convert | train | def convert(self, convert_to=None,
runscript="/bin/bash",
force=False):
'''This is a convenience function for the user to easily call to get
the most likely desired result, conversion to the opposite format.
We choose the selection based on th... | python | {
"resource": ""
} |
q12756 | Recipe._get_converter | train | def _get_converter(self, convert_to=None):
'''see convert and save. This is a helper function that returns
the proper conversion function, but doesn't call it. We do this
so that in the case of convert, we do the conversion and return
a string. In the case of save, we save the ... | python | {
"resource": ""
} |
q12757 | Recipe._get_conversion_outfile | train | def _get_conversion_outfile(self, convert_to=None):
'''a helper function to return a conversion temporary output file
based on kind of conversion
Parameters
==========
convert_to: a string either docker or singularity, if a different
'''
conversion =... | python | {
"resource": ""
} |
q12758 | Recipe._get_conversion_type | train | def _get_conversion_type(self, convert_to=None):
'''a helper function to return the conversion type based on user
preference and input recipe.
Parameters
==========
convert_to: a string either docker or singularity (default None)
'''
acceptable = ['... | python | {
"resource": ""
} |
q12759 | Recipe._write_script | train | def _write_script(path, lines, chmod=True):
'''write a script with some lines content to path in the image. This
is done by way of adding echo statements to the install section.
Parameters
==========
path: the path to the file to write
lines: the lines to ... | python | {
"resource": ""
} |
q12760 | resume | train | def resume(self, container_id=None, sudo=None):
''' resume a stopped OciImage container, if it exists
Equivalent command line example:
singularity oci resume <container_ID>
Parameters
==========
container_id: the id to stop.
sudo: Add sudo to the... | python | {
"resource": ""
} |
q12761 | pause | train | def pause(self, container_id=None, sudo=None):
''' pause a running OciImage container, if it exists
Equivalent command line example:
singularity oci pause <container_ID>
Parameters
==========
container_id: the id to stop.
sudo: Add sudo to the co... | python | {
"resource": ""
} |
q12762 | stopall | train | def stopall(self, sudo=False, quiet=True):
'''stop ALL instances. This command is only added to the command group
as it doesn't make sense to call from a single instance
Parameters
==========
sudo: if the command should be done with sudo (exposes different set of
instances)... | python | {
"resource": ""
} |
q12763 | println | train | def println(self, output, quiet=False):
'''print will print the output, given that quiet is not True. This
function also serves to convert output in bytes to utf-8
Parameters
==========
output: the string to print
quiet: a runtime variable to over-ride the default.
'''
i... | python | {
"resource": ""
} |
q12764 | help | train | def help(self, command=None):
'''help prints the general function help, or help for a specific command
Parameters
==========
command: the command to get help for, if none, prints general help
'''
from spython.utils import check_install
check_install()
cmd = ['singularit... | python | {
"resource": ""
} |
q12765 | Instance.generate_name | train | def generate_name(self, name=None):
'''generate a Robot Name for the instance to use, if the user doesn't
supply one.
'''
# If no name provided, use robot name
if name == None:
name = self.RobotNamer.generate()
self.name = name.replace('-','_') | python | {
"resource": ""
} |
q12766 | Instance._update_metadata | train | def _update_metadata(self, kwargs=None):
'''Extract any additional attributes to hold with the instance
from kwargs
'''
# If not given metadata, use instance.list to get it for container
if kwargs == None and hasattr(self, 'name'):
kwargs = self._list(self.name, q... | python | {
"resource": ""
} |
q12767 | mount | train | def mount(self, image, sudo=None):
'''create an OCI bundle from SIF image
Parameters
==========
image: the container (sif) to mount
'''
return self._state_command(image, command="mount", sudo=sudo) | python | {
"resource": ""
} |
q12768 | main | train | def main(args, options, parser):
'''This function serves as a wrapper around the DockerRecipe and
SingularityRecipe converters. We can either save to file if
args.outfile is defined, or print to the console if not.
'''
from spython.main.parse import ( DockerRecipe, SingularityRecipe )
# ... | python | {
"resource": ""
} |
q12769 | DockerRecipe._setup | train | def _setup(self, action, line):
''' replace the command name from the group, alert the user of content,
and clean up empty spaces
'''
bot.debug('[in] %s' % line)
# Replace ACTION at beginning
line = re.sub('^%s' % action, '', line)
# Handle continuation lin... | python | {
"resource": ""
} |
q12770 | DockerRecipe._run | train | def _run(self, line):
''' everything from RUN goes into the install list
Parameters
==========
line: the line from the recipe file to parse for FROM
'''
line = self._setup('RUN', line)
self.install += line | python | {
"resource": ""
} |
q12771 | DockerRecipe._add | train | def _add(self, lines):
'''Add can also handle https, and compressed files.
Parameters
==========
line: the line from the recipe file to parse for ADD
'''
lines = self._setup('ADD', lines)
for line in lines:
values = line.split(" ")
... | python | {
"resource": ""
} |
q12772 | DockerRecipe._parse_http | train | def _parse_http(self, url, dest):
'''will get the filename of an http address, and return a statement
to download it to some location
Parameters
==========
url: the source url to retrieve with curl
dest: the destination folder to put it in the image
... | python | {
"resource": ""
} |
q12773 | DockerRecipe._parse_archive | train | def _parse_archive(self, targz, dest):
'''parse_targz will add a line to the install script to extract a
targz to a location, and also add it to the files.
Parameters
==========
targz: the targz to extract
dest: the location to extract it to
'''
... | python | {
"resource": ""
} |
q12774 | DockerRecipe._workdir | train | def _workdir(self, line):
'''A Docker WORKDIR command simply implies to cd to that location
Parameters
==========
line: the line from the recipe file to parse for WORKDIR
'''
workdir = self._setup('WORKDIR', line)
line = "cd %s" %(''.join(workdir))
... | python | {
"resource": ""
} |
q12775 | DockerRecipe._get_mapping | train | def _get_mapping(self, line, parser=None, previous=None):
'''mapping will take the command from a Dockerfile and return a map
function to add it to the appropriate place. Any lines that don't
cleanly map are assumed to be comments.
Parameters
==========
li... | python | {
"resource": ""
} |
q12776 | DockerRecipe._parse | train | def _parse(self):
'''parse is the base function for parsing the Dockerfile, and extracting
elements into the correct data structures. Everything is parsed into
lists or dictionaries that can be assembled again on demand.
Environment: Since Docker also exports environment as we... | python | {
"resource": ""
} |
q12777 | ImageBase.remove_uri | train | def remove_uri(self, image):
'''remove_image_uri will return just the image name.
this will also remove all spaces from the uri.
'''
image = image or ''
uri = self.get_uri(image) or ''
image = image.replace('%s://' %uri,'', 1)
return image.strip('-').rstrip('/'... | python | {
"resource": ""
} |
q12778 | create | train | def create(self,image_path, size=1024, sudo=False):
'''create will create a a new image
Parameters
==========
image_path: full path to image
size: image sizein MiB, default is 1024MiB
filesystem: supported file systems ext3/ext4 (ext[2/3]: default ext3
'''
f... | python | {
"resource": ""
} |
q12779 | check_install | train | def check_install(software='singularity', quiet=True):
'''check_install will attempt to run the singularity command, and
return True if installed. The command line utils will not run
without this check.
'''
cmd = [software, '--version']
found = False
try:
version = run_comma... | python | {
"resource": ""
} |
q12780 | get_singularity_version | train | def get_singularity_version():
'''get the singularity client version. Useful in the case that functionality
has changed, etc. Can be "hacked" if needed by exporting
SPYTHON_SINGULARITY_VERSION, which is checked before checking on the
command line.
'''
version = os.environ.get('SPYTHON_... | python | {
"resource": ""
} |
q12781 | get_requirements | train | def get_requirements(lookup=None):
'''get_requirements reads in requirements and versions from
the lookup obtained with get_lookup'''
if lookup == None:
lookup = get_lookup()
install_requires = []
for module in lookup['INSTALL_REQUIRES']:
module_name = module[0]
module_meta... | python | {
"resource": ""
} |
q12782 | load | train | def load(self, image=None):
'''load an image, either an actual path on the filesystem or a uri.
Parameters
==========
image: the image path or uri to load (e.g., docker://ubuntu
'''
from spython.image import Image
from spython.instance import Instance
self.simage = Image(ima... | python | {
"resource": ""
} |
q12783 | generate_oci_commands | train | def generate_oci_commands():
''' The oci command group will allow interaction with an image using
OCI commands.
'''
from spython.oci import OciImage
from spython.main.base.logger import println
# run_command uses run_cmd, but wraps to catch error
from spython.main.base.command import (... | python | {
"resource": ""
} |
q12784 | create_runscript | train | def create_runscript(self, default="/bin/bash", force=False):
'''create_entrypoint is intended to create a singularity runscript
based on a Docker entrypoint or command. We first use the Docker
ENTRYPOINT, if defined. If not, we use the CMD. If neither is found,
we use function default.
... | python | {
"resource": ""
} |
q12785 | finish_section | train | def finish_section(section, name):
'''finish_section will add the header to a section, to finish the recipe
take a custom command or list and return a section.
Parameters
==========
section: the section content, without a header
name: the name of the section for the header
'... | python | {
"resource": ""
} |
q12786 | create_env_section | train | def create_env_section(pairs, name):
'''environment key value pairs need to be joined by an equal, and
exported at the end.
Parameters
==========
section: the list of values to return as a parsed list of lines
name: the name of the section to write (e.g., files)
'''
section... | python | {
"resource": ""
} |
q12787 | abbreviate_str | train | def abbreviate_str(string, max_len=80, indicator="..."):
"""
Abbreviate a string, adding an indicator like an ellipsis if required.
"""
if not string or not max_len or len(string) <= max_len:
return string
elif max_len <= len(indicator):
return string[0:max_len]
else:
return string[0:max_len - l... | python | {
"resource": ""
} |
q12788 | abbreviate_list | train | def abbreviate_list(items, max_items=10, item_max_len=40, joiner=", ", indicator="..."):
"""
Abbreviate a list, truncating each element and adding an indicator at the end if the
whole list was truncated. Set item_max_len to None or 0 not to truncate items.
"""
if not items:
return items
else:
shorte... | python | {
"resource": ""
} |
q12789 | make_parent_dirs | train | def make_parent_dirs(path, mode=0o777):
"""
Ensure parent directories of a file are created as needed.
"""
parent = os.path.dirname(path)
if parent:
make_all_dirs(parent, mode)
return path | python | {
"resource": ""
} |
q12790 | atomic_output_file | train | def atomic_output_file(dest_path, make_parents=False, backup_suffix=None, suffix=".partial.%s"):
"""
A context manager for convenience in writing a file or directory in an atomic way. Set up
a temporary name, then rename it after the operation is done, optionally making a backup of
the previous file or director... | python | {
"resource": ""
} |
q12791 | temp_output_file | train | def temp_output_file(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False):
"""
A context manager for convenience in creating a temporary file,
which is deleted when exiting the context.
Usage:
with temp_output_file() as (fd, path):
...
"""
return _temp_output(False, prefix=p... | python | {
"resource": ""
} |
q12792 | temp_output_dir | train | def temp_output_dir(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False):
"""
A context manager for convenience in creating a temporary directory,
which is deleted when exiting the context.
Usage:
with temp_output_dir() as dirname:
...
"""
return _temp_output(True, prefix=pr... | python | {
"resource": ""
} |
q12793 | read_string_from_file | train | def read_string_from_file(path, encoding="utf8"):
"""
Read entire contents of file into a string.
"""
with codecs.open(path, "rb", encoding=encoding) as f:
value = f.read()
return value | python | {
"resource": ""
} |
q12794 | write_string_to_file | train | def write_string_to_file(path, string, make_parents=False, backup_suffix=BACKUP_SUFFIX, encoding="utf8"):
"""
Write entire file with given string contents, atomically. Keeps backup by default.
"""
with atomic_output_file(path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:
with codecs.... | python | {
"resource": ""
} |
q12795 | set_file_mtime | train | def set_file_mtime(path, mtime, atime=None):
"""Set access and modification times on a file."""
if not atime:
atime = mtime
f = open(path, 'a')
try:
os.utime(path, (atime, mtime))
finally:
f.close() | python | {
"resource": ""
} |
q12796 | copyfile_atomic | train | def copyfile_atomic(source_path, dest_path, make_parents=False, backup_suffix=None):
"""
Copy file on local filesystem in an atomic way, so partial copies never exist. Preserves timestamps.
"""
with atomic_output_file(dest_path, make_parents=make_parents, backup_suffix=backup_suffix) as tmp_path:
shutil.cop... | python | {
"resource": ""
} |
q12797 | copytree_atomic | train | def copytree_atomic(source_path, dest_path, make_parents=False, backup_suffix=None, symlinks=False):
"""
Copy a file or directory recursively, and atomically, reanaming file or top-level dir when done.
Unlike shutil.copytree, this will not fail on a file.
"""
if os.path.isdir(source_path):
with atomic_out... | python | {
"resource": ""
} |
q12798 | movefile | train | def movefile(source_path, dest_path, make_parents=False, backup_suffix=None):
"""
Move file. With a few extra options.
"""
if make_parents:
make_parent_dirs(dest_path)
move_to_backup(dest_path, backup_suffix=backup_suffix)
shutil.move(source_path, dest_path) | python | {
"resource": ""
} |
q12799 | rmtree_or_file | train | def rmtree_or_file(path, ignore_errors=False, onerror=None):
"""
rmtree fails on files or symlinks. This removes the target, whatever it is.
"""
# TODO: Could add an rsync-based delete, as in
# https://github.com/vivlabs/instaclone/blob/master/instaclone/instaclone.py#L127-L143
if ignore_errors and not os.p... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.