_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q273800 | logger_init | test | def logger_init():
'''Initialize logger based on configuration
'''
handlers = []
logconf = config('logging')
if logconf['syslog']:
handlers.append(logging.handlers.SysLogHandler(address='/dev/log'))
if logconf['stderr']:
handlers.append(logging.StreamHandler(sys.stderr))
if l... | python | {
"resource": ""
} |
q273801 | home | test | def home():
'''Serve the status page of the capture agent.
'''
# Get IDs of existing preview images
preview = config()['capture']['preview']
previewdir = config()['capture']['preview_dir']
preview = [p.replace('{{previewdir}}', previewdir) for p in preview]
preview = zip(preview, range(len(p... | python | {
"resource": ""
} |
q273802 | serve_image | test | def serve_image(image_id):
'''Serve the preview image with the given id
'''
try:
preview_dir = config()['capture']['preview_dir']
filepath = config()['capture']['preview'][image_id]
filepath = filepath.replace('{{previewdir}}', preview_dir)
filepath = os.path.abspath(filepath... | python | {
"resource": ""
} |
q273803 | run_all | test | def run_all(*modules):
'''Start all services.
'''
processes = [multiprocessing.Process(target=mod.run) for mod in modules]
for p in processes:
p.start()
for p in processes:
p.join() | python | {
"resource": ""
} |
q273804 | parse_ical | test | def parse_ical(vcal):
'''Parse Opencast schedule iCalendar file and return events as dict
'''
vcal = vcal.replace('\r\n ', '').replace('\r\n\r\n', '\r\n')
vevents = vcal.split('\r\nBEGIN:VEVENT\r\n')
del(vevents[0])
events = []
for vevent in vevents:
event = {}
for line in ve... | python | {
"resource": ""
} |
q273805 | get_schedule | test | def get_schedule():
'''Try to load schedule from the Matterhorn core. Returns a valid schedule
or None on failure.
'''
params = {'agentid': config()['agent']['name'].encode('utf8')}
lookahead = config()['agent']['cal_lookahead'] * 24 * 60 * 60
if lookahead:
params['cutoff'] = str((timest... | python | {
"resource": ""
} |
q273806 | control_loop | test | def control_loop():
'''Main loop, retrieving the schedule.
'''
set_service_status(Service.SCHEDULE, ServiceStatus.BUSY)
notify.notify('READY=1')
while not terminate():
notify.notify('WATCHDOG=1')
# Try getting an updated schedule
get_schedule()
session = get_session()... | python | {
"resource": ""
} |
q273807 | control_loop | test | def control_loop():
'''Main loop, updating the capture agent state.
'''
set_service_status(Service.AGENTSTATE, ServiceStatus.BUSY)
notify.notify('READY=1')
notify.notify('STATUS=Running')
while not terminate():
notify.notify('WATCHDOG=1')
update_agent_state()
next_update... | python | {
"resource": ""
} |
q273808 | make_error_response | test | def make_error_response(error, status=500):
''' Return a response with a jsonapi error object
'''
content = {
'errors': [{
'status': status,
'title': error
}]
}
return make_response(jsonify(content), status) | python | {
"resource": ""
} |
q273809 | make_data_response | test | def make_data_response(data, status=200):
''' Return a response with a list of jsonapi data objects
'''
content = {'data': ensurelist(data)}
return make_response(jsonify(content), status) | python | {
"resource": ""
} |
q273810 | internal_state | test | def internal_state():
'''Serve a json representation of internal agentstate as meta data
'''
data = {'services': {
'capture': ServiceStatus.str(get_service_status(Service.CAPTURE)),
'ingest': ServiceStatus.str(get_service_status(Service.INGEST)),
'schedule': ServiceStatus.str(get_ser... | python | {
"resource": ""
} |
q273811 | events | test | def events():
'''Serve a JSON representation of events
'''
db = get_session()
upcoming_events = db.query(UpcomingEvent)\
.order_by(UpcomingEvent.start)
recorded_events = db.query(RecordedEvent)\
.order_by(RecordedEvent.start.desc())
result = [even... | python | {
"resource": ""
} |
q273812 | event | test | def event(uid):
'''Return a specific events JSON
'''
db = get_session()
event = db.query(RecordedEvent).filter(RecordedEvent.uid == uid).first() \
or db.query(UpcomingEvent).filter(UpcomingEvent.uid == uid).first()
if event:
return make_data_response(event.serialize())
return ma... | python | {
"resource": ""
} |
q273813 | delete_event | test | def delete_event(uid):
'''Delete a specific event identified by its uid. Note that only recorded
events can be deleted. Events in the buffer for upcoming events are
regularly replaced anyway and a manual removal could have unpredictable
effects.
Use ?hard=true parameter to delete the recorded files... | python | {
"resource": ""
} |
q273814 | modify_event | test | def modify_event(uid):
'''Modify an event specified by its uid. The modifications for the event
are expected as JSON with the content type correctly set in the request.
Note that this method works for recorded events only. Upcoming events part
of the scheduler cache cannot be modified.
'''
try:... | python | {
"resource": ""
} |
q273815 | get_config_params | test | def get_config_params(properties):
'''Extract the set of configuration parameters from the properties attached
to the schedule
'''
param = []
wdef = ''
for prop in properties.split('\n'):
if prop.startswith('org.opencastproject.workflow.config'):
key, val = prop.split('=', 1)... | python | {
"resource": ""
} |
q273816 | ingest | test | def ingest(event):
'''Ingest a finished recording to the Opencast server.
'''
# Update status
set_service_status(Service.INGEST, ServiceStatus.BUSY)
notify.notify('STATUS=Uploading')
recording_state(event.uid, 'uploading')
update_event_status(event, Status.UPLOADING)
# Select ingest ser... | python | {
"resource": ""
} |
q273817 | start_capture | test | def start_capture(upcoming_event):
'''Start the capture process, creating all necessary files and directories
as well as ingesting the captured files if no backup mode is configured.
'''
logger.info('Start recording')
# First move event to recording_event table
db = get_session()
event = db... | python | {
"resource": ""
} |
q273818 | ExampleFragmentView.render_to_fragment | test | def render_to_fragment(self, request, **kwargs):
"""
Returns a simple fragment
"""
fragment = Fragment(TEST_HTML)
fragment.add_javascript(TEST_JS)
fragment.add_css(TEST_CSS)
return fragment | python | {
"resource": ""
} |
q273819 | Fragment.resources | test | def resources(self):
"""
Returns list of unique `FragmentResource`s by order of first appearance.
"""
seen = set()
# seen.add always returns None, so 'not seen.add(x)' is always True,
# but will only be called if the value is not already in seen (because
# 'and' s... | python | {
"resource": ""
} |
q273820 | Fragment.to_dict | test | def to_dict(self):
"""
Returns the fragment in a dictionary representation.
"""
return {
'content': self.content,
'resources': [r._asdict() for r in self.resources], # pylint: disable=W0212
'js_init_fn': self.js_init_fn,
'js_init_version':... | python | {
"resource": ""
} |
q273821 | Fragment.from_dict | test | def from_dict(cls, pods):
"""
Returns a new Fragment from a dictionary representation.
"""
frag = cls()
frag.content = pods['content']
frag._resources = [FragmentResource(**d) for d in pods['resources']] # pylint: disable=protected-access
frag.js_init_fn = pods['... | python | {
"resource": ""
} |
q273822 | Fragment.add_content | test | def add_content(self, content):
"""
Add content to this fragment.
`content` is a Unicode string, HTML to append to the body of the
fragment. It must not contain a ``<body>`` tag, or otherwise assume
that it is the only content on the page.
"""
assert isinstance(... | python | {
"resource": ""
} |
q273823 | Fragment.add_resource | test | def add_resource(self, text, mimetype, placement=None):
"""
Add a resource needed by this Fragment.
Other helpers, such as :func:`add_css` or :func:`add_javascript` are
more convenient for those common types of resource.
`text`: the actual text of this resource, as a unicode st... | python | {
"resource": ""
} |
q273824 | Fragment.add_resource_url | test | def add_resource_url(self, url, mimetype, placement=None):
"""
Add a resource by URL needed by this Fragment.
Other helpers, such as :func:`add_css_url` or
:func:`add_javascript_url` are more convenent for those common types of
resource.
`url`: the URL to the resource.
... | python | {
"resource": ""
} |
q273825 | Fragment.initialize_js | test | def initialize_js(self, js_func, json_args=None):
"""
Register a Javascript function to initialize the Javascript resources.
`js_func` is the name of a Javascript function defined by one of the
Javascript resources. As part of setting up the browser's runtime
environment, the f... | python | {
"resource": ""
} |
q273826 | Fragment.resources_to_html | test | def resources_to_html(self, placement):
"""
Get some resource HTML for this Fragment.
`placement` is "head" or "foot".
Returns a unicode string, the HTML for the head or foot of the page.
"""
# - non url js could be wrapped in an anonymous function
# - non url c... | python | {
"resource": ""
} |
q273827 | Fragment.resource_to_html | test | def resource_to_html(resource):
"""
Returns `resource` wrapped in the appropriate html tag for it's mimetype.
"""
if resource.mimetype == "text/css":
if resource.kind == "text":
return u"<style type='text/css'>\n%s\n</style>" % resource.data
elif r... | python | {
"resource": ""
} |
q273828 | FragmentView.get | test | def get(self, request, *args, **kwargs):
"""
Render a fragment to HTML or return JSON describing it, based on the request.
"""
fragment = self.render_to_fragment(request, **kwargs)
response_format = request.GET.get('format') or request.POST.get('format') or 'html'
if resp... | python | {
"resource": ""
} |
q273829 | FragmentView.render_standalone_response | test | def render_standalone_response(self, request, fragment, **kwargs): # pylint: disable=unused-argument
"""
Renders a standalone page as a response for the specified fragment.
"""
if fragment is None:
return HttpResponse(status=204)
html = self.render_to_standalone_htm... | python | {
"resource": ""
} |
q273830 | FragmentView.render_to_standalone_html | test | def render_to_standalone_html(self, request, fragment, **kwargs): # pylint: disable=unused-argument
"""
Render the specified fragment to HTML for a standalone page.
"""
template = get_template(STANDALONE_TEMPLATE_NAME)
context = {
'head_html': fragment.head_html(),
... | python | {
"resource": ""
} |
q273831 | calc | test | def calc(pvalues, lamb):
""" meaning pvalues presorted i descending order"""
m = len(pvalues)
pi0 = (pvalues > lamb).sum() / ((1 - lamb)*m)
pFDR = np.ones(m)
print("pFDR y Pr fastPow")
for i in range(m):
y = pvalues[i]
Pr = max(1, m - i) / float(m)
pFDR[i]... | python | {
"resource": ""
} |
q273832 | to_one_dim_array | test | def to_one_dim_array(values, as_type=None):
""" Converts list or flattens n-dim array to 1-dim array if possible """
if isinstance(values, (list, tuple)):
values = np.array(values, dtype=np.float32)
elif isinstance(values, pd.Series):
values = values.values
values = values.flatten()
... | python | {
"resource": ""
} |
q273833 | lookup_values_from_error_table | test | def lookup_values_from_error_table(scores, err_df):
""" Find matching q-value for each score in 'scores' """
ix = find_nearest_matches(np.float32(err_df.cutoff.values), np.float32(scores))
return err_df.pvalue.iloc[ix].values, err_df.svalue.iloc[ix].values, err_df.pep.iloc[ix].values, err_df.qvalue.iloc[ix]... | python | {
"resource": ""
} |
q273834 | posterior_chromatogram_hypotheses_fast | test | def posterior_chromatogram_hypotheses_fast(experiment, prior_chrom_null):
""" Compute posterior probabilities for each chromatogram
For each chromatogram (each group_id / peptide precursor), all hypothesis of all peaks
being correct (and all others false) as well as the h0 (all peaks are
false) are com... | python | {
"resource": ""
} |
q273835 | final_err_table | test | def final_err_table(df, num_cut_offs=51):
""" Create artificial cutoff sample points from given range of cutoff
values in df, number of sample points is 'num_cut_offs' """
cutoffs = df.cutoff.values
min_ = min(cutoffs)
max_ = max(cutoffs)
# extend max_ and min_ by 5 % of full range
margin =... | python | {
"resource": ""
} |
q273836 | summary_err_table | test | def summary_err_table(df, qvalues=[0, 0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5]):
""" Summary error table for some typical q-values """
qvalues = to_one_dim_array(qvalues)
# find best matching fows in df for given qvalues:
ix = find_nearest_matches(np.float32(df.qvalue.values), qvalues)
# extract ... | python | {
"resource": ""
} |
q273837 | error_statistics | test | def error_statistics(target_scores, decoy_scores, parametric, pfdr, pi0_lambda, pi0_method = "smoother", pi0_smooth_df = 3, pi0_smooth_log_pi0 = False, compute_lfdr = False, lfdr_trunc = True, lfdr_monotone = True, lfdr_transf = "probit", lfdr_adj = 1.5, lfdr_eps = np.power(10.0,-8)):
""" Takes list of decoy and ta... | python | {
"resource": ""
} |
q273838 | find_cutoff | test | def find_cutoff(tt_scores, td_scores, cutoff_fdr, parametric, pfdr, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0):
""" Finds cut off target score for specified false discovery rate fdr """
error_stat, pi0 = error_statistics(tt_scores, td_scores, parametric, pfdr, pi0_lambda, pi0_method, pi0_smooth... | python | {
"resource": ""
} |
q273839 | score | test | def score(infile, outfile, classifier, xgb_autotune, apply_weights, xeval_fraction, xeval_num_iter, ss_initial_fdr, ss_iteration_fdr, ss_num_iter, ss_main_score, group_id, parametric, pfdr, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0, lfdr_truncate, lfdr_monotone, lfdr_transformation, lfdr_adj, lfdr_eps, ... | python | {
"resource": ""
} |
q273840 | ipf | test | def ipf(infile, outfile, ipf_ms1_scoring, ipf_ms2_scoring, ipf_h0, ipf_grouped_fdr, ipf_max_precursor_pep, ipf_max_peakgroup_pep, ipf_max_precursor_peakgroup_pep, ipf_max_transition_pep):
"""
Infer peptidoforms after scoring of MS1, MS2 and transition-level data.
"""
if outfile is None:
outfile... | python | {
"resource": ""
} |
q273841 | peptide | test | def peptide(infile, outfile, context, parametric, pfdr, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0, lfdr_truncate, lfdr_monotone, lfdr_transformation, lfdr_adj, lfdr_eps):
"""
Infer peptides and conduct error-rate estimation in different contexts.
"""
if outfile is None:
outfile ... | python | {
"resource": ""
} |
q273842 | protein | test | def protein(infile, outfile, context, parametric, pfdr, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0, lfdr_truncate, lfdr_monotone, lfdr_transformation, lfdr_adj, lfdr_eps):
"""
Infer proteins and conduct error-rate estimation in different contexts.
"""
if outfile is None:
outfile ... | python | {
"resource": ""
} |
q273843 | subsample | test | def subsample(infile, outfile, subsample_ratio, test):
"""
Subsample OpenSWATH file to minimum for integrated scoring
"""
if outfile is None:
outfile = infile
else:
outfile = outfile
subsample_osw(infile, outfile, subsample_ratio, test) | python | {
"resource": ""
} |
q273844 | reduce | test | def reduce(infile, outfile):
"""
Reduce scored PyProphet file to minimum for global scoring
"""
if outfile is None:
outfile = infile
else:
outfile = outfile
reduce_osw(infile, outfile) | python | {
"resource": ""
} |
q273845 | backpropagate | test | def backpropagate(infile, outfile, apply_scores):
"""
Backpropagate multi-run peptide and protein scores to single files
"""
if outfile is None:
outfile = infile
else:
outfile = outfile
backpropagate_oswr(infile, outfile, apply_scores) | python | {
"resource": ""
} |
q273846 | filter | test | def filter(sqmassfiles, infile, max_precursor_pep, max_peakgroup_pep, max_transition_pep):
"""
Filter sqMass files
"""
filter_sqmass(sqmassfiles, infile, max_precursor_pep, max_peakgroup_pep, max_transition_pep) | python | {
"resource": ""
} |
q273847 | GWS.get_group_by_id | test | def get_group_by_id(self, group_id):
"""
Returns a restclients.Group object for the group identified by the
passed group ID.
"""
self._valid_group_id(group_id)
url = "{}/group/{}".format(self.API, group_id)
data = self._get_resource(url)
return self._gr... | python | {
"resource": ""
} |
q273848 | GWS.create_group | test | def create_group(self, group):
"""
Creates a group from the passed restclients.Group object.
"""
self._valid_group_id(group.id)
body = {"data": group.json_data()}
url = "{}/group/{}".format(self.API, group.name)
data = self._put_resource(url, headers={}, body=bo... | python | {
"resource": ""
} |
q273849 | GWS.delete_group | test | def delete_group(self, group_id):
"""
Deletes the group identified by the passed group ID.
"""
self._valid_group_id(group_id)
url = "{}/group/{}".format(self.API, group_id)
self._delete_resource(url)
return True | python | {
"resource": ""
} |
q273850 | GWS.get_members | test | def get_members(self, group_id):
"""
Returns a list of restclients.GroupMember objects for the group
identified by the passed group ID.
"""
self._valid_group_id(group_id)
url = "{}/group/{}/member".format(self.API, group_id)
data = self._get_resource(url)
... | python | {
"resource": ""
} |
q273851 | GWS.update_members | test | def update_members(self, group_id, members):
"""
Updates the membership of the group represented by the passed group id.
Returns a list of members not found.
"""
self._valid_group_id(group_id)
body = {"data": [m.json_data() for m in members]}
headers = {"If-Match... | python | {
"resource": ""
} |
q273852 | GWS.get_effective_member_count | test | def get_effective_member_count(self, group_id):
"""
Returns a count of effective members for the group identified by the
passed group ID.
"""
self._valid_group_id(group_id)
url = "{}/group/{}/effective_member?view=count".format(self.API,
... | python | {
"resource": ""
} |
q273853 | GWS.is_effective_member | test | def is_effective_member(self, group_id, netid):
"""
Returns True if the netid is in the group, False otherwise.
"""
self._valid_group_id(group_id)
# GWS doesn't accept EPPNs on effective member checks, for UW users
netid = re.sub('@washington.edu', '', netid)
ur... | python | {
"resource": ""
} |
q273854 | modify_conf | test | def modify_conf():
"""
pip install redbaron
"""
import redbaron
import ubelt as ub
conf_path = 'docs/conf.py'
source = ub.readfrom(conf_path)
red = redbaron.RedBaron(source)
# Insert custom extensions
extra_extensions = [
'"sphinxcontrib.napoleon"'
]
ext_node =... | python | {
"resource": ""
} |
q273855 | Group.create_dataset | test | def create_dataset(self, name, shape=None, dtype=None, data=None,
sparse_format=None, indptr_dtype=np.int64, indices_dtype=np.int32,
**kwargs):
"""Create 3 datasets in a group to represent the sparse array.
Parameters
----------
sparse_forma... | python | {
"resource": ""
} |
q273856 | cli_decrypt | test | def cli_decrypt(context, key):
"""
Decrypts context.io_manager's stdin and sends that to
context.io_manager's stdout.
See :py:mod:`swiftly.cli.decrypt` for context usage information.
See :py:class:`CLIDecrypt` for more information.
"""
with context.io_manager.with_stdout() as stdout:
... | python | {
"resource": ""
} |
q273857 | IOManager.get_stdin | test | def get_stdin(self, os_path=None, skip_sub_command=False):
"""
Returns a stdin-suitable file-like object based on the
optional os_path and optionally skipping any configured
sub-command.
"""
sub_command = None if skip_sub_command else self.stdin_sub_command
inn, p... | python | {
"resource": ""
} |
q273858 | IOManager.get_stdout | test | def get_stdout(self, os_path=None, skip_sub_command=False):
"""
Returns a stdout-suitable file-like object based on the
optional os_path and optionally skipping any configured
sub-command.
"""
sub_command = None if skip_sub_command else self.stdout_sub_command
out... | python | {
"resource": ""
} |
q273859 | IOManager.get_stderr | test | def get_stderr(self, os_path=None, skip_sub_command=False):
"""
Returns a stderr-suitable file-like object based on the
optional os_path and optionally skipping any configured
sub-command.
"""
sub_command = None if skip_sub_command else self.stderr_sub_command
out... | python | {
"resource": ""
} |
q273860 | IOManager.get_debug | test | def get_debug(self, os_path=None, skip_sub_command=False):
"""
Returns a debug-output-suitable file-like object based on the
optional os_path and optionally skipping any configured
sub-command.
"""
sub_command = None if skip_sub_command else self.debug_sub_command
... | python | {
"resource": ""
} |
q273861 | IOManager.with_stdin | test | def with_stdin(self, os_path=None, skip_sub_command=False,
disk_closed_callback=None):
"""
A context manager yielding a stdin-suitable file-like object
based on the optional os_path and optionally skipping any
configured sub-command.
:param os_path: Optional p... | python | {
"resource": ""
} |
q273862 | IOManager.with_stdout | test | def with_stdout(self, os_path=None, skip_sub_command=False,
disk_closed_callback=None):
"""
A context manager yielding a stdout-suitable file-like object
based on the optional os_path and optionally skipping any
configured sub-command.
:param os_path: Optiona... | python | {
"resource": ""
} |
q273863 | IOManager.with_stderr | test | def with_stderr(self, os_path=None, skip_sub_command=False,
disk_closed_callback=None):
"""
A context manager yielding a stderr-suitable file-like object
based on the optional os_path and optionally skipping any
configured sub-command.
:param os_path: Optiona... | python | {
"resource": ""
} |
q273864 | IOManager.with_debug | test | def with_debug(self, os_path=None, skip_sub_command=False,
disk_closed_callback=None):
"""
A context manager yielding a debug-output-suitable file-like
object based on the optional os_path and optionally skipping
any configured sub-command.
:param os_path: Opt... | python | {
"resource": ""
} |
q273865 | cli_empty_account | test | def cli_empty_account(context, yes_empty_account=False, until_empty=False):
"""
Deletes all objects and containers in the account.
You must set yes_empty_account to True to verify you really want to
do this.
By default, this will perform one pass at deleting all objects and
containers; so if o... | python | {
"resource": ""
} |
q273866 | cli_empty_container | test | def cli_empty_container(context, path, until_empty=False):
"""
Deletes all objects in the container.
By default, this will perform one pass at deleting all objects in
the container; so if objects revert to previous versions or if new
objects otherwise arise during the process, the container may not... | python | {
"resource": ""
} |
q273867 | _stdout_filed | test | def _stdout_filed(func):
"""
Instance method decorator to convert an optional file keyword
argument into an actual value, whether it be a passed value, a
value obtained from an io_manager, or sys.stdout.
"""
def wrapper(self, file=None):
if file:
return func(self, file=file)
... | python | {
"resource": ""
} |
q273868 | _stderr_filed | test | def _stderr_filed(func):
"""
Instance method decorator to convert an optional file keyword
argument into an actual value, whether it be a passed value, a
value obtained from an io_manager, or sys.stderr.
"""
def wrapper(self, msg, file=None):
if file:
return func(self, msg, f... | python | {
"resource": ""
} |
q273869 | OptionParser.error | test | def error(self, msg, file=None):
"""
Outputs the error msg to the file if specified, or to the
io_manager's stderr if available, or to sys.stderr.
"""
self.error_encountered = True
file.write(self.error_prefix)
file.write(msg)
file.write('\n')
file... | python | {
"resource": ""
} |
q273870 | OptionParser.print_help | test | def print_help(self, file=None):
"""
Outputs help information to the file if specified, or to the
io_manager's stdout if available, or to sys.stdout.
"""
optparse.OptionParser.print_help(self, file)
if self.raw_epilog:
file.write(self.raw_epilog)
file.... | python | {
"resource": ""
} |
q273871 | OptionParser.print_usage | test | def print_usage(self, file=None):
"""
Outputs usage information to the file if specified, or to the
io_manager's stdout if available, or to sys.stdout.
"""
optparse.OptionParser.print_usage(self, file)
file.flush() | python | {
"resource": ""
} |
q273872 | OptionParser.print_version | test | def print_version(self, file=None):
"""
Outputs version information to the file if specified, or to
the io_manager's stdout if available, or to sys.stdout.
"""
optparse.OptionParser.print_version(self, file)
file.flush() | python | {
"resource": ""
} |
q273873 | Client.request | test | def request(self, method, path, contents, headers, decode_json=False,
stream=False, query=None, cdn=False):
"""
Performs a direct HTTP request to the Swift service.
:param method: The request method ('GET', 'HEAD', etc.)
:param path: The request path.
:param cont... | python | {
"resource": ""
} |
q273874 | Client.post_account | test | def post_account(self, headers=None, query=None, cdn=False, body=None):
"""
POSTs the account and returns the results. This is usually
done to set X-Account-Meta-xxx headers. Note that any existing
X-Account-Meta-xxx headers will remain untouched. To remove an
X-Account-Meta-xxx ... | python | {
"resource": ""
} |
q273875 | Client.delete_account | test | def delete_account(self, headers=None,
yes_i_mean_delete_the_account=False, query=None,
cdn=False, body=None):
"""
Sends a DELETE request to the account and returns the results.
With ``query['bulk-delete'] = ''`` this might mean a bulk
delet... | python | {
"resource": ""
} |
q273876 | Client.put_container | test | def put_container(self, container, headers=None, query=None, cdn=False,
body=None):
"""
PUTs the container and returns the results. This is usually
done to create new containers and can also be used to set
X-Container-Meta-xxx headers. Note that if the container
... | python | {
"resource": ""
} |
q273877 | Client.head_object | test | def head_object(self, container, obj, headers=None, query=None, cdn=False):
"""
HEADs the object and returns the results.
:param container: The name of the container.
:param obj: The name of the object.
:param headers: Additional headers to send with the request.
:param ... | python | {
"resource": ""
} |
q273878 | Client.get_object | test | def get_object(self, container, obj, headers=None, stream=True, query=None,
cdn=False):
"""
GETs the object and returns the results.
:param container: The name of the container.
:param obj: The name of the object.
:param headers: Additional headers to send wit... | python | {
"resource": ""
} |
q273879 | Client.put_object | test | def put_object(self, container, obj, contents, headers=None, query=None,
cdn=False):
"""
PUTs the object and returns the results. This is used to
create or overwrite objects. X-Object-Meta-xxx can optionally
be sent to be stored with the object. Content-Type,
C... | python | {
"resource": ""
} |
q273880 | Client.post_object | test | def post_object(self, container, obj, headers=None, query=None, cdn=False,
body=None):
"""
POSTs the object and returns the results. This is used to
update the object's header values. Note that all headers must
be sent with the POST, unlike the account and container P... | python | {
"resource": ""
} |
q273881 | CLI._resolve_option | test | def _resolve_option(self, options, option_name, section_name):
"""Resolves an option value into options.
Sets options.<option_name> to a resolved value. Any value
already in options overrides a value in os.environ which
overrides self.context.conf.
:param options: The options i... | python | {
"resource": ""
} |
q273882 | CLIContext.copy | test | def copy(self):
"""
Returns a new CLIContext instance that is a shallow copy of
the original, much like dict's copy method.
"""
context = CLIContext()
for item in dir(self):
if item[0] != '_' and item not in ('copy', 'write_headers'):
setattr(c... | python | {
"resource": ""
} |
q273883 | CLIContext.write_headers | test | def write_headers(self, fp, headers, mute=None):
"""
Convenience function to output headers in a formatted fashion
to a file-like fp, optionally muting any headers in the mute
list.
"""
if headers:
if not mute:
mute = []
fmt = '%%-%... | python | {
"resource": ""
} |
q273884 | cli_auth | test | def cli_auth(context):
"""
Authenticates and then outputs the resulting information.
See :py:mod:`swiftly.cli.auth` for context usage information.
See :py:class:`CLIAuth` for more information.
"""
with context.io_manager.with_stdout() as fp:
with context.client_manager.with_client() as... | python | {
"resource": ""
} |
q273885 | generate_temp_url | test | def generate_temp_url(method, url, seconds, key):
"""
Returns a TempURL good for the given request method, url, and
number of seconds from now, signed by the given key.
"""
method = method.upper()
base_url, object_path = url.split('/v1/')
object_path = '/v1/' + object_path
expires = int(... | python | {
"resource": ""
} |
q273886 | quote | test | def quote(value, safe='/:'):
"""
Much like parse.quote in that it returns a URL encoded string
for the given value, protecting the safe characters; but this
version also ensures the value is UTF-8 encoded.
"""
if isinstance(value, six.text_type):
value = value.encode('utf8')
elif not... | python | {
"resource": ""
} |
q273887 | cli_fordo | test | def cli_fordo(context, path=None):
"""
Issues commands for each item in an account or container listing.
See :py:mod:`swiftly.cli.fordo` for context usage information.
See :py:class:`CLIForDo` for more information.
"""
path = path.lstrip('/') if path else None
if path and '/' in path:
... | python | {
"resource": ""
} |
q273888 | ClientManager.get_client | test | def get_client(self):
"""
Obtains a client for use, whether an existing unused client
or a brand new one if none are available.
"""
client = None
try:
client = self.clients.get(block=False)
except queue.Empty:
pass
if not client:
... | python | {
"resource": ""
} |
q273889 | aes_encrypt | test | def aes_encrypt(key, stdin, preamble=None, chunk_size=65536,
content_length=None):
"""
Generator that encrypts a content stream using AES 256 in CBC
mode.
:param key: Any string to use as the encryption key.
:param stdin: Where to read the contents from.
:param preamble: str to ... | python | {
"resource": ""
} |
q273890 | aes_decrypt | test | def aes_decrypt(key, stdin, chunk_size=65536):
"""
Generator that decrypts a content stream using AES 256 in CBC
mode.
:param key: Any string to use as the decryption key.
:param stdin: Where to read the encrypted data from.
:param chunk_size: Largest amount to read at once.
"""
if not ... | python | {
"resource": ""
} |
q273891 | cli_put_directory_structure | test | def cli_put_directory_structure(context, path):
"""
Performs PUTs rooted at the path using a directory structure
pointed to by context.input\_.
See :py:mod:`swiftly.cli.put` for context usage information.
See :py:class:`CLIPut` for more information.
"""
if not context.input_:
raise... | python | {
"resource": ""
} |
q273892 | cli_put_account | test | def cli_put_account(context):
"""
Performs a PUT on the account.
See :py:mod:`swiftly.cli.put` for context usage information.
See :py:class:`CLIPut` for more information.
"""
body = None
if context.input_:
if context.input_ == '-':
body = context.io_manager.get_stdin()
... | python | {
"resource": ""
} |
q273893 | cli_put_container | test | def cli_put_container(context, path):
"""
Performs a PUT on the container.
See :py:mod:`swiftly.cli.put` for context usage information.
See :py:class:`CLIPut` for more information.
"""
path = path.rstrip('/')
if '/' in path:
raise ReturnCode('called cli_put_container with object %r... | python | {
"resource": ""
} |
q273894 | _get_manifest_body | test | def _get_manifest_body(context, prefix, path2info, put_headers):
"""
Returns body for manifest file and modifies put_headers.
path2info is a dict like {"path": (size, etag)}
"""
if context.static_segments:
body = json.dumps([
{'path': '/' + p, 'size_bytes': s, 'etag': e}
... | python | {
"resource": ""
} |
q273895 | _create_container | test | def _create_container(context, path, l_mtime, size):
"""
Creates container for segments of file with `path`
"""
new_context = context.copy()
new_context.input_ = None
new_context.headers = None
new_context.query = None
container = path.split('/', 1)[0] + '_segments'
cli_put_container... | python | {
"resource": ""
} |
q273896 | cli_tempurl | test | def cli_tempurl(context, method, path, seconds=None, use_container=False):
"""
Generates a TempURL and sends that to the context.io_manager's
stdout.
See :py:mod:`swiftly.cli.tempurl` for context usage information.
See :py:class:`CLITempURL` for more information.
:param context: The :py:class... | python | {
"resource": ""
} |
q273897 | cli_trans | test | def cli_trans(context, x_trans_id):
"""
Translates any information that can be determined from the
x_trans_id and sends that to the context.io_manager's stdout.
See :py:mod:`swiftly.cli.trans` for context usage information.
See :py:class:`CLITrans` for more information.
"""
with context.io... | python | {
"resource": ""
} |
q273898 | cli_help | test | def cli_help(context, command_name, general_parser, command_parsers):
"""
Outputs help information.
See :py:mod:`swiftly.cli.help` for context usage information.
See :py:class:`CLIHelp` for more information.
:param context: The :py:class:`swiftly.cli.context.CLIContext` to
use.
:param... | python | {
"resource": ""
} |
q273899 | FileLikeIter.is_empty | test | def is_empty(self):
"""
Check whether the "file" is empty reading the single byte.
"""
something = self.read(1)
if something:
if self.buf:
self.buf = something + self.buf
else:
self.buf = something
return False
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.