query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
output to html file
|
python
|
def write_to_output(content, output=None,
encoding=anytemplate.compat.ENCODING):
"""
:param content: Content string to write to
:param output: Output destination
:param encoding: Character set encoding of outputs
"""
if anytemplate.compat.IS_PYTHON_3 and isinstance(content, bytes):
content = str(content, encoding)
if output and not output == '-':
_write_to_filepath(content, output)
elif anytemplate.compat.IS_PYTHON_3:
print(content)
else:
print(content.encode(encoding.lower()), file=get_output_stream())
|
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/utils.py#L208-L223
|
output to html file
|
python
|
def output_file(self, filename, title="Bokeh Plot", mode="cdn", root_dir=None):
''' Configure output to a standalone HTML file.
Calling ``output_file`` not clear the effects of any other calls to
``output_notebook``, etc. It adds an additional output destination
(publishing to HTML files). Any other active output modes continue
to be active.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`~bokeh.resources.Resources`
for more details.
root_dir (str, optional) : root dir to use for absolute resources
(default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or ``CDN``.
.. warning::
The specified output file will be overwritten on every save, e.g.,
every time ``show()`` or ``save()`` is called.
'''
self._file = {
'filename' : filename,
'resources' : Resources(mode=mode, root_dir=root_dir),
'title' : title
}
if os.path.isfile(filename):
log.info("Session output file '%s' already exists, will be overwritten." % filename)
|
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/state.py#L135-L171
|
output to html file
|
python
|
def _output_to_file(self):
""" Save to filepath specified on
init. (Will throw an error if
the document is already open).
"""
f = open(self.filepath, 'wb')
if not f:
raise Exception('Unable to create output file: ', self.filepath)
f.write(self.session.buffer)
f.close()
|
https://github.com/katerina7479/pypdflite/blob/ac2501f30d6619eae9dea5644717575ca9263d0a/pypdflite/pdflite.py#L294-L304
|
output to html file
|
python
|
def WriteOutput(self, output_file, feed_merger,
old_feed_path, new_feed_path, merged_feed_path):
"""Write the HTML output to a file.
Args:
output_file: The file object that the HTML output will be written to.
feed_merger: The FeedMerger instance.
old_feed_path: The path to the old feed file as a string.
new_feed_path: The path to the new feed file as a string
merged_feed_path: The path to the merged feed file as a string. This
may be None if no merged feed was written.
"""
if merged_feed_path is None:
html_merged_feed_path = ''
else:
html_merged_feed_path = '<p>Merged feed created: <code>%s</code></p>' % (
merged_feed_path)
html_header = """<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Feed Merger Results</title>
<style>
body {font-family: Georgia, serif; background-color: white}
.path {color: gray}
div.problem {max-width: 500px}
td,th {background-color: khaki; padding: 2px; font-family:monospace}
td.problem,th.problem {background-color: dc143c; color: white; padding: 2px;
font-family:monospace}
table {border-spacing: 5px 0px; margin-top: 3px}
h3.issueHeader {padding-left: 1em}
.notice {background-color: yellow}
span.pass {background-color: lightgreen}
span.fail {background-color: yellow}
.pass, .fail {font-size: 16pt; padding: 3px}
ol,.unused {padding-left: 40pt}
.header {background-color: white; font-family: Georgia, serif; padding: 0px}
th.header {text-align: right; font-weight: normal; color: gray}
.footer {font-size: 10pt}
</style>
</head>
<body>
<h1>Feed merger results</h1>
<p>Old feed: <code>%(old_feed_path)s</code></p>
<p>New feed: <code>%(new_feed_path)s</code></p>
%(html_merged_feed_path)s""" % locals()
html_stats = self._GenerateStatsTable(feed_merger)
html_summary = self._GenerateSummary()
html_notices = self._GenerateNotices()
html_errors = self._GenerateSection(transitfeed.TYPE_ERROR)
html_warnings = self._GenerateSection(transitfeed.TYPE_WARNING)
html_footer = """
<div class="footer">
Generated using transitfeed version %s on %s.
</div>
</body>
</html>""" % (transitfeed.__version__,
time.strftime('%B %d, %Y at %I:%M %p %Z'))
output_file.write(transitfeed.EncodeUnicode(html_header))
output_file.write(transitfeed.EncodeUnicode(html_stats))
output_file.write(transitfeed.EncodeUnicode(html_summary))
output_file.write(transitfeed.EncodeUnicode(html_notices))
output_file.write(transitfeed.EncodeUnicode(html_errors))
output_file.write(transitfeed.EncodeUnicode(html_warnings))
output_file.write(transitfeed.EncodeUnicode(html_footer))
|
https://github.com/google/transitfeed/blob/eb2991a3747ba541b2cb66502b305b6304a1f85f/merge.py#L283-L350
|
output to html file
|
python
|
def get_output(self):
'''
Get file content, selecting only lines we are interested in
'''
if not os.path.isfile(self.real_path):
logger.debug('File %s does not exist', self.real_path)
return
cmd = []
cmd.append('sed')
cmd.append('-rf')
cmd.append(constants.default_sed_file)
cmd.append(self.real_path)
sedcmd = Popen(cmd,
stdout=PIPE)
if self.exclude is not None:
exclude_file = NamedTemporaryFile()
exclude_file.write("\n".join(self.exclude).encode('utf-8'))
exclude_file.flush()
cmd = "grep -v -F -f %s" % exclude_file.name
args = shlex.split(cmd)
proc = Popen(args, stdin=sedcmd.stdout, stdout=PIPE)
sedcmd.stdout.close()
stdin = proc.stdout
if self.pattern is None:
output = proc.communicate()[0]
else:
sedcmd = proc
if self.pattern is not None:
pattern_file = NamedTemporaryFile()
pattern_file.write("\n".join(self.pattern).encode('utf-8'))
pattern_file.flush()
cmd = "grep -F -f %s" % pattern_file.name
args = shlex.split(cmd)
proc1 = Popen(args, stdin=sedcmd.stdout, stdout=PIPE)
sedcmd.stdout.close()
if self.exclude is not None:
stdin.close()
output = proc1.communicate()[0]
if self.pattern is None and self.exclude is None:
output = sedcmd.communicate()[0]
return output.decode('utf-8', 'ignore').strip()
|
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/insights_spec.py#L147-L196
|
output to html file
|
python
|
def get_output(self, stdin_content, stdin):
"""
Try to get output in a separate thread
"""
try:
if stdin:
if sys.version_info >= (3, 0):
self.process.stdin.write(bytes(stdin_content, "utf-8"))
else:
self.process.stdin.write(stdin_content)
self._out = self.process.communicate()[0]
except (error, IOError):
self._out = self._in
pass
|
https://github.com/mseclab/PyJFuzz/blob/f777067076f62c9ab74ffea6e90fd54402b7a1b4/pyjfuzz/core/pjf_executor.py#L75-L88
|
output to html file
|
python
|
def write_file(self, html, outfile):
"""Write an HTML string to a file.
"""
try:
with open(outfile, 'wt') as file:
file.write(html)
except (IOError, OSError) as e:
err_exit('Error writing %s: %s' % (outfile, e.strerror or e))
|
https://github.com/Jarn/jarn.viewdoc/blob/59ae82fd1658889c41096c1d8c08dcb1047dc349/jarn/viewdoc/viewdoc.py#L305-L312
|
output to html file
|
python
|
def render(file):
"""Generate the result HTML."""
fp = file.open()
content = fp.read()
fp.close()
notebook = nbformat.reads(content.decode('utf-8'), as_version=4)
html_exporter = HTMLExporter()
html_exporter.template_file = 'basic'
(body, resources) = html_exporter.from_notebook_node(notebook)
return body, resources
|
https://github.com/inveniosoftware/invenio-previewer/blob/558fd22e0f29cc8cd7a6999abd4febcf6b248c49/invenio_previewer/extensions/ipynb.py#L18-L29
|
output to html file
|
python
|
def print_output(response, output_file=None):
'''print the output to the console for the user. If the user wants the content
also printed to an output file, do that.
Parameters
==========
response: the response from the builder, with metadata added
output_file: if defined, write output also to file
'''
# If successful built, show container uri
if response['status'] == 'SUCCESS':
bucket = response['artifacts']['objects']['location']
obj = response['artifacts']['objects']['paths'][0]
bot.custom("MD5HASH", response['file_hash'], 'CYAN')
bot.custom("SIZE", response['size'], 'CYAN')
bot.custom(response['status'], bucket + obj , 'CYAN')
else:
bot.custom(response['status'], 'see logs for details', 'CYAN')
# Show the logs no matter what
bot.custom("LOGS", response['logUrl'], 'CYAN')
# Did the user make the container public?
if "public_url" in response:
bot.custom('URL', response['public_url'], 'CYAN')
# Does the user also need writing to an output file?
if output_file != None:
with open(output_file, 'w') as filey:
if response['status'] == 'SUCCESS':
filey.writelines('MD5HASH %s\n' % response['file_hash'])
filey.writelines('SIZE %s\n' % response['size'])
filey.writelines('%s %s%s\n' % (response['status'], bucket, obj))
filey.writelines('LOGS %s\n' % response['logUrl'])
if "public_url" in response:
filey.writelines('URL %s\n' % response['public_url'])
|
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/client/build.py#L94-L130
|
output to html file
|
python
|
def _redirect_output(self, value, filename=None, append=None, printfun=None):
"""Outputs the specified value to the console or a file depending on the redirect
behavior specified.
:arg value: the string text to print or save.
:arg filename: the name of the file to save the text to.
:arg append: when true, the text is appended to the file if it exists.
"""
if filename is None:
if printfun is None:
print(value)
else:
printfun(value)
else:
if append:
mode = 'a'
else:
mode = 'w'
from os import path
fullpath = path.abspath(filename)
with open(filename, mode) as f:
f.write(value + '\n')
|
https://github.com/rosenbrockc/fortpy/blob/1ed0757c52d549e41d9d44bdea68cb89529293a5/fortpy/scripts/analyze.py#L204-L226
|
output to html file
|
python
|
def get_output(self, job_id, outfn):
"""
Download an output file given the id of the output request job.
## Arguments
* `job_id` (int): The id of the _output_ job.
* `outfn` (str): The file where the output should be stored.
May also be a file-like object with a 'write' method.
"""
job_info = self.job_info(jobid=job_id)[0]
# Make sure that the job is finished.
status = int(job_info["Status"])
if status != 5:
raise Exception("The status of job %d is %d (%s)"
%(job_id, status, self.status_codes[status]))
# Try to download the output file.
remotefn = job_info["OutputLoc"]
r = requests.get(remotefn)
# Make sure that the request went through.
code = r.status_code
if code != 200:
raise Exception("Getting file %s yielded status: %d"
%(remotefn, code))
# Save the data to a file.
try:
outfn.write(r.content)
except AttributeError:
f = open(outfn, "wb")
f.write(r.content)
f.close()
|
https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L259-L294
|
output to html file
|
python
|
def html_to_file(html, file_path=None, open_browser=False):
"""Save the html to an html file adapting the paths to the filesystem.
if a file_path is passed, it is used, if not a unique_filename is
generated.
:param html: the html for the output file.
:type html: str
:param file_path: the path for the html output file.
:type file_path: str
:param open_browser: if true open the generated html in an external browser
:type open_browser: bool
"""
if file_path is None:
file_path = unique_filename(suffix='.html')
# Ensure html is in unicode for codecs module
html = html
with codecs.open(file_path, 'w', encoding='utf-8') as f:
f.write(html)
if open_browser:
open_in_browser(file_path)
|
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/utilities/utilities.py#L226-L250
|
output to html file
|
python
|
def generate_output_file(path):
"""
Generate a function to send the content to the file specified in 'path'
:param path:
:return:
"""
def write_file(content):
"""
Function to do write_file operation
:param content:
:return:
"""
with open(path, 'w+') as output:
output.write(content)
return write_file
|
https://github.com/drewsonne/aws-autodiscovery-templater/blob/9ef2edd6a373aeb5d343b841550c210966efe079/awsautodiscoverytemplater/command.py#L92-L108
|
output to html file
|
python
|
def from_file(filename,
output_path,
options=None,
toc=None,
cover=None,
css=None,
config=None,
cover_first=None):
"""
Convert HTML file/files to IMG file/files
:param filename: path of HTML file or list with paths or file-like object
:param output_path: path to output PDF file/files. False means file will be returned as string
:param options: (optional) dict with wkhtmltopdf global and page options, with or w/o '--'
:param toc: (optional) dict with toc-specific wkhtmltopdf options, with or w/o '--'
:param cover: (optional) string with url/filename with a cover html page
:param css: style of input
:param config: (optional) instance of imgkit.config.Config()
:param cover_first: (optional) if True, cover always precedes TOC
:return: True when success
"""
rtn = IMGKit(filename,
'file',
options=options,
toc=toc,
cover=cover,
css=css,
config=config,
cover_first=cover_first)
return rtn.to_img(output_path)
|
https://github.com/jarrekk/imgkit/blob/763296cc2e81b16b9c3ebd2cd4355ddd02d5ab16/imgkit/api.py#L35-L64
|
output to html file
|
python
|
def write_output(self, data, args=None, filename=None, label=None):
"""Write log data to a log file"""
if args:
if not args.outlog:
return 0
if not filename: filename=args.outlog
lastpath = ''
with open(str(filename), 'w') as output_file:
for entry in data['entries']:
if args.label:
if entry['source_path'] == lastpath:
output_file.write(entry['raw_text'] + '\n')
elif args.label == 'fname':
output_file.write('======== ' + \
entry['source_path'].split('/')[-1] + \
' >>>>\n' + entry['raw_text'] + '\n')
elif args.label == 'fpath':
output_file.write('======== ' + \
entry['source_path'] + \
' >>>>\n' + entry['raw_text'] + '\n')
else: output_file.write(entry['raw_text'] + '\n')
lastpath = entry['source_path']
|
https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/output/log.py#L37-L58
|
output to html file
|
python
|
def end_output (self, **kwargs):
"""Write end of checking info as HTML."""
if self.has_part("stats"):
self.write_stats()
if self.has_part("outro"):
self.write_outro()
self.close_fileoutput()
|
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/html.py#L331-L337
|
output to html file
|
python
|
def output_file(self):
"""
If only one output file return it. Otherwise raise an exception.
"""
out_files = self.output_files
if len(out_files) != 1:
err_msg = "output_file property is only valid if there is a single"
err_msg += " output file. Here there are "
err_msg += "%d output files." %(len(out_files))
raise ValueError(err_msg)
return out_files[0]
|
https://github.com/gwastro/pycbc/blob/7a64cdd104d263f1b6ea0b01e6841837d05a4cb3/pycbc/workflow/core.py#L976-L986
|
output to html file
|
python
|
def _output(self, file_like_object, path=None):
"""Display or save file like object."""
if not path:
self._output_to_display(file_like_object)
else:
self._output_to_file(file_like_object, path)
|
https://github.com/DataONEorg/d1_python/blob/3ac4d4f3ca052d3e8641a6a329cab526c8ddcb0d/client_cli/src/d1_cli/impl/command_processor.py#L242-L247
|
output to html file
|
python
|
def __save_output(self):
"""Saves the output into a native OOo document format.
"""
out = zipfile.ZipFile(self.outputfilename, 'w')
for info_zip in self.infile.infolist():
if info_zip.filename in self.templated_files:
# Template file - we have edited these.
# get a temp file
streamout = open(get_secure_filename(), "w+b")
fname, output_stream = self.output_streams[
self.templated_files.index(info_zip.filename)
]
transformer = get_list_transformer(self.namespaces)
remapped_stream = output_stream | transformer
# write the whole stream to it
for chunk in remapped_stream.serialize():
streamout.write(chunk.encode('utf-8'))
yield True
# close the temp file to flush all data and make sure we get
# it back when writing to the zip archive.
streamout.close()
# write the full file to archive
out.write(streamout.name, fname)
# remove temp file
os.unlink(streamout.name)
else:
# Copy other files straight from the source archive.
out.writestr(info_zip, self.infile.read(info_zip.filename))
# Save images in the "Pictures" sub-directory of the archive.
for identifier, data in self.images.items():
out.writestr(PY3O_IMAGE_PREFIX + identifier, data)
# close the zipfile before leaving
out.close()
yield True
|
https://github.com/faide/py3o.template/blob/1ae8435ab8ba9f469a3e8d1156e7f24271c77c0e/py3o/template/main.py#L735-L779
|
output to html file
|
python
|
def render_compressed_output(self, package, package_name, package_type):
"""Render HTML for using the package's output file.
Subclasses can override this method to provide custom behavior for
rendering the output file.
"""
method = getattr(self, 'render_{0}'.format(package_type))
return method(package, package.output_filename)
|
https://github.com/jazzband/django-pipeline/blob/3cd2f93bb47bf8d34447e13ff691f7027e7b07a2/pipeline/templatetags/pipeline.py#L74-L82
|
output to html file
|
python
|
def output(self):
"""Output the generated source file."""
print(copyright_header % spec_version)
self._output_imports()
self._output_tags()
self._output_validators()
header = self.override.get_header()
if header:
print()
print()
print(header.rstrip())
seen = {}
for class_name, properties in sorted(self.resources.items()):
resource_name = self.resource_names[class_name]
t = self.build_tree(class_name, properties, resource_name)
self.output_tree(t, seen)
|
https://github.com/cloudtools/troposphere/blob/f7ea5591a7c287a843adc9c184d2f56064cfc632/scripts/gen.py#L278-L294
|
output to html file
|
python
|
def output_to_file(filename, tracklisting, action):
"""
Produce requested output; either output text file, tag audio file or do
both.
filename: a string of path + filename without file extension
tracklisting: a string containing a tracklisting
action: 'tag', 'text' or 'both', from command line arguments
"""
if action in ('tag', 'both'):
audio_tagged = tag_audio(filename, tracklisting)
if action == 'both' and audio_tagged:
write_text(filename, tracklisting)
elif action == 'text':
write_text(filename, tracklisting)
|
https://github.com/StevenMaude/bbc-radio-tracklisting-downloader/blob/9fe9096b4d889888f65756444e4fd71352b92458/bbc_tracklist.py#L196-L210
|
output to html file
|
python
|
def write_output(output, text=True, output_path=None):
"""Write binary or text output to a file or stdout."""
if output_path is None and text is False:
print("ERROR: You must specify an output file using -o/--output for binary output formats")
sys.exit(1)
if output_path is not None:
if text:
outfile = open(output_path, "w", encoding="utf-8")
else:
outfile = open(output_path, "wb")
else:
outfile = sys.stdout
try:
if text and isinstance(output, bytes):
output = output.decode('utf-8')
outfile.write(output)
finally:
if outfile is not sys.stdout:
outfile.close()
|
https://github.com/iotile/coretools/blob/2d794f5f1346b841b0dcd16c9d284e9bf2f3c6ec/iotilesensorgraph/iotile/sg/scripts/iotile_sgcompile.py#L23-L45
|
output to html file
|
python
|
def _write_to_filepath(content, output):
"""
:param content: Content string to write to
:param output: Output file path
"""
outdir = os.path.dirname(output)
if outdir and not os.path.exists(outdir):
os.makedirs(outdir)
with anytemplate.compat.copen(output, 'w') as out:
out.write(content)
|
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/utils.py#L195-L205
|
output to html file
|
python
|
def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
if formatted:
to.write(self.start_tag)
to.write('\n')
if not self.tag_self_closes:
for blok in self.blox:
to.write(indentation * (indent + 1))
blok.output(to=to, indent=indent + 1, formatted=True, indentation=indentation, *args, **kwargs)
to.write('\n')
to.write(indentation * indent)
to.write(self.end_tag)
if not indentation:
to.write('\n')
else:
to.write(self.start_tag)
if not self.tag_self_closes:
for blok in self.blox:
blok.output(to=to, *args, **kwargs)
to.write(self.end_tag)
|
https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/base.py#L450-L470
|
output to html file
|
python
|
def write_output(self):
"""Write all stored output data to storage."""
for data in self.output_data.values():
self.create_output(data.get('key'), data.get('value'), data.get('type'))
|
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_playbook.py#L583-L586
|
output to html file
|
python
|
def output(self, name='',dest=''):
"Output PDF to some destination"
#Finish document if necessary
if(self.state<3):
self.close()
dest=dest.upper()
if(dest==''):
if(name==''):
name='doc.pdf'
dest='I'
else:
dest='F'
if dest=='I':
print(self.buffer)
elif dest=='D':
print(self.buffer)
elif dest=='F':
#Save to local file
f=open(name,'wb')
if(not f):
self.error('Unable to create output file: '+name)
if PY3K:
# manage binary data as latin1 until PEP461 or similar is implemented
f.write(self.buffer.encode("latin1"))
else:
f.write(self.buffer)
f.close()
elif dest=='S':
#Return as a string
return self.buffer
else:
self.error('Incorrect output destination: '+dest)
return ''
|
https://github.com/m32/endesive/blob/973091dc69847fe2df594c80ac9235a8d08460ff/endesive/pdf/fpdf/fpdf.py#L1061-L1093
|
output to html file
|
python
|
def write_output(self, data, filename=None, args=None):
"""Write log data to a file with one JSON object per line"""
if args:
if not args.linejson:
return 0
if not filename: filename = args.linejson
entrylist = []
for entry in data['entries']:
entrystring = json.dumps(entry, sort_keys=True)
entrylist.append(entrystring)
with open(str(filename), 'w') as output_file:
output_file.write('\n'.join(entrylist))
|
https://github.com/dogoncouch/logdissect/blob/426b50264cbfa9665c86df3781e1e415ba8dbbd3/logdissect/output/linejson.py#L36-L48
|
output to html file
|
python
|
def get_output(command):
"""Returns the output of a command returning a single line of output."""
p = Popen(command, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
p.stdin.close()
p.stderr.close()
line=p.stdout.readline().strip()
p.wait()
if type(line).__name__ == "bytes":
line = str(line, encoding="utf-8")
return line, p.returncode
|
https://github.com/vtraag/leidenalg/blob/a9e15116973a81048edf02ef7cf800d54debe1cc/setup.py#L106-L115
|
output to html file
|
python
|
def bytes_to_file(input_data, output_file):
"""Save bytes to a file."""
pathlib.Path(output_file.parent).mkdir(parents=True, exist_ok=True)
with open(output_file, "wb") as file:
file.write(input_data)
|
https://github.com/dylanaraps/bum/blob/004d795a67398e79f2c098d7775e9cd97231646b/bum/util.py#L7-L12
|
output to html file
|
python
|
def request_and_get_output(self, table, outtype, outfn):
"""
Shorthand for requesting an output file and then downloading it when
ready.
## Arguments
* `table` (str): The name of the table to export.
* `outtype` (str): The type of output. Must be one of:
CSV - Comma Seperated Values
DataSet - XML DataSet
FITS - Flexible Image Transfer System (FITS Binary)
VOTable - XML Virtual Observatory VOTABLE
* `outfn` (str): The file where the output should be stored.
May also be a file-like object with a 'write' method.
"""
job_id = self.request_output(table, outtype)
status = self.monitor(job_id)
if status[0] != 5:
raise Exception("Output request failed.")
self.get_output(job_id, outfn)
|
https://github.com/dfm/casjobs/blob/1cc3f5511cc254d776082909221787e3c037ac16/casjobs.py#L296-L317
|
output to html file
|
python
|
def get_output(cmd, args):
"""Runs a command and returns its output (stdout + stderr).
:param str|unicode cmd:
:param str|unicode|list[str|unicode] args:
:rtype: str|unicode
"""
from subprocess import Popen, STDOUT, PIPE
command = [cmd]
command.extend(listify(args))
process = Popen(command, stdout=PIPE, stderr=STDOUT)
out, _ = process.communicate()
return out.decode('utf-8')
|
https://github.com/idlesign/uwsgiconf/blob/475407acb44199edbf7e0a66261bfeb51de1afae/uwsgiconf/utils.py#L237-L254
|
output to html file
|
python
|
def output(self, to=None, *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
for blok in self:
blok.output(to, *args, **kwargs)
return self
|
https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/base.py#L58-L62
|
output to html file
|
python
|
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
|
https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L561-L584
|
output to html file
|
python
|
def output(self):
"""
Output the results to either STDOUT or
:return:
"""
if not self.path_output:
self.output_to_fd(sys.stdout)
else:
with open(self.path_output, "w") as out:
self.output_to_fd(out)
|
https://github.com/Paradoxis/PIP-Module-Scanner/blob/168c62050b8217df0167b7d59405dcb1421cf50d/pip_module_scanner/scanner.py#L50-L59
|
output to html file
|
python
|
def get_output(self, output_files, clear=True):
"Get the output files as an id indexed dict."
patt = re.compile(r'(.*?)-semantics.*?')
for outpath in output_files:
if outpath is None:
logger.warning("Found outpath with value None. Skipping.")
continue
re_out = patt.match(path.basename(outpath))
if re_out is None:
raise SparserError("Could not get prefix from output path %s."
% outpath)
prefix = re_out.groups()[0]
if prefix.startswith('PMC'):
prefix = prefix[3:]
if prefix.isdecimal():
# In this case we assume the prefix is a tcid.
prefix = int(prefix)
try:
with open(outpath, 'rt') as f:
content = json.load(f)
except Exception as e:
logger.exception(e)
logger.error("Could not load reading content from %s."
% outpath)
content = None
self.add_result(prefix, content)
if clear:
input_path = outpath.replace('-semantics.json', '.nxml')
try:
remove(outpath)
remove(input_path)
except Exception as e:
logger.exception(e)
logger.error("Could not remove sparser files %s and %s."
% (outpath, input_path))
return self.results
|
https://github.com/sorgerlab/indra/blob/79a70415832c5702d7a820c7c9ccc8e25010124b/indra/tools/reading/readers.py#L600-L639
|
output to html file
|
python
|
def output_file(filename, title="Bokeh Plot", mode="cdn", root_dir=None):
'''Configure the default output state to generate output saved
to a file when :func:`show` is called.
Does not change the current ``Document`` from ``curdoc()``. File and notebook
output may be active at the same time, so e.g., this does not clear the
effects of ``output_notebook()``.
Args:
filename (str) : a filename for saving the HTML document
title (str, optional) : a title for the HTML document (default: "Bokeh Plot")
mode (str, optional) : how to include BokehJS (default: ``'cdn'``)
One of: ``'inline'``, ``'cdn'``, ``'relative(-dev)'`` or
``'absolute(-dev)'``. See :class:`bokeh.resources.Resources` for more details.
root_dir (str, optional) : root directory to use for 'absolute' resources. (default: None)
This value is ignored for other resource types, e.g. ``INLINE`` or
``CDN``.
Returns:
None
.. note::
Generally, this should be called at the beginning of an interactive
session or the top of a script.
.. warning::
This output file will be overwritten on every save, e.g., each time
show() or save() is invoked.
'''
curstate().output_file(
filename,
title=title,
mode=mode,
root_dir=root_dir
)
|
https://github.com/bokeh/bokeh/blob/dc8cf49e4e4302fd38537ad089ece81fbcca4737/bokeh/io/output.py#L45-L83
|
output to html file
|
python
|
def collect_output(self):
""" helper function to gather the results of `compile_and_process` on
all target files
"""
if self.embed:
if self.concat:
concat_scripts = [self.compiled_scripts[path]
for path in self.build_order]
return [self.embed_template_string % '\n'.join(concat_scripts)]
else:
return [self.embed_template_string %
self.compiled_scripts[path]
for path in self.build_order]
else:
return [self.external_template_string %
os.path.join(
self.relative_directory,
os.path.relpath(
self.out_path_of(path),
self.output_directory))
for path in self.build_order
if self.compiled_scripts[path] != ""]
|
https://github.com/Archived-Object/ligament/blob/ff3d78130522676a20dc64086dc8a27b197cc20f/ligament_precompiler_template/__init__.py#L116-L139
|
output to html file
|
python
|
def export(path=None, user_content=False, context=None,
username=None, password=None, render_offline=False,
render_wide=False, render_inline=True, out_filename=None,
api_url=None, title=None, quiet=False, grip_class=None):
"""
Exports the rendered HTML to a file.
"""
export_to_stdout = out_filename == '-'
if out_filename is None:
if path == '-':
export_to_stdout = True
else:
filetitle, _ = os.path.splitext(
os.path.relpath(DirectoryReader(path).root_filename))
out_filename = '{0}.html'.format(filetitle)
if not export_to_stdout and not quiet:
print('Exporting to', out_filename, file=sys.stderr)
page = render_page(path, user_content, context, username, password,
render_offline, render_wide, render_inline, api_url,
title, None, quiet, grip_class)
if export_to_stdout:
try:
print(page)
except IOError as ex:
if ex.errno != 0 and ex.errno != errno.EPIPE:
raise
else:
with io.open(out_filename, 'w', encoding='utf-8') as f:
f.write(page)
|
https://github.com/joeyespo/grip/blob/ce933ccc4ca8e0d3718f271c59bd530a4518bf63/grip/api.py#L97-L128
|
output to html file
|
python
|
def get_output(script, expanded):
"""Runs the script and obtains stdin/stderr.
:type script: str
:type expanded: str
:rtype: str | None
"""
env = dict(os.environ)
env.update(settings.env)
is_slow = shlex.split(expanded) in settings.slow_commands
with logs.debug_time(u'Call: {}; with env: {}; is slow: '.format(
script, env, is_slow)):
result = Popen(expanded, shell=True, stdin=PIPE,
stdout=PIPE, stderr=STDOUT, env=env)
if _wait_output(result, is_slow):
output = result.stdout.read().decode('utf-8')
logs.debug(u'Received output: {}'.format(output))
return output
else:
logs.debug(u'Execution timed out!')
return None
|
https://github.com/nvbn/thefuck/blob/40ab4eb62db57627bff10cf029d29c94704086a2/thefuck/output_readers/rerun.py#L45-L67
|
output to html file
|
python
|
def Output(self):
"""Output all sections of the page."""
self.Open()
self.Header()
self.Body()
self.Footer()
|
https://github.com/google/python-gflags/blob/4f06c3d0d6cbe9b1fb90ee9fb1c082b3bf9285f6/gflags2man.py#L446-L451
|
output to html file
|
python
|
def render(self, file_path, **kwargs):
""" Save the content of the .text file in the PDF.
Parameters
----------
file_path: str
Path to the output file.
"""
temp = get_tempfile(suffix='.tex')
self.save_content(temp.name)
try:
self._render_function(temp.name, file_path, output_format='pdf')
except:
log.exception('Error exporting file {} to PDF.'.format(file_path))
raise
|
https://github.com/PythonSanSebastian/docstamp/blob/b43808f2e15351b0b2f0b7eade9c7ef319c9e646/docstamp/template.py#L272-L287
|
output to html file
|
python
|
def get_output(src):
"""
parse lines looking for commands
"""
output = ''
lines = open(src.path, 'rU').readlines()
for line in lines:
m = re.match(config.import_regex,line)
if m:
include_path = os.path.abspath(src.dir + '/' + m.group('script'));
if include_path not in config.sources:
script = Script(include_path)
script.parents.append(src)
config.sources[script.path] = script
include_file = config.sources[include_path]
#require statements dont include if the file has already been included
if include_file not in config.stack or m.group('command') == 'import':
config.stack.append(include_file)
output += get_output(include_file)
else:
output += line
return output
|
https://github.com/coded-by-hand/mass/blob/59005479efed3cd8598a8f0c66791a4482071899/mass/parse.py#L28-L49
|
output to html file
|
python
|
def generate_output(self, writer=None):
'''
Generate redirect files
'''
logger.info(
'Generating permalink files in %r', self.permalink_output_path)
clean_output_dir(self.permalink_output_path, [])
mkdir_p(self.permalink_output_path)
for content in itertools.chain(
self.context['articles'], self.context['pages']):
for permalink_id in content.get_permalink_ids_iter():
permalink_path = os.path.join(
self.permalink_output_path, permalink_id) + '.html'
redirect_string = REDIRECT_STRING.format(
url=article_url(content),
title=content.title)
open(permalink_path, 'w').write(redirect_string)
|
https://github.com/getpelican/pelican-plugins/blob/cfc7a3f224f1743063b034561f89a6a712d13587/permalinks/permalinks.py#L60-L79
|
output to html file
|
python
|
def get_output_from_pipe(self, input_file):
"""Executes an external command and get its output. The command
receives its input_file from the stdin through a pipe
:param input_file: input file
:return: output of command
"""
args = shlex.split(self.cmd)
p = Popen(args, stdout=PIPE, stdin=PIPE) # | grep es
p.stdin.write(bytearray(input_file.encode("utf8"))) # echo test |
return p.communicate()[0].decode("utf8")
|
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/system/process.py#L42-L52
|
output to html file
|
python
|
def to_output(self, value):
"""Convert value to process output format."""
return json.loads(resolwe_runtime_utils.save_file(self.name, value.path, *value.refs))
|
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/process/fields.py#L340-L342
|
output to html file
|
python
|
def get_output(self):
"""
Override standard get_output to return xml-file if xml-file is specified.
Otherwise, will return database.
"""
if self.__xml_output:
return self.__xml_output
elif self.get_database():
return self.get_database()
else:
raise ValueError, "no output xml file or database specified"
|
https://github.com/gwastro/pycbc-glue/blob/a3e906bae59fbfd707c3ff82e5d008d939ec5e24/pycbc_glue/pipeline.py#L4326-L4336
|
output to html file
|
python
|
def render_to(filepath, context=None, output=None,
at_encoding=anytemplate.compat.ENCODING, **options):
"""
Render given template file and write the result string to given `output`.
The result string will be printed to sys.stdout if output is None or '-'.
:param filepath: Template file path
:param context: A dict or dict-like object to instantiate given
template file
:param output: File path to write the rendered result string to or None/'-'
to print it to stdout
:param at_encoding: Template encoding
:param options: Optional keyword arguments such as:
- at_paths: Template search paths
- at_engine: Specify the name of template engine to use explicitly or
None to find it automatically anyhow.
- at_cls_args: Arguments passed to instantiate template engine class
- other keyword arguments passed to the template engine to render
templates with specific features enabled.
"""
res = render(filepath, context=context, **options)
anytemplate.utils.write_to_output(res, output, at_encoding)
|
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/api.py#L158-L180
|
output to html file
|
python
|
def output(self, to=None, formatted=False, indent=0, indentation=' ', *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
if formatted and self.blox:
self.blox[0].output(to=to, formatted=True, indent=indent, indentation=indentation, *args, **kwargs)
for blok in self.blox[1:]:
to.write('\n')
to.write(indent * indentation)
blok.output(to=to, formatted=True, indent=indent, indentation=indentation, *args, **kwargs)
if not indent:
to.write('\n')
else:
for blok in self.blox:
blok.output(to=to, *args, **kwargs)
return self
|
https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/base.py#L313-L327
|
output to html file
|
python
|
def to_file(output_file, encoder=EliotJSONEncoder):
"""
Add a destination that writes a JSON message per line to the given file.
@param output_file: A file-like object.
"""
Logger._destinations.add(
FileDestination(file=output_file, encoder=encoder)
)
|
https://github.com/itamarst/eliot/blob/c03c96520c5492fadfc438b4b0f6336e2785ba2d/eliot/_output.py#L472-L480
|
output to html file
|
python
|
def to_file(self, output_filename):
'''Handles pdf and epub format.
Inpute: output_filename should have the proper extension.
Output: The name of the file created, or an IOError if failed'''
temp_file = NamedTemporaryFile(mode="w", suffix=".md", delete=False)
temp_file.write(self._content)
temp_file.close()
subprocess_arguments = [PANDOC_PATH, temp_file.name, '-o %s' % output_filename]
subprocess_arguments.extend(self.arguments)
cmd = " ".join(subprocess_arguments)
fin = os.popen(cmd)
msg = fin.read()
fin.close()
if msg:
print("Pandoc message: {}",format(msg))
os.remove(temp_file.name)
if exists(output_filename):
return output_filename
else:
raise IOError("Failed creating file: %s" % output_filename)
|
https://github.com/kenneth-reitz/pyandoc/blob/4417ee34e85c88c874f0a5ae93bc54b0f5d93af0/pandoc/core.py#L100-L123
|
output to html file
|
python
|
def output(self):
""" Generates output from data array
:returns Pythoned file
:rtype str or unicode
"""
if len(self.files) < 1:
raise Exception('Converter#output: No files to convert')
return self.template.render(self.files)
|
https://github.com/kwarunek/file2py/blob/f94730b6d4f40ea22b5f048126f60fa14c0e2bf0/file2py/conv.py#L82-L90
|
output to html file
|
python
|
def write_output_file(self,
path: str,
per_identity_data: 'RDD',
spark_session: Optional['SparkSession'] = None) -> None:
"""
Basic helper function to persist data to disk.
If window BTS was provided then the window BTS output to written in csv format, otherwise,
the streaming BTS output is written in JSON format to the `path` provided
:param path: Path where the output should be written.
:param per_identity_data: Output of the `execute()` call.
:param spark_session: `SparkSession` to use for execution. If None is provided then a basic
`SparkSession` is created.
:return:
"""
_spark_session_ = get_spark_session(spark_session)
if not self._window_bts:
per_identity_data.flatMap(
lambda x: [json.dumps(data, cls=BlurrJSONEncoder) for data in x[1][0].items()]
).saveAsTextFile(path)
else:
# Convert to a DataFrame first so that the data can be saved as a CSV
_spark_session_.createDataFrame(per_identity_data.flatMap(lambda x: x[1][1])).write.csv(
path, header=True)
|
https://github.com/productml/blurr/blob/1b688b2c4a9bbbb2139c58bf0682ddc05a6c24fa/blurr/runner/spark_runner.py#L134-L158
|
output to html file
|
python
|
def write_output(job_id, content, conn=None):
"""writes output to the output table
:param job_id: <str> id of the job
:param content: <str> output to write
:param conn:
"""
output_job = get_job_by_id(job_id, conn)
results = {}
if output_job is not None:
entry = {
OUTPUTJOB_FIELD: output_job,
CONTENT_FIELD: content
}
results = RBO.insert(entry, conflict=RDB_REPLACE).run(conn)
return results
|
https://github.com/ramrod-project/database-brain/blob/b024cb44f34cabb9d80af38271ddb65c25767083/schema/brain/queries/writes.py#L122-L137
|
output to html file
|
python
|
def produce_csv_output(filehandle: TextIO,
fields: Sequence[str],
values: Iterable[str]) -> None:
"""
Produce CSV output, without using ``csv.writer``, so the log can be used
for lots of things.
- ... eh? What was I talking about?
- POOR; DEPRECATED.
Args:
filehandle: file to write to
fields: field names
values: values
"""
output_csv(filehandle, fields)
for row in values:
output_csv(filehandle, row)
|
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/rnc_text.py#L39-L56
|
output to html file
|
python
|
def get_output_from_input(self):
"""Populate output form with default output path based on input layer.
"""
input_path = self.layer.currentLayer().source()
output_path = (
os.path.splitext(input_path)[0] + '_multi_buffer'
+ os.path.splitext(input_path)[1])
self.output_form.setText(output_path)
|
https://github.com/inasafe/inasafe/blob/831d60abba919f6d481dc94a8d988cc205130724/safe/gui/tools/multi_buffer_dialog.py#L178-L185
|
output to html file
|
python
|
def write_file(self, target_path, html):
"""
Writes out the provided HTML to the provided path.
"""
logger.debug("Building to {}{}".format(self.fs_name, target_path))
with self.fs.open(smart_text(target_path), 'wb') as outfile:
outfile.write(six.binary_type(html))
outfile.close()
|
https://github.com/datadesk/django-bakery/blob/e2feb13a66552a388fbcfaaacdd504bba08d3c69/bakery/views/base.py#L72-L79
|
output to html file
|
python
|
def htmlDocContentDumpOutput(self, buf, encoding):
"""Dump an HTML document. Formating return/spaces are added. """
if buf is None: buf__o = None
else: buf__o = buf._o
libxml2mod.htmlDocContentDumpOutput(buf__o, self._o, encoding)
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3997-L4001
|
output to html file
|
python
|
def htmlDocContentDumpOutput(self, cur, encoding):
"""Dump an HTML document. Formating return/spaces are added. """
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.htmlDocContentDumpOutput(self._o, cur__o, encoding)
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L6041-L6045
|
output to html file
|
python
|
def output(f):
""" This decorator allows to choose to return an output as text or to save
it to a file. """
def wrapper(self, *args, **kwargs):
try:
text = kwargs.get('text') or args[0]
except IndexError:
text = True
_ = f(self, *args, **kwargs)
if text:
return _
elif _ is not None and isinstance(_, string_types):
filename = "{}.{}".format(self.filename, f.__name__)
while exists(filename):
name, ext = splitext(filename)
try:
name, i = name.split('-')
i = int(i) + 1
except ValueError:
i = 2
filename = "{}-{}".format(name, i) + ext
with open(filename, 'w') as out:
out.write(_)
return wrapper
|
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L32-L55
|
output to html file
|
python
|
def write_output(self, data, file_name, key=None):
"""Writes output data to disk.
Parameters
----------
data: pandas.DataFrame or dict
The data to write to disk.
file_name: str
The name of the file to write.
key: str, optional
The lookup key for the sub_directory to write results to, if any.
"""
path = os.path.join(self._directories[key], file_name)
extension = file_name.split('.')[-1]
if extension == 'yaml':
with open(path, 'w') as f:
yaml.dump(data, f)
elif extension == 'hdf':
# to_hdf breaks with categorical dtypes.
categorical_columns = data.dtypes[data.dtypes == 'category'].index
data.loc[:, categorical_columns] = data.loc[:, categorical_columns].astype('object')
# Writing to an hdf over and over balloons the file size so write to new file and move it over to avoid
data.to_hdf(path + "update", 'data')
if os.path.exists(path):
os.remove(path)
os.rename(path + "update", path)
else:
raise NotImplementedError(
f"Only 'yaml' and 'hdf' file types are supported. You requested {extension}")
|
https://github.com/ihmeuw/vivarium/blob/c5f5d50f775c8bf337d3aae1ff7c57c025a8e258/src/vivarium/framework/results_writer.py#L50-L79
|
output to html file
|
python
|
def write_to(output, txt):
"""Write some text to some output"""
if (isinstance(txt, six.binary_type) or six.PY3 and isinstance(output, StringIO)) or isinstance(output, TextIOWrapper):
output.write(txt)
else:
output.write(txt.encode("utf-8", "replace"))
|
https://github.com/delfick/harpoon/blob/a2d39311d6127b7da2e15f40468bf320d598e461/harpoon/helpers.py#L66-L71
|
output to html file
|
python
|
def show_output(self, txt, device='Console'):
"""
Output the data to the current device (usually
screen via print statements but can be file or
network / API
"""
if device == 'Console':
print(txt)
elif device == 'File':
raise ('show_output to File not implemented')
elif device == 'Function_Return': # hacky, to run test_AI_CLI.py
return txt
|
https://github.com/acutesoftware/AIKIF/blob/fcf1582dc5f884b9a4fa7c6e20e9de9d94d21d03/scripts/AI_CLI.py#L49-L60
|
output to html file
|
python
|
def html_output_graph(self, node):
"""
Output the graph for HTML. This will insert a PNG with clickable
image map.
"""
graph = node['graph']
parts = node['parts']
graph_hash = get_graph_hash(node)
name = "inheritance%s" % graph_hash
path = '_images'
dest_path = os.path.join(setup.app.builder.outdir, path)
if not os.path.exists(dest_path):
os.makedirs(dest_path)
png_path = os.path.join(dest_path, name + ".png")
path = setup.app.builder.imgpath
# Create a mapping from fully-qualified class names to URLs.
urls = {}
for child in node:
if child.get('refuri') is not None:
urls[child['reftitle']] = child.get('refuri')
elif child.get('refid') is not None:
urls[child['reftitle']] = '#' + child.get('refid')
# These arguments to dot will save a PNG file to disk and write
# an HTML image map to stdout.
image_map = graph.run_dot(['-Tpng', '-o%s' % png_path, '-Tcmapx'],
name, parts, urls)
return ('<img src="%s/%s.png" usemap="#%s" class="inheritance"/>%s' %
(path, name, name, image_map))
|
https://github.com/matthias-k/cyipopt/blob/ed03f54de2e0b8c8ba4c0aa18ab9ab6c8846bc19/doc/source/sphinxext/inheritance_diagram.py#L325-L355
|
output to html file
|
python
|
def get_output(self, style=OutputStyle.file):
"""Returns the result of all previous calls to execute_code."""
return self.manager.get_output(style=style)
|
https://github.com/nerdvegas/rez/blob/1d3b846d53b5b5404edfe8ddb9083f9ceec8c5e7/src/rez/rex.py#L1247-L1249
|
output to html file
|
python
|
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
"""Extend BaseForm's helper function for outputting HTML. Used by as_table(), as_ul(), as_p().
Combines the HTML version of the main form's fields with the HTML content
for any subforms.
"""
parts = []
parts.append(super(XmlObjectForm, self)._html_output(normal_row, error_row, row_ender,
help_text_html, errors_on_separate_row))
def _subform_output(subform):
return subform._html_output(normal_row, error_row, row_ender,
help_text_html, errors_on_separate_row)
for name, subform in six.iteritems(self.subforms):
# use form label if one was set
if hasattr(subform, 'form_label'):
name = subform.form_label
parts.append(self._html_subform_output(subform, name, _subform_output))
for name, formset in six.iteritems(self.formsets):
parts.append(u(formset.management_form))
# use form label if one was set
# - use declared subform label if any
if hasattr(formset.forms[0], 'form_label') and \
formset.forms[0].form_label is not None:
name = formset.forms[0].form_label
# fallback to generated label from field name
elif hasattr(formset, 'form_label'):
name = formset.form_label
# collect the html output for all the forms in the formset
subform_parts = list()
for subform in formset.forms:
subform_parts.append(self._html_subform_output(subform,
gen_html=_subform_output, suppress_section=True))
# then wrap all forms in the section container, so formset label appears once
parts.append(self._html_subform_output(name=name, content=u'\n'.join(subform_parts)))
return mark_safe(u'\n'.join(parts))
|
https://github.com/emory-libraries/eulxml/blob/17d71c7d98c0cebda9932b7f13e72093805e1fe2/eulxml/forms/xmlobject.py#L652-L692
|
output to html file
|
python
|
def _output_work(self, work, root):
"""Saves the TEI XML document `root` at the path `work`."""
output_filename = os.path.join(self._output_dir, work)
tree = etree.ElementTree(root)
tree.write(output_filename, encoding='utf-8', pretty_print=True)
|
https://github.com/ajenhl/tacl/blob/b8a343248e77f1c07a5a4ac133a9ad6e0b4781c2/tacl/tei_corpus.py#L141-L145
|
output to html file
|
python
|
def htmlDocContentDumpFormatOutput(self, buf, encoding, format):
"""Dump an HTML document. """
if buf is None: buf__o = None
else: buf__o = buf._o
libxml2mod.htmlDocContentDumpFormatOutput(buf__o, self._o, encoding, format)
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L3991-L3995
|
output to html file
|
python
|
def print_input_output(opts):
"""
Prints the input and output directories to the console.
:param opts: namespace that contains printable 'input' and 'output' fields.
"""
if opts.is_dir:
print("Root input directory:\t" + opts.input)
print("Outputting to:\t\t" + opts.output + "\n")
else:
print("Input file:\t\t" + opts.input)
print("Outputting to:\t\t" + opts.output + opts.input + "\n")
|
https://github.com/samjabrahams/anchorhub/blob/5ade359b08297d4003a5f477389c01de9e634b54/anchorhub/messages.py#L7-L18
|
output to html file
|
python
|
def build_output(self, fout):
"""Squash self.out into string.
Join every line in self.out with a new line and write the
result to the output file.
"""
fout.write('\n'.join([s for s in self.out]))
|
https://github.com/mozilla/python-zeppelin/blob/76ce6b7608ef6cf7b807bd5d850a58ea6a59ef07/zeppelin/converters/markdown.py#L129-L135
|
output to html file
|
python
|
def output(self, to=None, *args, **kwargs):
'''Outputs to a stream (like a file or request)'''
to.write(self.start_tag)
if not self.tag_self_closes:
to.write(self.end_tag)
|
https://github.com/timothycrosley/blox/blob/dc410783d2a2ecad918d1e19c6ee000d20e42d35/blox/base.py#L385-L389
|
output to html file
|
python
|
def output_html_for_tuning(
self,
audio_file_path,
output_file_path,
parameters=None
):
"""
Output an HTML file for fine tuning the sync map manually.
:param string audio_file_path: the path to the associated audio file
:param string output_file_path: the path to the output file to write
:param dict parameters: additional parameters
.. versionadded:: 1.3.1
"""
if not gf.file_can_be_written(output_file_path):
self.log_exc(u"Cannot output HTML file '%s'. Wrong permissions?" % (output_file_path), None, True, OSError)
if parameters is None:
parameters = {}
audio_file_path_absolute = gf.fix_slash(os.path.abspath(audio_file_path))
template_path_absolute = gf.absolute_path(self.FINETUNEAS_PATH, __file__)
with io.open(template_path_absolute, "r", encoding="utf-8") as file_obj:
template = file_obj.read()
for repl in self.FINETUNEAS_REPLACEMENTS:
template = template.replace(repl[0], repl[1])
template = template.replace(
self.FINETUNEAS_REPLACE_AUDIOFILEPATH,
u"audioFilePath = \"file://%s\";" % audio_file_path_absolute
)
template = template.replace(
self.FINETUNEAS_REPLACE_FRAGMENTS,
u"fragments = (%s).fragments;" % self.json_string
)
if gc.PPN_TASK_OS_FILE_FORMAT in parameters:
output_format = parameters[gc.PPN_TASK_OS_FILE_FORMAT]
if output_format in self.FINETUNEAS_ALLOWED_FORMATS:
template = template.replace(
self.FINETUNEAS_REPLACE_OUTPUT_FORMAT,
u"outputFormat = \"%s\";" % output_format
)
if output_format == "smil":
for key, placeholder, replacement in [
(
gc.PPN_TASK_OS_FILE_SMIL_AUDIO_REF,
self.FINETUNEAS_REPLACE_SMIL_AUDIOREF,
"audioref = \"%s\";"
),
(
gc.PPN_TASK_OS_FILE_SMIL_PAGE_REF,
self.FINETUNEAS_REPLACE_SMIL_PAGEREF,
"pageref = \"%s\";"
),
]:
if key in parameters:
template = template.replace(
placeholder,
replacement % parameters[key]
)
with io.open(output_file_path, "w", encoding="utf-8") as file_obj:
file_obj.write(template)
|
https://github.com/readbeyond/aeneas/blob/9d95535ad63eef4a98530cfdff033b8c35315ee1/aeneas/syncmap/__init__.py#L309-L368
|
output to html file
|
python
|
def get_output(self):
"""
:yield: stdout_line, stderr_line, running
Generator that outputs lines captured from stdout and stderr
These can be consumed to output on a widget in an IDE
"""
if self.process.poll() is not None:
self.close()
yield None, None
while not (self.stdout_queue.empty() and self.stderr_queue.empty()):
if not self.stdout_queue.empty():
line = self.stdout_queue.get().decode('utf-8')
yield line, None
if not self.stderr_queue.empty():
line = self.stderr_queue.get().decode('utf-8')
yield None, line
|
https://github.com/shoebot/shoebot/blob/d554c1765c1899fa25727c9fc6805d221585562b/extensions/lib/shoebotit/ide_utils.py#L233-L253
|
output to html file
|
python
|
def end_output (self, **kwargs):
"""Write end of output info, and flush all output buffers."""
self.stats.downloaded_bytes = kwargs.get("downloaded_bytes")
self.stats.num_urls = kwargs.get("num_urls")
if self.has_part('stats'):
self.write_stats()
if self.has_part('outro'):
self.write_outro(interrupt=kwargs.get("interrupt"))
self.close_fileoutput()
|
https://github.com/wummel/linkchecker/blob/c2ce810c3fb00b895a841a7be6b2e78c64e7b042/linkcheck/logger/text.py#L287-L295
|
output to html file
|
python
|
def write(cls, html_file):
"""Writes the HTML report to the given file."""
f = open(html_file, 'w')
f.write('<html>')
f.write('<head>')
f.write('</head>')
f.write('<body>')
f.write('<h1>Test times</h1>')
fmt_test = '<tr><td>{:.05f}</td><td>{}</td></tr><tr><td> </td><td>{}</td></tr>'
f.write('<table>')
f.write('<tr><th>Time</th><th>Test info</th></tr>')
for row in TestTime.get_slowest_tests(10):
f.write(fmt_test.format(row['elapsed'], row['file'], '{}.{}.{}'.format(row['module'], row['class'], row['func'])))
f.write('</table>')
fmt_file = '<tr><td>{:.05f}</td><td>{}</td></tr>'
f.write('<table>')
f.write('<tr><th>Time</th><th>Test info</th></tr>')
for row in TestTime.get_slowest_files(10):
f.write(fmt_file.format(row['sum_elapsed'], row['file']))
f.write('</table>')
f.write('<h1>Setup times</h1>')
f.write('<table>')
f.write('<tr><th>Time</th><th>Test info</th></tr>')
for row in SetupTime.get_slowest_tests(10):
f.write(fmt_test.format(row['elapsed'], row['file'], '{}.{}.{}'.format(row['module'], row['class'], row['func'])))
f.write('</table>')
f.write('<table>')
f.write('<tr><th>Time</th><th>Test info</th></tr>')
for row in SetupTime.get_slowest_files(10):
f.write(fmt_file.format(row['sum_elapsed'], row['file']))
f.write('</table>')
f.write('</body>')
f.write('</html>')
f.close()
|
https://github.com/etscrivner/nose-perfdump/blob/a203a68495d30346fab43fb903cb60cd29b17d49/perfdump/html.py#L36-L81
|
output to html file
|
python
|
def _output_from_file(self, entry='git_describe'):
"""
Read the version from a .version file that may exist alongside __init__.py.
This file can be generated by piping the following output to file:
git describe --long --match v*.*
"""
try:
vfile = os.path.join(os.path.dirname(self.fpath), '.version')
with open(vfile, 'r') as f:
return json.loads(f.read()).get(entry, None)
except: # File may be missing if using pip + git archive
return None
|
https://github.com/pyviz/param/blob/8f0dafa78defa883247b40635f96cc6d5c1b3481/param/version.py#L231-L244
|
output to html file
|
python
|
def get_output_filename(args):
"""Returns a filename as string without an extension."""
# If filename and path provided, use these for output text file.
if args.directory is not None and args.fileprefix is not None:
path = args.directory
filename = args.fileprefix
output = os.path.join(path, filename)
# Otherwise, set output to current path
elif args.fileprefix is not None:
output = args.fileprefix
else:
output = args.pid
return output
|
https://github.com/StevenMaude/bbc-radio-tracklisting-downloader/blob/9fe9096b4d889888f65756444e4fd71352b92458/bbc_tracklist.py#L132-L144
|
output to html file
|
python
|
def htmlDocContentDumpFormatOutput(self, cur, encoding, format):
"""Dump an HTML document. """
if cur is None: cur__o = None
else: cur__o = cur._o
libxml2mod.htmlDocContentDumpFormatOutput(self._o, cur__o, encoding, format)
|
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/libxml2-2.9.1/python/libxml2.py#L6035-L6039
|
output to html file
|
python
|
def yieldOutput(self):
"""
Generate the text output for the table.
@rtype: generator of str
@return: Text output.
"""
width = self.__width
if width:
num_cols = len(width)
fmt = ['%%%ds' % -w for w in width]
if width[-1] > 0:
fmt[-1] = '%s'
fmt = self.__sep.join(fmt)
for row in self.__cols:
row.extend( [''] * (num_cols - len(row)) )
yield fmt % tuple(row)
|
https://github.com/fabioz/PyDev.Debugger/blob/ed9c4307662a5593b8a7f1f3389ecd0e79b8c503/pydevd_attach_to_process/winappdbg/textio.py#L1180-L1196
|
output to html file
|
python
|
def tofile(path=""):
"""Instead of printing to a screen print to a file
:Example:
with pout.tofile("/path/to/file.txt"):
# all pout calls in this with block will print to file.txt
pout.v("a string")
pout.b()
pout.h()
:param path: str, a path to the file you want to write to
"""
if not path:
path = os.path.join(os.getcwd(), "{}.txt".format(__name__))
global stream
orig_stream = stream
try:
stream = FileStream(path)
yield stream
finally:
stream = orig_stream
|
https://github.com/Jaymon/pout/blob/fa71b64384ddeb3b538855ed93e785d9985aad05/pout/__init__.py#L97-L120
|
output to html file
|
python
|
def output(self, mode='file', forced=False, context=None):
"""
The general output method, override in subclass if you need to do
any custom modification. Calls other mode specific methods or simply
returns the content directly.
"""
output = '\n'.join(self.filter_input(forced, context=context))
if not output:
return ''
if settings.COMPRESS_ENABLED or forced:
filtered_output = self.filter_output(output)
return self.handle_output(mode, filtered_output, forced)
return output
|
https://github.com/django-leonardo/django-leonardo/blob/4b933e1792221a13b4028753d5f1d3499b0816d4/leonardo/utils/compress_patch.py#L165-L180
|
output to html file
|
python
|
def to_file(self, slug, folderpath=None, header=None, footer=None):
"""
Writes the html report to a file from the report stack
"""
if folderpath is None:
if self.report_path is None:
self.err(
"Please set the report_path parameter or pass a path in arguments")
return
folderpath = self.report_path
else:
self.report_path = folderpath
html = self._get_header(header)
if html is None or html == "":
self.err(self.to_file, "Can not get html header")
for report in self.reports:
if "html" not in report:
self.err("No html for report " + report)
self.reports = self.report_engines = []
return
html += report["html"]
html += self._get_footer(footer)
try:
path = self._write_file(slug, folderpath, html)
path = "file://" + path
except Exception as e:
self.err(e, self.to_file, "Can not save report to file")
return
self.reports = []
self.report_engines = []
if self.notebook is True:
link = '<a href="' + path + '" target="_blank">' + path + '</a>'
return display(HTML(link))
|
https://github.com/synw/dataswim/blob/4a4a53f80daa7cd8e8409d76a19ce07296269da2/dataswim/report.py#L57-L89
|
output to html file
|
python
|
def getoutput(cmd):
"""Return standard output of executing cmd in a shell.
Accepts the same arguments as os.system().
Parameters
----------
cmd : str
A command to be executed in the system shell.
Returns
-------
stdout : str
"""
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
out = process_handler(cmd, lambda p: p.communicate()[0], STDOUT)
if out is None:
out = b''
return py3compat.bytes_to_str(out)
|
https://github.com/cloud9ers/gurumate/blob/075dc74d1ee62a8c6b7a8bf2b271364f01629d1e/environment/lib/python2.7/site-packages/IPython/utils/_process_win32.py#L136-L158
|
output to html file
|
python
|
def get_output(self, buildroot_id):
"""
Build the 'output' section of the metadata.
:return: list, Output instances
"""
def add_buildroot_id(output):
logfile, metadata = output
metadata.update({'buildroot_id': buildroot_id})
return Output(file=logfile, metadata=metadata)
def add_log_type(output, arch):
logfile, metadata = output
metadata.update({'type': 'log', 'arch': arch})
return Output(file=logfile, metadata=metadata)
arch = os.uname()[4]
output_files = [add_log_type(add_buildroot_id(metadata), arch)
for metadata in self.get_logs()]
# Parent of squashed built image is base image
image_id = self.workflow.builder.image_id
parent_id = None
if not self.workflow.builder.base_from_scratch:
parent_id = self.workflow.builder.base_image_inspect['Id']
# Read config from the registry using v2 schema 2 digest
registries = self.workflow.push_conf.docker_registries
if registries:
config = copy.deepcopy(registries[0].config)
else:
config = {}
# We don't need container_config section
if config and 'container_config' in config:
del config['container_config']
repositories, typed_digests = self.get_repositories_and_digests()
tags = set(image.tag for image in self.workflow.tag_conf.images)
metadata, output = self.get_image_output()
metadata.update({
'arch': arch,
'type': 'docker-image',
'components': self.get_image_components(),
'extra': {
'image': {
'arch': arch,
},
'docker': {
'id': image_id,
'parent_id': parent_id,
'repositories': repositories,
'layer_sizes': self.workflow.layer_sizes,
'tags': list(tags),
'config': config,
'digests': typed_digests
},
},
})
if self.workflow.builder.base_from_scratch:
del metadata['extra']['docker']['parent_id']
if not config:
del metadata['extra']['docker']['config']
if not typed_digests:
del metadata['extra']['docker']['digests']
# Add the 'docker save' image to the output
image = add_buildroot_id(output)
output_files.append(image)
# add operator manifests to output
operator_manifests_path = (self.workflow.postbuild_results
.get(PLUGIN_EXPORT_OPERATOR_MANIFESTS_KEY))
if operator_manifests_path:
operator_manifests_file = open(operator_manifests_path)
manifests_metadata = self.get_output_metadata(operator_manifests_path,
OPERATOR_MANIFESTS_ARCHIVE)
operator_manifests_output = Output(file=operator_manifests_file,
metadata=manifests_metadata)
# We use log type here until a more appropriate type name is supported by koji
operator_manifests_output.metadata.update({'arch': arch, 'type': 'log'})
operator_manifests = add_buildroot_id(operator_manifests_output)
output_files.append(operator_manifests)
return output_files
|
https://github.com/projectatomic/atomic-reactor/blob/fd31c01b964097210bf169960d051e5f04019a80/atomic_reactor/plugins/post_koji_upload.py#L380-L467
|
output to html file
|
python
|
def convert_to_html(self,
file,
filename=None,
file_content_type=None,
model=None,
**kwargs):
"""
Convert document to HTML.
Converts a document to HTML.
:param file file: The document to convert.
:param str filename: The filename for file.
:param str file_content_type: The content type of file.
:param str model: The analysis model to be used by the service. For the **Element
classification** and **Compare two documents** methods, the default is
`contracts`. For the **Extract tables** method, the default is `tables`. These
defaults apply to the standalone methods as well as to the methods' use in
batch-processing requests.
:param dict headers: A `dict` containing the request headers
:return: A `DetailedResponse` containing the result, headers and HTTP status code.
:rtype: DetailedResponse
"""
if file is None:
raise ValueError('file must be provided')
headers = {}
if 'headers' in kwargs:
headers.update(kwargs.get('headers'))
sdk_headers = get_sdk_headers('compare-comply', 'V1', 'convert_to_html')
headers.update(sdk_headers)
params = {'version': self.version, 'model': model}
form_data = {}
if not filename and hasattr(file, 'name'):
filename = basename(file.name)
if not filename:
raise ValueError('filename must be provided')
form_data['file'] = (filename, file, file_content_type or
'application/octet-stream')
url = '/v1/html_conversion'
response = self.request(
method='POST',
url=url,
headers=headers,
params=params,
files=form_data,
accept_json=True)
return response
|
https://github.com/watson-developer-cloud/python-sdk/blob/4c2c9df4466fcde88975da9ecd834e6ba95eb353/ibm_watson/compare_comply_v1.py#L93-L144
|
output to html file
|
python
|
def generate_output(self, writer):
"""
Generates the sitemap file and the stylesheet file and puts them into the content dir.
:param writer: the writer instance
:type writer: pelican.writers.Writer
"""
# write xml stylesheet
with codecs_open(os.path.join(os.path.dirname(__file__), 'sitemap-stylesheet.xsl'), 'r', encoding='utf-8') as fd_origin:
with codecs_open(os.path.join(self.path_output, 'sitemap-stylesheet.xsl'), 'w', encoding='utf-8') as fd_destination:
xsl = fd_origin.read()
# replace some template markers
# TODO use pelican template magic
xsl = xsl.replace('{{ SITENAME }}', self.context.get('SITENAME'))
fd_destination.write(xsl)
# will contain the url nodes as text
urls = ''
# get all articles sorted by time
articles_sorted = sorted(self.context['articles'], key=self.__get_date_key, reverse=True)
# get all pages with date/modified date
pages_with_date = list(
filter(
lambda p: getattr(p, 'modified', False) or getattr(p, 'date', False),
self.context.get('pages')
)
)
pages_with_date_sorted = sorted(pages_with_date, key=self.__get_date_key, reverse=True)
# get all pages without date
pages_without_date = list(
filter(
lambda p: getattr(p, 'modified', None) is None and getattr(p, 'date', None) is None,
self.context.get('pages')
)
)
pages_without_date_sorted = sorted(pages_without_date, key=self.__get_title_key, reverse=False)
# join them, first date sorted, then title sorted
pages_sorted = pages_with_date_sorted + pages_without_date_sorted
# the landing page
if 'index' in self.context.get('DIRECT_TEMPLATES'):
# assume that the index page has changed with the most current article or page
# use the first article or page if no articles
index_reference = None
if len(articles_sorted) > 0:
index_reference = articles_sorted[0]
elif len(pages_sorted) > 0:
index_reference = pages_sorted[0]
if index_reference is not None:
urls += self.__create_url_node_for_content(
index_reference,
'index',
url=self.url_site,
)
# process articles
for article in articles_sorted:
urls += self.__create_url_node_for_content(
article,
'articles',
url=urljoin(self.url_site, article.url)
)
# process pages
for page in pages_sorted:
urls += self.__create_url_node_for_content(
page,
'pages',
url=urljoin(self.url_site, page.url)
)
# process category pages
if self.context.get('CATEGORY_URL'):
urls += self.__process_url_wrapper_elements(self.context.get('categories'))
# process tag pages
if self.context.get('TAG_URL'):
urls += self.__process_url_wrapper_elements(sorted(self.context.get('tags'), key=lambda x: x[0].name))
# process author pages
if self.context.get('AUTHOR_URL'):
urls += self.__process_url_wrapper_elements(self.context.get('authors'))
# handle all DIRECT_TEMPLATES but "index"
for direct_template in list(filter(lambda p: p != 'index', self.context.get('DIRECT_TEMPLATES'))):
# we assume the modification date of the last article as modification date for the listings of
# categories, authors and archives (all values of DIRECT_TEMPLATES but "index")
modification_time = getattr(articles_sorted[0], 'modified', getattr(articles_sorted[0], 'date', None))
url = self.__get_direct_template_url(direct_template)
urls += self.__create_url_node_for_content(None, 'others', url, modification_time)
# write the final sitemap file
with codecs_open(os.path.join(self.path_output, 'sitemap.xml'), 'w', encoding='utf-8') as fd:
fd.write(self.xml_wrap % {
'SITEURL': self.url_site,
'urls': urls
})
|
https://github.com/dArignac/pelican-extended-sitemap/blob/1cf7746c071c303db3b321955a91b3a78d9585f8/extended_sitemap/__init__.py#L86-L186
|
output to html file
|
python
|
def _output_file_data(self, outfp, blocksize, ino):
# type: (BinaryIO, int, inode.Inode) -> int
'''
Internal method to write a directory record entry out.
Parameters:
outfp - The file object to write the data to.
blocksize - The blocksize to use when writing the data out.
ino - The Inode to write.
Returns:
The total number of bytes written out.
'''
log_block_size = self.pvd.logical_block_size()
outfp.seek(ino.extent_location() * log_block_size)
tmp_start = outfp.tell()
with inode.InodeOpenData(ino, log_block_size) as (data_fp, data_len):
utils.copy_data(data_len, blocksize, data_fp, outfp)
utils.zero_pad(outfp, data_len, log_block_size)
if self._track_writes:
end = outfp.tell()
bisect.insort_left(self._write_check_list, self._WriteRange(tmp_start, end - 1))
# If this file is being used as a bootfile, and the user
# requested that the boot info table be patched into it,
# we patch the boot info table at offset 8 here.
if ino.boot_info_table is not None:
old = outfp.tell()
outfp.seek(tmp_start + 8)
self._outfp_write_with_check(outfp, ino.boot_info_table.record(),
enable_overwrite_check=False)
outfp.seek(old)
return outfp.tell() - tmp_start
|
https://github.com/clalancette/pycdlib/blob/1e7b77a809e905d67dc71e12d70e850be26b6233/pycdlib/pycdlib.py#L2711-L2744
|
output to html file
|
python
|
def to_output(self, value):
"""Convert value to process output format."""
return {self.name: [self.inner.to_output(v)[self.name] for v in value]}
|
https://github.com/genialis/resolwe/blob/f7bb54932c81ec0cfc5b5e80d238fceaeaa48d86/resolwe/process/fields.py#L453-L455
|
output to html file
|
python
|
def write_inputs(self, output_dir, **kwargs):
"""
Writes all input files (input script, and data if needed).
Other supporting files are not handled at this moment.
Args:
output_dir (str): Directory to output the input files.
**kwargs: kwargs supported by LammpsData.write_file.
"""
write_lammps_inputs(output_dir=output_dir,
script_template=self.script_template,
settings=self.settings, data=self.data,
script_filename=self.script_filename, **kwargs)
|
https://github.com/materialsproject/pymatgen/blob/4ca558cf72f8d5f8a1f21dfdfc0181a971c186da/pymatgen/io/lammps/inputs.py#L61-L74
|
output to html file
|
python
|
def get_output_docs(self):
"""Return the output docstrings once formatted
:returns: the formatted docstrings
:rtype: list
"""
if not self.parsed:
self._parse()
lst = []
for e in self.docs_list:
lst.append(e['docs'].get_raw_docs())
return lst
|
https://github.com/dadadel/pyment/blob/3d1bdf87d083ff56230bd0bf7c5252e20552b7b6/pyment/pyment.py#L222-L234
|
output to html file
|
python
|
def write_output(self):
"""Write the Playbook output variables.
This method should be overridden with the output variables defined in the install.json
configuration file.
"""
self.tcex.log.info('Writing Output')
self.tcex.playbook.create_output('json.pretty', self.pretty_json)
|
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/app_init/playbook_utility/app.py#L54-L61
|
output to html file
|
python
|
def get_simple_output(self, stderr=STDOUT):
"""Executes a simple external command and get its output
The command contains no pipes. Error messages are
redirected to the standard output by default
:param stderr: where to put stderr
:return: output of command
"""
args = shlex.split(self.cmd)
proc = Popen(args, stdout=PIPE, stderr=stderr)
return proc.communicate()[0].decode("utf8")
|
https://github.com/sirfoga/pyhal/blob/4394d8a1f7e45bea28a255ec390f4962ee64d33a/hal/system/process.py#L21-L31
|
output to html file
|
python
|
def _format_output(self, outfile_name, out_type):
""" Prepend proper output prefix to output filename """
outfile_name = self._absolute(outfile_name)
outparts = outfile_name.split("/")
outparts[-1] = self._out_format % (out_type, outparts[-1] )
return '/'.join(outparts)
|
https://github.com/biocore/burrito-fillings/blob/02ab71a46119b40793bd56a4ae00ca15f6dc3329/bfillings/raxml_v730.py#L468-L475
|
output to html file
|
python
|
def _get_output_template(self):
'''Return the path prefix and output template.'''
path = self._file_writer_session.extra_resource_path('.youtube-dl')
if not path:
self._temp_dir = tempfile.TemporaryDirectory(
dir=self._root_path, prefix='tmp-wpull-youtubedl'
)
path = '{}/tmp'.format(self._temp_dir.name)
return path, '{}.%(id)s.%(format_id)s.%(ext)s'.format(path)
|
https://github.com/ArchiveTeam/wpull/blob/ddf051aa3322479325ba20aa778cb2cb97606bf5/wpull/processor/coprocessor/youtubedl.py#L124-L134
|
output to html file
|
python
|
def make_op_return_outputs(data, inputs, change_address, fee=OP_RETURN_FEE,
send_amount=0, format='bin'):
""" Builds the outputs for an OP_RETURN transaction.
"""
return [
# main output
{ "script_hex": make_op_return_script(data, format=format), "value": send_amount },
# change output
{ "script_hex": make_pay_to_address_script(change_address),
"value": calculate_change_amount(inputs, send_amount, fee)
}
]
|
https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L36-L47
|
output to html file
|
python
|
def get_output_stream(encoding=anytemplate.compat.ENCODING,
ostream=sys.stdout):
"""
Get output stream take care of characters encoding correctly.
:param ostream: Output stream (file-like object); sys.stdout by default
:param encoding: Characters set encoding, e.g. UTF-8
:return: sys.stdout can output encoded strings
>>> get_output_stream("UTF-8") # doctest: +ELLIPSIS
<encodings.utf_8.StreamWriter ... at 0x...>
"""
return codecs.getwriter(encoding)(ostream)
|
https://github.com/ssato/python-anytemplate/blob/3e56baa914bd47f044083b20e33100f836443596/anytemplate/utils.py#L29-L41
|
output to html file
|
python
|
def dump(self, stream, index=0, count=0, output=str()):
""" Dumps the content of the byte *stream* to the console or to the
optional given *output* file.
:param bytes stream: byte stream to view.
:param int index: optional start index of the viewing area in bytes.
Default is the begin of the stream.
:param int count: optional number of bytes to view.
Default is to the end of the stream.
:param str output: location and name for the optional output file.
"""
def numerate(pattern, _count):
return ''.join(pattern.format(x) for x in range(_count))
def write_to(file_handle, content):
if file_handle:
file_handle.write(content + "\n")
else:
print(content)
dst = None
if output:
dst = open(output, 'w')
start, stop = self._view_area(stream, index, count)
digits = max(len(hex(start + stop)) - 2, 8)
# Write header
write_to(dst,
" " * digits +
" |" +
numerate(" {0:02d}", self.columns) +
" |")
write_to(dst,
"-" * digits +
"-+" +
"-" * (self.columns * 3) +
"-+-" +
"-" * self.columns)
# Set start row and column
row = int(start / self.columns)
column = int(start % self.columns)
# Initialize output for start index row
output_line = "{0:0{1:d}X} |".format(row * self.columns,
digits)
output_line += " .." * column
output_ascii = "." * column
# Iterate over viewing area
for value in stream[start:stop]:
column += 1
output_line += " {0:02X}".format(int(value))
if value in range(32, 126):
output_ascii += "{0:c}".format(value)
else:
output_ascii += "."
column %= self.columns
if not column:
# Write output line
output_line += ' | ' + output_ascii
write_to(dst, output_line)
# Next row
row += 1
output_line = "{0:0{1:d}X} |".format(row * self.columns,
digits)
output_ascii = ""
# Write output of stop index row
if column:
# Fill missing columns with white spaces
output_line += " " * (self.columns - column) * 3
output_line += " | " + output_ascii
write_to(dst, output_line)
|
https://github.com/JoeVirtual/KonFoo/blob/0c62ef5c2bed4deaf908b34082e4de2544532fdc/konfoo/utils.py#L90-L165
|
output to html file
|
python
|
def dump(self, output, close_after_write=True):
"""Write data to the output with tabular format.
Args:
output (file descriptor or str):
file descriptor or path to the output file.
close_after_write (bool, optional):
Close the output after write.
Defaults to |True|.
"""
try:
output.write
self.stream = output
except AttributeError:
self.stream = io.open(output, "w", encoding="utf-8")
try:
self.write_table()
finally:
if close_after_write:
self.stream.close()
self.stream = sys.stdout
|
https://github.com/thombashi/pytablewriter/blob/52ea85ed8e89097afa64f137c6a1b3acdfefdbda/pytablewriter/writer/text/_text_writer.py#L179-L201
|
output to html file
|
python
|
def output(*streams_and_filename, **kwargs):
"""Output file URL
Syntax:
`ffmpeg.output(stream1[, stream2, stream3...], filename, **ffmpeg_args)`
Any supplied keyword arguments are passed to ffmpeg verbatim (e.g.
``t=20``, ``f='mp4'``, ``acodec='pcm'``, ``vcodec='rawvideo'``,
etc.). Some keyword-arguments are handled specially, as shown below.
Args:
video_bitrate: parameter for ``-b:v``, e.g. ``video_bitrate=1000``.
audio_bitrate: parameter for ``-b:a``, e.g. ``audio_bitrate=200``.
format: alias for ``-f`` parameter, e.g. ``format='mp4'``
(equivalent to ``f='mp4'``).
If multiple streams are provided, they are mapped to the same
output.
To tell ffmpeg to write to stdout, use ``pipe:`` as the filename.
Official documentation: `Synopsis <https://ffmpeg.org/ffmpeg.html#Synopsis>`__
"""
streams_and_filename = list(streams_and_filename)
if 'filename' not in kwargs:
if not isinstance(streams_and_filename[-1], basestring):
raise ValueError('A filename must be provided')
kwargs['filename'] = streams_and_filename.pop(-1)
streams = streams_and_filename
fmt = kwargs.pop('f', None)
if fmt:
if 'format' in kwargs:
raise ValueError("Can't specify both `format` and `f` kwargs")
kwargs['format'] = fmt
return OutputNode(streams, output.__name__, kwargs=kwargs).stream()
|
https://github.com/kkroening/ffmpeg-python/blob/ac111dc3a976ddbb872bc7d6d4fe24a267c1a956/ffmpeg/_ffmpeg.py#L59-L94
|
output to html file
|
python
|
def html(self, text=TEXT):
""" Generate an HTML file from the report data. """
self.logger.debug("Generating the HTML report{}..."
.format(["", " (text only)"][text]))
html = []
for piece in self._pieces:
if isinstance(piece, string_types):
html.append(markdown2.markdown(piece, extras=["tables"]))
elif isinstance(piece, Element):
html.append(piece.html())
return "\n\n".join(html)
|
https://github.com/dhondta/tinyscript/blob/624a0718db698899e7bc3ba6ac694baed251e81d/tinyscript/report/__init__.py#L133-L143
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.