partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
start_capture
Start the capture process, creating all necessary files and directories as well as ingesting the captured files if no backup mode is configured.
pyca/capture.py
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.query(RecordedEvent)\ .filter(RecordedEvent.uid == upcoming_event.uid)\ .filter(RecordedEvent.start == upcoming_event.start)\ .first() if not event: event = RecordedEvent(upcoming_event) db.add(event) db.commit() try_mkdir(config()['capture']['directory']) os.mkdir(event.directory()) # Set state update_event_status(event, Status.RECORDING) recording_state(event.uid, 'capturing') set_service_status_immediate(Service.CAPTURE, ServiceStatus.BUSY) # Recording tracks = recording_command(event) event.set_tracks(tracks) db.commit() # Set status update_event_status(event, Status.FINISHED_RECORDING) recording_state(event.uid, 'capture_finished') set_service_status_immediate(Service.CAPTURE, ServiceStatus.IDLE) logger.info('Finished recording')
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.query(RecordedEvent)\ .filter(RecordedEvent.uid == upcoming_event.uid)\ .filter(RecordedEvent.start == upcoming_event.start)\ .first() if not event: event = RecordedEvent(upcoming_event) db.add(event) db.commit() try_mkdir(config()['capture']['directory']) os.mkdir(event.directory()) # Set state update_event_status(event, Status.RECORDING) recording_state(event.uid, 'capturing') set_service_status_immediate(Service.CAPTURE, ServiceStatus.BUSY) # Recording tracks = recording_command(event) event.set_tracks(tracks) db.commit() # Set status update_event_status(event, Status.FINISHED_RECORDING) recording_state(event.uid, 'capture_finished') set_service_status_immediate(Service.CAPTURE, ServiceStatus.IDLE) logger.info('Finished recording')
[ "Start", "the", "capture", "process", "creating", "all", "necessary", "files", "and", "directories", "as", "well", "as", "ingesting", "the", "captured", "files", "if", "no", "backup", "mode", "is", "configured", "." ]
opencast/pyCA
python
https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/capture.py#L41-L76
[ "def", "start_capture", "(", "upcoming_event", ")", ":", "logger", ".", "info", "(", "'Start recording'", ")", "# First move event to recording_event table", "db", "=", "get_session", "(", ")", "event", "=", "db", ".", "query", "(", "RecordedEvent", ")", ".", "filter", "(", "RecordedEvent", ".", "uid", "==", "upcoming_event", ".", "uid", ")", ".", "filter", "(", "RecordedEvent", ".", "start", "==", "upcoming_event", ".", "start", ")", ".", "first", "(", ")", "if", "not", "event", ":", "event", "=", "RecordedEvent", "(", "upcoming_event", ")", "db", ".", "add", "(", "event", ")", "db", ".", "commit", "(", ")", "try_mkdir", "(", "config", "(", ")", "[", "'capture'", "]", "[", "'directory'", "]", ")", "os", ".", "mkdir", "(", "event", ".", "directory", "(", ")", ")", "# Set state", "update_event_status", "(", "event", ",", "Status", ".", "RECORDING", ")", "recording_state", "(", "event", ".", "uid", ",", "'capturing'", ")", "set_service_status_immediate", "(", "Service", ".", "CAPTURE", ",", "ServiceStatus", ".", "BUSY", ")", "# Recording", "tracks", "=", "recording_command", "(", "event", ")", "event", ".", "set_tracks", "(", "tracks", ")", "db", ".", "commit", "(", ")", "# Set status", "update_event_status", "(", "event", ",", "Status", ".", "FINISHED_RECORDING", ")", "recording_state", "(", "event", ".", "uid", ",", "'capture_finished'", ")", "set_service_status_immediate", "(", "Service", ".", "CAPTURE", ",", "ServiceStatus", ".", "IDLE", ")", "logger", ".", "info", "(", "'Finished recording'", ")" ]
c89b168d4780d157e1b3f7676628c1b131956a88
test
safe_start_capture
Start a capture process but make sure to catch any errors during this process, log them but otherwise ignore them.
pyca/capture.py
def safe_start_capture(event): '''Start a capture process but make sure to catch any errors during this process, log them but otherwise ignore them. ''' try: start_capture(event) except Exception: logger.error('Recording failed') logger.error(traceback.format_exc()) # Update state recording_state(event.uid, 'capture_error') update_event_status(event, Status.FAILED_RECORDING) set_service_status_immediate(Service.CAPTURE, ServiceStatus.IDLE)
def safe_start_capture(event): '''Start a capture process but make sure to catch any errors during this process, log them but otherwise ignore them. ''' try: start_capture(event) except Exception: logger.error('Recording failed') logger.error(traceback.format_exc()) # Update state recording_state(event.uid, 'capture_error') update_event_status(event, Status.FAILED_RECORDING) set_service_status_immediate(Service.CAPTURE, ServiceStatus.IDLE)
[ "Start", "a", "capture", "process", "but", "make", "sure", "to", "catch", "any", "errors", "during", "this", "process", "log", "them", "but", "otherwise", "ignore", "them", "." ]
opencast/pyCA
python
https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/capture.py#L79-L91
[ "def", "safe_start_capture", "(", "event", ")", ":", "try", ":", "start_capture", "(", "event", ")", "except", "Exception", ":", "logger", ".", "error", "(", "'Recording failed'", ")", "logger", ".", "error", "(", "traceback", ".", "format_exc", "(", ")", ")", "# Update state", "recording_state", "(", "event", ".", "uid", ",", "'capture_error'", ")", "update_event_status", "(", "event", ",", "Status", ".", "FAILED_RECORDING", ")", "set_service_status_immediate", "(", "Service", ".", "CAPTURE", ",", "ServiceStatus", ".", "IDLE", ")" ]
c89b168d4780d157e1b3f7676628c1b131956a88
test
recording_command
Run the actual command to record the a/v material.
pyca/capture.py
def recording_command(event): '''Run the actual command to record the a/v material. ''' conf = config('capture') # Prepare command line cmd = conf['command'] cmd = cmd.replace('{{time}}', str(event.remaining_duration(timestamp()))) cmd = cmd.replace('{{dir}}', event.directory()) cmd = cmd.replace('{{name}}', event.name()) cmd = cmd.replace('{{previewdir}}', conf['preview_dir']) # Signal configuration sigterm_time = conf['sigterm_time'] sigkill_time = conf['sigkill_time'] sigcustom_time = conf['sigcustom_time'] sigcustom_time = 0 if sigcustom_time < 0 else event.end + sigcustom_time sigterm_time = 0 if sigterm_time < 0 else event.end + sigterm_time sigkill_time = 0 if sigkill_time < 0 else event.end + sigkill_time # Launch capture command logger.info(cmd) args = shlex.split(cmd) DEVNULL = getattr(subprocess, 'DEVNULL', os.open(os.devnull, os.O_RDWR)) captureproc = subprocess.Popen(args, stdin=DEVNULL) hasattr(subprocess, 'DEVNULL') or os.close(DEVNULL) # Set systemd status notify.notify('STATUS=Capturing') # Check process while captureproc.poll() is None: notify.notify('WATCHDOG=1') if sigcustom_time and timestamp() > sigcustom_time: logger.info("Sending custom signal to capture process") captureproc.send_signal(conf['sigcustom']) sigcustom_time = 0 # send only once if sigterm_time and timestamp() > sigterm_time: logger.info("Terminating capture process") captureproc.terminate() sigterm_time = 0 # send only once elif sigkill_time and timestamp() > sigkill_time: logger.warning("Killing capture process") captureproc.kill() sigkill_time = 0 # send only once time.sleep(0.1) # Remove preview files: for preview in conf['preview']: try: os.remove(preview.replace('{{previewdir}}', conf['preview_dir'])) except OSError: logger.warning('Could not remove preview files') logger.warning(traceback.format_exc()) # Check process for errors exitcode = config()['capture']['exit_code'] if captureproc.poll() > 0 and captureproc.returncode != exitcode: raise RuntimeError('Recording failed (%i)' % captureproc.returncode) # Reset systemd status notify.notify('STATUS=Waiting') # Return [(flavor,path),…] files = (f.replace('{{dir}}', event.directory()) for f in conf['files']) files = (f.replace('{{name}}', event.name()) for f in files) return list(zip(conf['flavors'], files))
def recording_command(event): '''Run the actual command to record the a/v material. ''' conf = config('capture') # Prepare command line cmd = conf['command'] cmd = cmd.replace('{{time}}', str(event.remaining_duration(timestamp()))) cmd = cmd.replace('{{dir}}', event.directory()) cmd = cmd.replace('{{name}}', event.name()) cmd = cmd.replace('{{previewdir}}', conf['preview_dir']) # Signal configuration sigterm_time = conf['sigterm_time'] sigkill_time = conf['sigkill_time'] sigcustom_time = conf['sigcustom_time'] sigcustom_time = 0 if sigcustom_time < 0 else event.end + sigcustom_time sigterm_time = 0 if sigterm_time < 0 else event.end + sigterm_time sigkill_time = 0 if sigkill_time < 0 else event.end + sigkill_time # Launch capture command logger.info(cmd) args = shlex.split(cmd) DEVNULL = getattr(subprocess, 'DEVNULL', os.open(os.devnull, os.O_RDWR)) captureproc = subprocess.Popen(args, stdin=DEVNULL) hasattr(subprocess, 'DEVNULL') or os.close(DEVNULL) # Set systemd status notify.notify('STATUS=Capturing') # Check process while captureproc.poll() is None: notify.notify('WATCHDOG=1') if sigcustom_time and timestamp() > sigcustom_time: logger.info("Sending custom signal to capture process") captureproc.send_signal(conf['sigcustom']) sigcustom_time = 0 # send only once if sigterm_time and timestamp() > sigterm_time: logger.info("Terminating capture process") captureproc.terminate() sigterm_time = 0 # send only once elif sigkill_time and timestamp() > sigkill_time: logger.warning("Killing capture process") captureproc.kill() sigkill_time = 0 # send only once time.sleep(0.1) # Remove preview files: for preview in conf['preview']: try: os.remove(preview.replace('{{previewdir}}', conf['preview_dir'])) except OSError: logger.warning('Could not remove preview files') logger.warning(traceback.format_exc()) # Check process for errors exitcode = config()['capture']['exit_code'] if captureproc.poll() > 0 and captureproc.returncode != exitcode: raise RuntimeError('Recording failed (%i)' % captureproc.returncode) # Reset systemd status notify.notify('STATUS=Waiting') # Return [(flavor,path),…] files = (f.replace('{{dir}}', event.directory()) for f in conf['files']) files = (f.replace('{{name}}', event.name()) for f in files) return list(zip(conf['flavors'], files))
[ "Run", "the", "actual", "command", "to", "record", "the", "a", "/", "v", "material", "." ]
opencast/pyCA
python
https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/capture.py#L94-L159
[ "def", "recording_command", "(", "event", ")", ":", "conf", "=", "config", "(", "'capture'", ")", "# Prepare command line", "cmd", "=", "conf", "[", "'command'", "]", "cmd", "=", "cmd", ".", "replace", "(", "'{{time}}'", ",", "str", "(", "event", ".", "remaining_duration", "(", "timestamp", "(", ")", ")", ")", ")", "cmd", "=", "cmd", ".", "replace", "(", "'{{dir}}'", ",", "event", ".", "directory", "(", ")", ")", "cmd", "=", "cmd", ".", "replace", "(", "'{{name}}'", ",", "event", ".", "name", "(", ")", ")", "cmd", "=", "cmd", ".", "replace", "(", "'{{previewdir}}'", ",", "conf", "[", "'preview_dir'", "]", ")", "# Signal configuration", "sigterm_time", "=", "conf", "[", "'sigterm_time'", "]", "sigkill_time", "=", "conf", "[", "'sigkill_time'", "]", "sigcustom_time", "=", "conf", "[", "'sigcustom_time'", "]", "sigcustom_time", "=", "0", "if", "sigcustom_time", "<", "0", "else", "event", ".", "end", "+", "sigcustom_time", "sigterm_time", "=", "0", "if", "sigterm_time", "<", "0", "else", "event", ".", "end", "+", "sigterm_time", "sigkill_time", "=", "0", "if", "sigkill_time", "<", "0", "else", "event", ".", "end", "+", "sigkill_time", "# Launch capture command", "logger", ".", "info", "(", "cmd", ")", "args", "=", "shlex", ".", "split", "(", "cmd", ")", "DEVNULL", "=", "getattr", "(", "subprocess", ",", "'DEVNULL'", ",", "os", ".", "open", "(", "os", ".", "devnull", ",", "os", ".", "O_RDWR", ")", ")", "captureproc", "=", "subprocess", ".", "Popen", "(", "args", ",", "stdin", "=", "DEVNULL", ")", "hasattr", "(", "subprocess", ",", "'DEVNULL'", ")", "or", "os", ".", "close", "(", "DEVNULL", ")", "# Set systemd status", "notify", ".", "notify", "(", "'STATUS=Capturing'", ")", "# Check process", "while", "captureproc", ".", "poll", "(", ")", "is", "None", ":", "notify", ".", "notify", "(", "'WATCHDOG=1'", ")", "if", "sigcustom_time", "and", "timestamp", "(", ")", ">", "sigcustom_time", ":", "logger", ".", "info", "(", "\"Sending custom signal to capture process\"", ")", "captureproc", ".", "send_signal", "(", "conf", "[", "'sigcustom'", "]", ")", "sigcustom_time", "=", "0", "# send only once", "if", "sigterm_time", "and", "timestamp", "(", ")", ">", "sigterm_time", ":", "logger", ".", "info", "(", "\"Terminating capture process\"", ")", "captureproc", ".", "terminate", "(", ")", "sigterm_time", "=", "0", "# send only once", "elif", "sigkill_time", "and", "timestamp", "(", ")", ">", "sigkill_time", ":", "logger", ".", "warning", "(", "\"Killing capture process\"", ")", "captureproc", ".", "kill", "(", ")", "sigkill_time", "=", "0", "# send only once", "time", ".", "sleep", "(", "0.1", ")", "# Remove preview files:", "for", "preview", "in", "conf", "[", "'preview'", "]", ":", "try", ":", "os", ".", "remove", "(", "preview", ".", "replace", "(", "'{{previewdir}}'", ",", "conf", "[", "'preview_dir'", "]", ")", ")", "except", "OSError", ":", "logger", ".", "warning", "(", "'Could not remove preview files'", ")", "logger", ".", "warning", "(", "traceback", ".", "format_exc", "(", ")", ")", "# Check process for errors", "exitcode", "=", "config", "(", ")", "[", "'capture'", "]", "[", "'exit_code'", "]", "if", "captureproc", ".", "poll", "(", ")", ">", "0", "and", "captureproc", ".", "returncode", "!=", "exitcode", ":", "raise", "RuntimeError", "(", "'Recording failed (%i)'", "%", "captureproc", ".", "returncode", ")", "# Reset systemd status", "notify", ".", "notify", "(", "'STATUS=Waiting'", ")", "# Return [(flavor,path),…]", "files", "=", "(", "f", ".", "replace", "(", "'{{dir}}'", ",", "event", ".", "directory", "(", ")", ")", "for", "f", "in", "conf", "[", "'files'", "]", ")", "files", "=", "(", "f", ".", "replace", "(", "'{{name}}'", ",", "event", ".", "name", "(", ")", ")", "for", "f", "in", "files", ")", "return", "list", "(", "zip", "(", "conf", "[", "'flavors'", "]", ",", "files", ")", ")" ]
c89b168d4780d157e1b3f7676628c1b131956a88
test
control_loop
Main loop of the capture agent, retrieving and checking the schedule as well as starting the capture process if necessry.
pyca/capture.py
def control_loop(): '''Main loop of the capture agent, retrieving and checking the schedule as well as starting the capture process if necessry. ''' set_service_status(Service.CAPTURE, ServiceStatus.IDLE) notify.notify('READY=1') notify.notify('STATUS=Waiting') while not terminate(): notify.notify('WATCHDOG=1') # Get next recording event = get_session().query(UpcomingEvent)\ .filter(UpcomingEvent.start <= timestamp())\ .filter(UpcomingEvent.end > timestamp())\ .first() if event: safe_start_capture(event) time.sleep(1.0) logger.info('Shutting down capture service') set_service_status(Service.CAPTURE, ServiceStatus.STOPPED)
def control_loop(): '''Main loop of the capture agent, retrieving and checking the schedule as well as starting the capture process if necessry. ''' set_service_status(Service.CAPTURE, ServiceStatus.IDLE) notify.notify('READY=1') notify.notify('STATUS=Waiting') while not terminate(): notify.notify('WATCHDOG=1') # Get next recording event = get_session().query(UpcomingEvent)\ .filter(UpcomingEvent.start <= timestamp())\ .filter(UpcomingEvent.end > timestamp())\ .first() if event: safe_start_capture(event) time.sleep(1.0) logger.info('Shutting down capture service') set_service_status(Service.CAPTURE, ServiceStatus.STOPPED)
[ "Main", "loop", "of", "the", "capture", "agent", "retrieving", "and", "checking", "the", "schedule", "as", "well", "as", "starting", "the", "capture", "process", "if", "necessry", "." ]
opencast/pyCA
python
https://github.com/opencast/pyCA/blob/c89b168d4780d157e1b3f7676628c1b131956a88/pyca/capture.py#L162-L180
[ "def", "control_loop", "(", ")", ":", "set_service_status", "(", "Service", ".", "CAPTURE", ",", "ServiceStatus", ".", "IDLE", ")", "notify", ".", "notify", "(", "'READY=1'", ")", "notify", ".", "notify", "(", "'STATUS=Waiting'", ")", "while", "not", "terminate", "(", ")", ":", "notify", ".", "notify", "(", "'WATCHDOG=1'", ")", "# Get next recording", "event", "=", "get_session", "(", ")", ".", "query", "(", "UpcomingEvent", ")", ".", "filter", "(", "UpcomingEvent", ".", "start", "<=", "timestamp", "(", ")", ")", ".", "filter", "(", "UpcomingEvent", ".", "end", ">", "timestamp", "(", ")", ")", ".", "first", "(", ")", "if", "event", ":", "safe_start_capture", "(", "event", ")", "time", ".", "sleep", "(", "1.0", ")", "logger", ".", "info", "(", "'Shutting down capture service'", ")", "set_service_status", "(", "Service", ".", "CAPTURE", ",", "ServiceStatus", ".", "STOPPED", ")" ]
c89b168d4780d157e1b3f7676628c1b131956a88
test
ExampleFragmentView.render_to_fragment
Returns a simple fragment
web_fragments/examples/views.py
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
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
[ "Returns", "a", "simple", "fragment" ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/examples/views.py#L22-L29
[ "def", "render_to_fragment", "(", "self", ",", "request", ",", "*", "*", "kwargs", ")", ":", "fragment", "=", "Fragment", "(", "TEST_HTML", ")", "fragment", ".", "add_javascript", "(", "TEST_JS", ")", "fragment", ".", "add_css", "(", "TEST_CSS", ")", "return", "fragment" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.resources
Returns list of unique `FragmentResource`s by order of first appearance.
web_fragments/fragment.py
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' short-circuits) return [x for x in self._resources if x not in seen and not seen.add(x)]
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' short-circuits) return [x for x in self._resources if x not in seen and not seen.add(x)]
[ "Returns", "list", "of", "unique", "FragmentResource", "s", "by", "order", "of", "first", "appearance", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L44-L52
[ "def", "resources", "(", "self", ")", ":", "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' short-circuits)", "return", "[", "x", "for", "x", "in", "self", ".", "_resources", "if", "x", "not", "in", "seen", "and", "not", "seen", ".", "add", "(", "x", ")", "]" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.to_dict
Returns the fragment in a dictionary representation.
web_fragments/fragment.py
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': self.js_init_version, 'json_init_args': self.json_init_args }
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': self.js_init_version, 'json_init_args': self.json_init_args }
[ "Returns", "the", "fragment", "in", "a", "dictionary", "representation", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L54-L64
[ "def", "to_dict", "(", "self", ")", ":", "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'", ":", "self", ".", "js_init_version", ",", "'json_init_args'", ":", "self", ".", "json_init_args", "}" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.from_dict
Returns a new Fragment from a dictionary representation.
web_fragments/fragment.py
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['js_init_fn'] frag.js_init_version = pods['js_init_version'] frag.json_init_args = pods['json_init_args'] return frag
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['js_init_fn'] frag.js_init_version = pods['js_init_version'] frag.json_init_args = pods['json_init_args'] return frag
[ "Returns", "a", "new", "Fragment", "from", "a", "dictionary", "representation", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L67-L77
[ "def", "from_dict", "(", "cls", ",", "pods", ")", ":", "frag", "=", "cls", "(", ")", "frag", ".", "content", "=", "pods", "[", "'content'", "]", "frag", ".", "_resources", "=", "[", "FragmentResource", "(", "*", "*", "d", ")", "for", "d", "in", "pods", "[", "'resources'", "]", "]", "# pylint: disable=protected-access", "frag", ".", "js_init_fn", "=", "pods", "[", "'js_init_fn'", "]", "frag", ".", "js_init_version", "=", "pods", "[", "'js_init_version'", "]", "frag", ".", "json_init_args", "=", "pods", "[", "'json_init_args'", "]", "return", "frag" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.add_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.
web_fragments/fragment.py
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(content, six.text_type) self.content += content
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(content, six.text_type) self.content += content
[ "Add", "content", "to", "this", "fragment", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L79-L88
[ "def", "add_content", "(", "self", ",", "content", ")", ":", "assert", "isinstance", "(", "content", ",", "six", ".", "text_type", ")", "self", ".", "content", "+=", "content" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.add_resource
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 string. `mimetype`: the MIME type of the resource. `placement`: where on the page the resource should be placed: None: let the Fragment choose based on the MIME type. "head": put this resource in the ``<head>`` of the page. "foot": put this resource at the end of the ``<body>`` of the page.
web_fragments/fragment.py
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 string. `mimetype`: the MIME type of the resource. `placement`: where on the page the resource should be placed: None: let the Fragment choose based on the MIME type. "head": put this resource in the ``<head>`` of the page. "foot": put this resource at the end of the ``<body>`` of the page. """ if not placement: placement = self._default_placement(mimetype) res = FragmentResource('text', text, mimetype, placement) self._resources.append(res)
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 string. `mimetype`: the MIME type of the resource. `placement`: where on the page the resource should be placed: None: let the Fragment choose based on the MIME type. "head": put this resource in the ``<head>`` of the page. "foot": put this resource at the end of the ``<body>`` of the page. """ if not placement: placement = self._default_placement(mimetype) res = FragmentResource('text', text, mimetype, placement) self._resources.append(res)
[ "Add", "a", "resource", "needed", "by", "this", "Fragment", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L98-L122
[ "def", "add_resource", "(", "self", ",", "text", ",", "mimetype", ",", "placement", "=", "None", ")", ":", "if", "not", "placement", ":", "placement", "=", "self", ".", "_default_placement", "(", "mimetype", ")", "res", "=", "FragmentResource", "(", "'text'", ",", "text", ",", "mimetype", ",", "placement", ")", "self", ".", "_resources", ".", "append", "(", "res", ")" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.add_resource_url
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. Other parameters are as defined for :func:`add_resource`.
web_fragments/fragment.py
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. Other parameters are as defined for :func:`add_resource`. """ if not placement: placement = self._default_placement(mimetype) self._resources.append(FragmentResource('url', url, mimetype, placement))
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. Other parameters are as defined for :func:`add_resource`. """ if not placement: placement = self._default_placement(mimetype) self._resources.append(FragmentResource('url', url, mimetype, placement))
[ "Add", "a", "resource", "by", "URL", "needed", "by", "this", "Fragment", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L124-L138
[ "def", "add_resource_url", "(", "self", ",", "url", ",", "mimetype", ",", "placement", "=", "None", ")", ":", "if", "not", "placement", ":", "placement", "=", "self", ".", "_default_placement", "(", "mimetype", ")", "self", ".", "_resources", ".", "append", "(", "FragmentResource", "(", "'url'", ",", "url", ",", "mimetype", ",", "placement", ")", ")" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.initialize_js
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 function will be invoked, passing a runtime object and a DOM element.
web_fragments/fragment.py
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 function will be invoked, passing a runtime object and a DOM element. """ self.js_init_fn = js_func self.js_init_version = JS_API_VERSION if json_args: self.json_init_args = json_args
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 function will be invoked, passing a runtime object and a DOM element. """ self.js_init_fn = js_func self.js_init_version = JS_API_VERSION if json_args: self.json_init_args = json_args
[ "Register", "a", "Javascript", "function", "to", "initialize", "the", "Javascript", "resources", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L189-L201
[ "def", "initialize_js", "(", "self", ",", "js_func", ",", "json_args", "=", "None", ")", ":", "self", ".", "js_init_fn", "=", "js_func", "self", ".", "js_init_version", "=", "JS_API_VERSION", "if", "json_args", ":", "self", ".", "json_init_args", "=", "json_args" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.resources_to_html
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.
web_fragments/fragment.py
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 css could be rewritten to match the wrapper tag return '\n'.join( self.resource_to_html(resource) for resource in self.resources if resource.placement == placement )
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 css could be rewritten to match the wrapper tag return '\n'.join( self.resource_to_html(resource) for resource in self.resources if resource.placement == placement )
[ "Get", "some", "resource", "HTML", "for", "this", "Fragment", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L230-L245
[ "def", "resources_to_html", "(", "self", ",", "placement", ")", ":", "# - non url js could be wrapped in an anonymous function", "# - non url css could be rewritten to match the wrapper tag", "return", "'\\n'", ".", "join", "(", "self", ".", "resource_to_html", "(", "resource", ")", "for", "resource", "in", "self", ".", "resources", "if", "resource", ".", "placement", "==", "placement", ")" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
Fragment.resource_to_html
Returns `resource` wrapped in the appropriate html tag for it's mimetype.
web_fragments/fragment.py
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 resource.kind == "url": return u"<link rel='stylesheet' href='%s' type='text/css'>" % resource.data else: raise Exception("Unrecognized resource kind %r" % resource.kind) elif resource.mimetype == "application/javascript": if resource.kind == "text": return u"<script>\n%s\n</script>" % resource.data elif resource.kind == "url": return u"<script src='%s' type='application/javascript'></script>" % resource.data else: raise Exception("Unrecognized resource kind %r" % resource.kind) elif resource.mimetype == "text/html": assert resource.kind == "text" return resource.data else: raise Exception("Unrecognized mimetype %r" % resource.mimetype)
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 resource.kind == "url": return u"<link rel='stylesheet' href='%s' type='text/css'>" % resource.data else: raise Exception("Unrecognized resource kind %r" % resource.kind) elif resource.mimetype == "application/javascript": if resource.kind == "text": return u"<script>\n%s\n</script>" % resource.data elif resource.kind == "url": return u"<script src='%s' type='application/javascript'></script>" % resource.data else: raise Exception("Unrecognized resource kind %r" % resource.kind) elif resource.mimetype == "text/html": assert resource.kind == "text" return resource.data else: raise Exception("Unrecognized mimetype %r" % resource.mimetype)
[ "Returns", "resource", "wrapped", "in", "the", "appropriate", "html", "tag", "for", "it", "s", "mimetype", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/fragment.py#L248-L273
[ "def", "resource_to_html", "(", "resource", ")", ":", "if", "resource", ".", "mimetype", "==", "\"text/css\"", ":", "if", "resource", ".", "kind", "==", "\"text\"", ":", "return", "u\"<style type='text/css'>\\n%s\\n</style>\"", "%", "resource", ".", "data", "elif", "resource", ".", "kind", "==", "\"url\"", ":", "return", "u\"<link rel='stylesheet' href='%s' type='text/css'>\"", "%", "resource", ".", "data", "else", ":", "raise", "Exception", "(", "\"Unrecognized resource kind %r\"", "%", "resource", ".", "kind", ")", "elif", "resource", ".", "mimetype", "==", "\"application/javascript\"", ":", "if", "resource", ".", "kind", "==", "\"text\"", ":", "return", "u\"<script>\\n%s\\n</script>\"", "%", "resource", ".", "data", "elif", "resource", ".", "kind", "==", "\"url\"", ":", "return", "u\"<script src='%s' type='application/javascript'></script>\"", "%", "resource", ".", "data", "else", ":", "raise", "Exception", "(", "\"Unrecognized resource kind %r\"", "%", "resource", ".", "kind", ")", "elif", "resource", ".", "mimetype", "==", "\"text/html\"", ":", "assert", "resource", ".", "kind", "==", "\"text\"", "return", "resource", ".", "data", "else", ":", "raise", "Exception", "(", "\"Unrecognized mimetype %r\"", "%", "resource", ".", "mimetype", ")" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
FragmentView.get
Render a fragment to HTML or return JSON describing it, based on the request.
web_fragments/views.py
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 response_format == 'json' or WEB_FRAGMENT_RESPONSE_TYPE in request.META.get('HTTP_ACCEPT', 'text/html'): return JsonResponse(fragment.to_dict()) else: return self.render_standalone_response(request, fragment, **kwargs)
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 response_format == 'json' or WEB_FRAGMENT_RESPONSE_TYPE in request.META.get('HTTP_ACCEPT', 'text/html'): return JsonResponse(fragment.to_dict()) else: return self.render_standalone_response(request, fragment, **kwargs)
[ "Render", "a", "fragment", "to", "HTML", "or", "return", "JSON", "describing", "it", "based", "on", "the", "request", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/views.py#L21-L30
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "fragment", "=", "self", ".", "render_to_fragment", "(", "request", ",", "*", "*", "kwargs", ")", "response_format", "=", "request", ".", "GET", ".", "get", "(", "'format'", ")", "or", "request", ".", "POST", ".", "get", "(", "'format'", ")", "or", "'html'", "if", "response_format", "==", "'json'", "or", "WEB_FRAGMENT_RESPONSE_TYPE", "in", "request", ".", "META", ".", "get", "(", "'HTTP_ACCEPT'", ",", "'text/html'", ")", ":", "return", "JsonResponse", "(", "fragment", ".", "to_dict", "(", ")", ")", "else", ":", "return", "self", ".", "render_standalone_response", "(", "request", ",", "fragment", ",", "*", "*", "kwargs", ")" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
FragmentView.render_standalone_response
Renders a standalone page as a response for the specified fragment.
web_fragments/views.py
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_html(request, fragment, **kwargs) return HttpResponse(html)
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_html(request, fragment, **kwargs) return HttpResponse(html)
[ "Renders", "a", "standalone", "page", "as", "a", "response", "for", "the", "specified", "fragment", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/views.py#L32-L40
[ "def", "render_standalone_response", "(", "self", ",", "request", ",", "fragment", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "fragment", "is", "None", ":", "return", "HttpResponse", "(", "status", "=", "204", ")", "html", "=", "self", ".", "render_to_standalone_html", "(", "request", ",", "fragment", ",", "*", "*", "kwargs", ")", "return", "HttpResponse", "(", "html", ")" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
FragmentView.render_to_standalone_html
Render the specified fragment to HTML for a standalone page.
web_fragments/views.py
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(), 'body_html': fragment.body_html(), 'foot_html': fragment.foot_html(), } return template.render(context)
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(), 'body_html': fragment.body_html(), 'foot_html': fragment.foot_html(), } return template.render(context)
[ "Render", "the", "specified", "fragment", "to", "HTML", "for", "a", "standalone", "page", "." ]
edx/web-fragments
python
https://github.com/edx/web-fragments/blob/42d760d700d70465e4e573b7b41442d8802ccd3c/web_fragments/views.py#L42-L52
[ "def", "render_to_standalone_html", "(", "self", ",", "request", ",", "fragment", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "template", "=", "get_template", "(", "STANDALONE_TEMPLATE_NAME", ")", "context", "=", "{", "'head_html'", ":", "fragment", ".", "head_html", "(", ")", ",", "'body_html'", ":", "fragment", ".", "body_html", "(", ")", ",", "'foot_html'", ":", "fragment", ".", "foot_html", "(", ")", ",", "}", "return", "template", ".", "render", "(", "context", ")" ]
42d760d700d70465e4e573b7b41442d8802ccd3c
test
calc
meaning pvalues presorted i descending order
sandbox/compare.py
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] = (pi0 * y) / (Pr * (1 - math.pow(1-y, m))) print(i, pFDR[i], y, Pr, 1.0 - math.pow(1-y, m)) num_null = pi0*m num_alt = m - num_null num_negs = np.array(range(m)) num_pos = m - num_negs pp = num_pos / float(m) qvalues = np.ones(m) qvalues[0] = pFDR[0] for i in range(m-1): qvalues[i+1] = min(qvalues[i], pFDR[i+1]) sens = ((1.0 - qvalues) * num_pos) / num_alt sens[sens > 1.0] = 1.0 df = pd.DataFrame(dict( pvalue=pvalues, qvalue=qvalues, FDR=pFDR, percentile_positive=pp, sens=sens )) df["svalue"] = df.sens[::-1].cummax()[::-1] return df, num_null, m
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] = (pi0 * y) / (Pr * (1 - math.pow(1-y, m))) print(i, pFDR[i], y, Pr, 1.0 - math.pow(1-y, m)) num_null = pi0*m num_alt = m - num_null num_negs = np.array(range(m)) num_pos = m - num_negs pp = num_pos / float(m) qvalues = np.ones(m) qvalues[0] = pFDR[0] for i in range(m-1): qvalues[i+1] = min(qvalues[i], pFDR[i+1]) sens = ((1.0 - qvalues) * num_pos) / num_alt sens[sens > 1.0] = 1.0 df = pd.DataFrame(dict( pvalue=pvalues, qvalue=qvalues, FDR=pFDR, percentile_positive=pp, sens=sens )) df["svalue"] = df.sens[::-1].cummax()[::-1] return df, num_null, m
[ "meaning", "pvalues", "presorted", "i", "descending", "order" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/sandbox/compare.py#L20-L59
[ "def", "calc", "(", "pvalues", ",", "lamb", ")", ":", "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", "]", "=", "(", "pi0", "*", "y", ")", "/", "(", "Pr", "*", "(", "1", "-", "math", ".", "pow", "(", "1", "-", "y", ",", "m", ")", ")", ")", "print", "(", "i", ",", "pFDR", "[", "i", "]", ",", "y", ",", "Pr", ",", "1.0", "-", "math", ".", "pow", "(", "1", "-", "y", ",", "m", ")", ")", "num_null", "=", "pi0", "*", "m", "num_alt", "=", "m", "-", "num_null", "num_negs", "=", "np", ".", "array", "(", "range", "(", "m", ")", ")", "num_pos", "=", "m", "-", "num_negs", "pp", "=", "num_pos", "/", "float", "(", "m", ")", "qvalues", "=", "np", ".", "ones", "(", "m", ")", "qvalues", "[", "0", "]", "=", "pFDR", "[", "0", "]", "for", "i", "in", "range", "(", "m", "-", "1", ")", ":", "qvalues", "[", "i", "+", "1", "]", "=", "min", "(", "qvalues", "[", "i", "]", ",", "pFDR", "[", "i", "+", "1", "]", ")", "sens", "=", "(", "(", "1.0", "-", "qvalues", ")", "*", "num_pos", ")", "/", "num_alt", "sens", "[", "sens", ">", "1.0", "]", "=", "1.0", "df", "=", "pd", ".", "DataFrame", "(", "dict", "(", "pvalue", "=", "pvalues", ",", "qvalue", "=", "qvalues", ",", "FDR", "=", "pFDR", ",", "percentile_positive", "=", "pp", ",", "sens", "=", "sens", ")", ")", "df", "[", "\"svalue\"", "]", "=", "df", ".", "sens", "[", ":", ":", "-", "1", "]", ".", "cummax", "(", ")", "[", ":", ":", "-", "1", "]", "return", "df", ",", "num_null", ",", "m" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
unwrap_self_for_multiprocessing
You can not call methods with multiprocessing, but free functions, If you want to call inst.method(arg0, arg1), unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1)) does the trick.
pyprophet/pyprophet.py
def unwrap_self_for_multiprocessing(arg): """ You can not call methods with multiprocessing, but free functions, If you want to call inst.method(arg0, arg1), unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1)) does the trick. """ (inst, method_name, args) = arg return getattr(inst, method_name)(*args)
def unwrap_self_for_multiprocessing(arg): """ You can not call methods with multiprocessing, but free functions, If you want to call inst.method(arg0, arg1), unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1)) does the trick. """ (inst, method_name, args) = arg return getattr(inst, method_name)(*args)
[ "You", "can", "not", "call", "methods", "with", "multiprocessing", "but", "free", "functions", "If", "you", "want", "to", "call", "inst", ".", "method", "(", "arg0", "arg1", ")" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/pyprophet.py#L49-L58
[ "def", "unwrap_self_for_multiprocessing", "(", "arg", ")", ":", "(", "inst", ",", "method_name", ",", "args", ")", "=", "arg", "return", "getattr", "(", "inst", ",", "method_name", ")", "(", "*", "args", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
to_one_dim_array
Converts list or flattens n-dim array to 1-dim array if possible
pyprophet/stats.py
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() assert values.ndim == 1, "values has wrong dimension" if as_type is not None: return values.astype(as_type) return values
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() assert values.ndim == 1, "values has wrong dimension" if as_type is not None: return values.astype(as_type) return values
[ "Converts", "list", "or", "flattens", "n", "-", "dim", "array", "to", "1", "-", "dim", "array", "if", "possible" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L41-L52
[ "def", "to_one_dim_array", "(", "values", ",", "as_type", "=", "None", ")", ":", "if", "isinstance", "(", "values", ",", "(", "list", ",", "tuple", ")", ")", ":", "values", "=", "np", ".", "array", "(", "values", ",", "dtype", "=", "np", ".", "float32", ")", "elif", "isinstance", "(", "values", ",", "pd", ".", "Series", ")", ":", "values", "=", "values", ".", "values", "values", "=", "values", ".", "flatten", "(", ")", "assert", "values", ".", "ndim", "==", "1", ",", "\"values has wrong dimension\"", "if", "as_type", "is", "not", "None", ":", "return", "values", ".", "astype", "(", "as_type", ")", "return", "values" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
lookup_values_from_error_table
Find matching q-value for each score in 'scores'
pyprophet/stats.py
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].values
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].values
[ "Find", "matching", "q", "-", "value", "for", "each", "score", "in", "scores" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L56-L59
[ "def", "lookup_values_from_error_table", "(", "scores", ",", "err_df", ")", ":", "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", "]", ".", "values" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
posterior_chromatogram_hypotheses_fast
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 computed. The prior probability that the are given in the function This assumes that the input data is sorted by tg_num_id Args: experiment(:class:`data_handling.Multipeptide`): the data of one experiment prior_chrom_null(float): the prior probability that any precursor is absent (all peaks are false) Returns: tuple(hypothesis, h0): two vectors that contain for each entry in the input dataframe the probabilities for the hypothesis that the peak is correct and the probability for the h0
pyprophet/stats.py
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 computed. The prior probability that the are given in the function This assumes that the input data is sorted by tg_num_id Args: experiment(:class:`data_handling.Multipeptide`): the data of one experiment prior_chrom_null(float): the prior probability that any precursor is absent (all peaks are false) Returns: tuple(hypothesis, h0): two vectors that contain for each entry in the input dataframe the probabilities for the hypothesis that the peak is correct and the probability for the h0 """ tg_ids = experiment.df.tg_num_id.values pp_values = 1-experiment.df["pep"].values current_tg_id = tg_ids[0] scores = [] final_result = [] final_result_h0 = [] for i in range(tg_ids.shape[0]): id_ = tg_ids[i] if id_ != current_tg_id: # Actual computation for a single transition group (chromatogram) prior_pg_true = (1.0 - prior_chrom_null) / len(scores) rr = single_chromatogram_hypothesis_fast( np.array(scores), prior_chrom_null, prior_pg_true) final_result.extend(rr[1:]) final_result_h0.extend(rr[0] for i in range(len(scores))) # Reset for next cycle scores = [] current_tg_id = id_ scores.append(1.0 - pp_values[i]) # Last cycle prior_pg_true = (1.0 - prior_chrom_null) / len(scores) rr = single_chromatogram_hypothesis_fast(np.array(scores), prior_chrom_null, prior_pg_true) final_result.extend(rr[1:]) final_result_h0.extend([rr[0]] * len(scores)) return final_result, final_result_h0
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 computed. The prior probability that the are given in the function This assumes that the input data is sorted by tg_num_id Args: experiment(:class:`data_handling.Multipeptide`): the data of one experiment prior_chrom_null(float): the prior probability that any precursor is absent (all peaks are false) Returns: tuple(hypothesis, h0): two vectors that contain for each entry in the input dataframe the probabilities for the hypothesis that the peak is correct and the probability for the h0 """ tg_ids = experiment.df.tg_num_id.values pp_values = 1-experiment.df["pep"].values current_tg_id = tg_ids[0] scores = [] final_result = [] final_result_h0 = [] for i in range(tg_ids.shape[0]): id_ = tg_ids[i] if id_ != current_tg_id: # Actual computation for a single transition group (chromatogram) prior_pg_true = (1.0 - prior_chrom_null) / len(scores) rr = single_chromatogram_hypothesis_fast( np.array(scores), prior_chrom_null, prior_pg_true) final_result.extend(rr[1:]) final_result_h0.extend(rr[0] for i in range(len(scores))) # Reset for next cycle scores = [] current_tg_id = id_ scores.append(1.0 - pp_values[i]) # Last cycle prior_pg_true = (1.0 - prior_chrom_null) / len(scores) rr = single_chromatogram_hypothesis_fast(np.array(scores), prior_chrom_null, prior_pg_true) final_result.extend(rr[1:]) final_result_h0.extend([rr[0]] * len(scores)) return final_result, final_result_h0
[ "Compute", "posterior", "probabilities", "for", "each", "chromatogram" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L62-L115
[ "def", "posterior_chromatogram_hypotheses_fast", "(", "experiment", ",", "prior_chrom_null", ")", ":", "tg_ids", "=", "experiment", ".", "df", ".", "tg_num_id", ".", "values", "pp_values", "=", "1", "-", "experiment", ".", "df", "[", "\"pep\"", "]", ".", "values", "current_tg_id", "=", "tg_ids", "[", "0", "]", "scores", "=", "[", "]", "final_result", "=", "[", "]", "final_result_h0", "=", "[", "]", "for", "i", "in", "range", "(", "tg_ids", ".", "shape", "[", "0", "]", ")", ":", "id_", "=", "tg_ids", "[", "i", "]", "if", "id_", "!=", "current_tg_id", ":", "# Actual computation for a single transition group (chromatogram)", "prior_pg_true", "=", "(", "1.0", "-", "prior_chrom_null", ")", "/", "len", "(", "scores", ")", "rr", "=", "single_chromatogram_hypothesis_fast", "(", "np", ".", "array", "(", "scores", ")", ",", "prior_chrom_null", ",", "prior_pg_true", ")", "final_result", ".", "extend", "(", "rr", "[", "1", ":", "]", ")", "final_result_h0", ".", "extend", "(", "rr", "[", "0", "]", "for", "i", "in", "range", "(", "len", "(", "scores", ")", ")", ")", "# Reset for next cycle", "scores", "=", "[", "]", "current_tg_id", "=", "id_", "scores", ".", "append", "(", "1.0", "-", "pp_values", "[", "i", "]", ")", "# Last cycle", "prior_pg_true", "=", "(", "1.0", "-", "prior_chrom_null", ")", "/", "len", "(", "scores", ")", "rr", "=", "single_chromatogram_hypothesis_fast", "(", "np", ".", "array", "(", "scores", ")", ",", "prior_chrom_null", ",", "prior_pg_true", ")", "final_result", ".", "extend", "(", "rr", "[", "1", ":", "]", ")", "final_result_h0", ".", "extend", "(", "[", "rr", "[", "0", "]", "]", "*", "len", "(", "scores", ")", ")", "return", "final_result", ",", "final_result_h0" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
pnorm
[P(X>pi, mu, sigma) for pi in pvalues] for normal distributed stat with expectation value mu and std deviation sigma
pyprophet/stats.py
def pnorm(stat, stat0): """ [P(X>pi, mu, sigma) for pi in pvalues] for normal distributed stat with expectation value mu and std deviation sigma """ mu, sigma = mean_and_std_dev(stat0) stat = to_one_dim_array(stat, np.float64) args = (stat - mu) / sigma return 1-(0.5 * (1.0 + scipy.special.erf(args / np.sqrt(2.0))))
def pnorm(stat, stat0): """ [P(X>pi, mu, sigma) for pi in pvalues] for normal distributed stat with expectation value mu and std deviation sigma """ mu, sigma = mean_and_std_dev(stat0) stat = to_one_dim_array(stat, np.float64) args = (stat - mu) / sigma return 1-(0.5 * (1.0 + scipy.special.erf(args / np.sqrt(2.0))))
[ "[", "P", "(", "X", ">", "pi", "mu", "sigma", ")", "for", "pi", "in", "pvalues", "]", "for", "normal", "distributed", "stat", "with", "expectation", "value", "mu", "and", "std", "deviation", "sigma" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L122-L130
[ "def", "pnorm", "(", "stat", ",", "stat0", ")", ":", "mu", ",", "sigma", "=", "mean_and_std_dev", "(", "stat0", ")", "stat", "=", "to_one_dim_array", "(", "stat", ",", "np", ".", "float64", ")", "args", "=", "(", "stat", "-", "mu", ")", "/", "sigma", "return", "1", "-", "(", "0.5", "*", "(", "1.0", "+", "scipy", ".", "special", ".", "erf", "(", "args", "/", "np", ".", "sqrt", "(", "2.0", ")", ")", ")", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
pemp
Computes empirical values identically to bioconductor/qvalue empPvals
pyprophet/stats.py
def pemp(stat, stat0): """ Computes empirical values identically to bioconductor/qvalue empPvals """ assert len(stat0) > 0 assert len(stat) > 0 stat = np.array(stat) stat0 = np.array(stat0) m = len(stat) m0 = len(stat0) statc = np.concatenate((stat, stat0)) v = np.array([True] * m + [False] * m0) perm = np.argsort(-statc, kind="mergesort") # reversed sort, mergesort is stable v = v[perm] u = np.where(v)[0] p = (u - np.arange(m)) / float(m0) # ranks can be fractional, we round down to the next integer, ranking returns values starting # with 1, not 0: ranks = np.floor(scipy.stats.rankdata(-stat)).astype(int) - 1 p = p[ranks] p[p <= 1.0 / m0] = 1.0 / m0 return p
def pemp(stat, stat0): """ Computes empirical values identically to bioconductor/qvalue empPvals """ assert len(stat0) > 0 assert len(stat) > 0 stat = np.array(stat) stat0 = np.array(stat0) m = len(stat) m0 = len(stat0) statc = np.concatenate((stat, stat0)) v = np.array([True] * m + [False] * m0) perm = np.argsort(-statc, kind="mergesort") # reversed sort, mergesort is stable v = v[perm] u = np.where(v)[0] p = (u - np.arange(m)) / float(m0) # ranks can be fractional, we round down to the next integer, ranking returns values starting # with 1, not 0: ranks = np.floor(scipy.stats.rankdata(-stat)).astype(int) - 1 p = p[ranks] p[p <= 1.0 / m0] = 1.0 / m0 return p
[ "Computes", "empirical", "values", "identically", "to", "bioconductor", "/", "qvalue", "empPvals" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L133-L159
[ "def", "pemp", "(", "stat", ",", "stat0", ")", ":", "assert", "len", "(", "stat0", ")", ">", "0", "assert", "len", "(", "stat", ")", ">", "0", "stat", "=", "np", ".", "array", "(", "stat", ")", "stat0", "=", "np", ".", "array", "(", "stat0", ")", "m", "=", "len", "(", "stat", ")", "m0", "=", "len", "(", "stat0", ")", "statc", "=", "np", ".", "concatenate", "(", "(", "stat", ",", "stat0", ")", ")", "v", "=", "np", ".", "array", "(", "[", "True", "]", "*", "m", "+", "[", "False", "]", "*", "m0", ")", "perm", "=", "np", ".", "argsort", "(", "-", "statc", ",", "kind", "=", "\"mergesort\"", ")", "# reversed sort, mergesort is stable", "v", "=", "v", "[", "perm", "]", "u", "=", "np", ".", "where", "(", "v", ")", "[", "0", "]", "p", "=", "(", "u", "-", "np", ".", "arange", "(", "m", ")", ")", "/", "float", "(", "m0", ")", "# ranks can be fractional, we round down to the next integer, ranking returns values starting", "# with 1, not 0:", "ranks", "=", "np", ".", "floor", "(", "scipy", ".", "stats", ".", "rankdata", "(", "-", "stat", ")", ")", ".", "astype", "(", "int", ")", "-", "1", "p", "=", "p", "[", "ranks", "]", "p", "[", "p", "<=", "1.0", "/", "m0", "]", "=", "1.0", "/", "m0", "return", "p" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
pi0est
Estimate pi0 according to bioconductor/qvalue
pyprophet/stats.py
def pi0est(p_values, lambda_ = np.arange(0.05,1.0,0.05), pi0_method = "smoother", smooth_df = 3, smooth_log_pi0 = False): """ Estimate pi0 according to bioconductor/qvalue """ # Compare to bioconductor/qvalue reference implementation # import rpy2 # import rpy2.robjects as robjects # from rpy2.robjects import pandas2ri # pandas2ri.activate() # smoothspline=robjects.r('smooth.spline') # predict=robjects.r('predict') p = np.array(p_values) rm_na = np.isfinite(p) p = p[rm_na] m = len(p) ll = 1 if isinstance(lambda_, np.ndarray ): ll = len(lambda_) lambda_ = np.sort(lambda_) if (min(p) < 0 or max(p) > 1): raise click.ClickException("p-values not in valid range [0,1].") elif (ll > 1 and ll < 4): raise click.ClickException("If lambda_ is not predefined (one value), at least four data points are required.") elif (np.min(lambda_) < 0 or np.max(lambda_) >= 1): raise click.ClickException("Lambda must be within [0,1)") if (ll == 1): pi0 = np.mean(p >= lambda_)/(1 - lambda_) pi0_lambda = pi0 pi0 = np.minimum(pi0, 1) pi0Smooth = False else: pi0 = [] for l in lambda_: pi0.append(np.mean(p >= l)/(1 - l)) pi0_lambda = pi0 if (pi0_method == "smoother"): if smooth_log_pi0: pi0 = np.log(pi0) spi0 = sp.interpolate.UnivariateSpline(lambda_, pi0, k=smooth_df) pi0Smooth = np.exp(spi0(lambda_)) # spi0 = smoothspline(lambda_, pi0, df = smooth_df) # R reference function # pi0Smooth = np.exp(predict(spi0, x = lambda_).rx2('y')) # R reference function else: spi0 = sp.interpolate.UnivariateSpline(lambda_, pi0, k=smooth_df) pi0Smooth = spi0(lambda_) # spi0 = smoothspline(lambda_, pi0, df = smooth_df) # R reference function # pi0Smooth = predict(spi0, x = lambda_).rx2('y') # R reference function pi0 = np.minimum(pi0Smooth[ll-1],1) elif (pi0_method == "bootstrap"): minpi0 = np.percentile(pi0,0.1) W = [] for l in lambda_: W.append(np.sum(p >= l)) mse = (np.array(W) / (np.power(m,2) * np.power((1 - lambda_),2))) * (1 - np.array(W) / m) + np.power((pi0 - minpi0),2) pi0 = np.minimum(pi0[np.argmin(mse)],1) pi0Smooth = False else: raise click.ClickException("pi0_method must be one of 'smoother' or 'bootstrap'.") if (pi0<=0): raise click.ClickException("The estimated pi0 <= 0. Check that you have valid p-values or use a different range of lambda.") return {'pi0': pi0, 'pi0_lambda': pi0_lambda, 'lambda_': lambda_, 'pi0_smooth': pi0Smooth}
def pi0est(p_values, lambda_ = np.arange(0.05,1.0,0.05), pi0_method = "smoother", smooth_df = 3, smooth_log_pi0 = False): """ Estimate pi0 according to bioconductor/qvalue """ # Compare to bioconductor/qvalue reference implementation # import rpy2 # import rpy2.robjects as robjects # from rpy2.robjects import pandas2ri # pandas2ri.activate() # smoothspline=robjects.r('smooth.spline') # predict=robjects.r('predict') p = np.array(p_values) rm_na = np.isfinite(p) p = p[rm_na] m = len(p) ll = 1 if isinstance(lambda_, np.ndarray ): ll = len(lambda_) lambda_ = np.sort(lambda_) if (min(p) < 0 or max(p) > 1): raise click.ClickException("p-values not in valid range [0,1].") elif (ll > 1 and ll < 4): raise click.ClickException("If lambda_ is not predefined (one value), at least four data points are required.") elif (np.min(lambda_) < 0 or np.max(lambda_) >= 1): raise click.ClickException("Lambda must be within [0,1)") if (ll == 1): pi0 = np.mean(p >= lambda_)/(1 - lambda_) pi0_lambda = pi0 pi0 = np.minimum(pi0, 1) pi0Smooth = False else: pi0 = [] for l in lambda_: pi0.append(np.mean(p >= l)/(1 - l)) pi0_lambda = pi0 if (pi0_method == "smoother"): if smooth_log_pi0: pi0 = np.log(pi0) spi0 = sp.interpolate.UnivariateSpline(lambda_, pi0, k=smooth_df) pi0Smooth = np.exp(spi0(lambda_)) # spi0 = smoothspline(lambda_, pi0, df = smooth_df) # R reference function # pi0Smooth = np.exp(predict(spi0, x = lambda_).rx2('y')) # R reference function else: spi0 = sp.interpolate.UnivariateSpline(lambda_, pi0, k=smooth_df) pi0Smooth = spi0(lambda_) # spi0 = smoothspline(lambda_, pi0, df = smooth_df) # R reference function # pi0Smooth = predict(spi0, x = lambda_).rx2('y') # R reference function pi0 = np.minimum(pi0Smooth[ll-1],1) elif (pi0_method == "bootstrap"): minpi0 = np.percentile(pi0,0.1) W = [] for l in lambda_: W.append(np.sum(p >= l)) mse = (np.array(W) / (np.power(m,2) * np.power((1 - lambda_),2))) * (1 - np.array(W) / m) + np.power((pi0 - minpi0),2) pi0 = np.minimum(pi0[np.argmin(mse)],1) pi0Smooth = False else: raise click.ClickException("pi0_method must be one of 'smoother' or 'bootstrap'.") if (pi0<=0): raise click.ClickException("The estimated pi0 <= 0. Check that you have valid p-values or use a different range of lambda.") return {'pi0': pi0, 'pi0_lambda': pi0_lambda, 'lambda_': lambda_, 'pi0_smooth': pi0Smooth}
[ "Estimate", "pi0", "according", "to", "bioconductor", "/", "qvalue" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L163-L229
[ "def", "pi0est", "(", "p_values", ",", "lambda_", "=", "np", ".", "arange", "(", "0.05", ",", "1.0", ",", "0.05", ")", ",", "pi0_method", "=", "\"smoother\"", ",", "smooth_df", "=", "3", ",", "smooth_log_pi0", "=", "False", ")", ":", "# Compare to bioconductor/qvalue reference implementation", "# import rpy2", "# import rpy2.robjects as robjects", "# from rpy2.robjects import pandas2ri", "# pandas2ri.activate()", "# smoothspline=robjects.r('smooth.spline')", "# predict=robjects.r('predict')", "p", "=", "np", ".", "array", "(", "p_values", ")", "rm_na", "=", "np", ".", "isfinite", "(", "p", ")", "p", "=", "p", "[", "rm_na", "]", "m", "=", "len", "(", "p", ")", "ll", "=", "1", "if", "isinstance", "(", "lambda_", ",", "np", ".", "ndarray", ")", ":", "ll", "=", "len", "(", "lambda_", ")", "lambda_", "=", "np", ".", "sort", "(", "lambda_", ")", "if", "(", "min", "(", "p", ")", "<", "0", "or", "max", "(", "p", ")", ">", "1", ")", ":", "raise", "click", ".", "ClickException", "(", "\"p-values not in valid range [0,1].\"", ")", "elif", "(", "ll", ">", "1", "and", "ll", "<", "4", ")", ":", "raise", "click", ".", "ClickException", "(", "\"If lambda_ is not predefined (one value), at least four data points are required.\"", ")", "elif", "(", "np", ".", "min", "(", "lambda_", ")", "<", "0", "or", "np", ".", "max", "(", "lambda_", ")", ">=", "1", ")", ":", "raise", "click", ".", "ClickException", "(", "\"Lambda must be within [0,1)\"", ")", "if", "(", "ll", "==", "1", ")", ":", "pi0", "=", "np", ".", "mean", "(", "p", ">=", "lambda_", ")", "/", "(", "1", "-", "lambda_", ")", "pi0_lambda", "=", "pi0", "pi0", "=", "np", ".", "minimum", "(", "pi0", ",", "1", ")", "pi0Smooth", "=", "False", "else", ":", "pi0", "=", "[", "]", "for", "l", "in", "lambda_", ":", "pi0", ".", "append", "(", "np", ".", "mean", "(", "p", ">=", "l", ")", "/", "(", "1", "-", "l", ")", ")", "pi0_lambda", "=", "pi0", "if", "(", "pi0_method", "==", "\"smoother\"", ")", ":", "if", "smooth_log_pi0", ":", "pi0", "=", "np", ".", "log", "(", "pi0", ")", "spi0", "=", "sp", ".", "interpolate", ".", "UnivariateSpline", "(", "lambda_", ",", "pi0", ",", "k", "=", "smooth_df", ")", "pi0Smooth", "=", "np", ".", "exp", "(", "spi0", "(", "lambda_", ")", ")", "# spi0 = smoothspline(lambda_, pi0, df = smooth_df) # R reference function", "# pi0Smooth = np.exp(predict(spi0, x = lambda_).rx2('y')) # R reference function", "else", ":", "spi0", "=", "sp", ".", "interpolate", ".", "UnivariateSpline", "(", "lambda_", ",", "pi0", ",", "k", "=", "smooth_df", ")", "pi0Smooth", "=", "spi0", "(", "lambda_", ")", "# spi0 = smoothspline(lambda_, pi0, df = smooth_df) # R reference function", "# pi0Smooth = predict(spi0, x = lambda_).rx2('y') # R reference function", "pi0", "=", "np", ".", "minimum", "(", "pi0Smooth", "[", "ll", "-", "1", "]", ",", "1", ")", "elif", "(", "pi0_method", "==", "\"bootstrap\"", ")", ":", "minpi0", "=", "np", ".", "percentile", "(", "pi0", ",", "0.1", ")", "W", "=", "[", "]", "for", "l", "in", "lambda_", ":", "W", ".", "append", "(", "np", ".", "sum", "(", "p", ">=", "l", ")", ")", "mse", "=", "(", "np", ".", "array", "(", "W", ")", "/", "(", "np", ".", "power", "(", "m", ",", "2", ")", "*", "np", ".", "power", "(", "(", "1", "-", "lambda_", ")", ",", "2", ")", ")", ")", "*", "(", "1", "-", "np", ".", "array", "(", "W", ")", "/", "m", ")", "+", "np", ".", "power", "(", "(", "pi0", "-", "minpi0", ")", ",", "2", ")", "pi0", "=", "np", ".", "minimum", "(", "pi0", "[", "np", ".", "argmin", "(", "mse", ")", "]", ",", "1", ")", "pi0Smooth", "=", "False", "else", ":", "raise", "click", ".", "ClickException", "(", "\"pi0_method must be one of 'smoother' or 'bootstrap'.\"", ")", "if", "(", "pi0", "<=", "0", ")", ":", "raise", "click", ".", "ClickException", "(", "\"The estimated pi0 <= 0. Check that you have valid p-values or use a different range of lambda.\"", ")", "return", "{", "'pi0'", ":", "pi0", ",", "'pi0_lambda'", ":", "pi0_lambda", ",", "'lambda_'", ":", "lambda_", ",", "'pi0_smooth'", ":", "pi0Smooth", "}" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
lfdr
Estimate local FDR / posterior error probability from p-values according to bioconductor/qvalue
pyprophet/stats.py
def lfdr(p_values, pi0, trunc = True, monotone = True, transf = "probit", adj = 1.5, eps = np.power(10.0,-8)): """ Estimate local FDR / posterior error probability from p-values according to bioconductor/qvalue """ p = np.array(p_values) # Compare to bioconductor/qvalue reference implementation # import rpy2 # import rpy2.robjects as robjects # from rpy2.robjects import pandas2ri # pandas2ri.activate() # density=robjects.r('density') # smoothspline=robjects.r('smooth.spline') # predict=robjects.r('predict') # Check inputs lfdr_out = p rm_na = np.isfinite(p) p = p[rm_na] if (min(p) < 0 or max(p) > 1): raise click.ClickException("p-values not in valid range [0,1].") elif (pi0 < 0 or pi0 > 1): raise click.ClickException("pi0 not in valid range [0,1].") # Local FDR method for both probit and logit transformations if (transf == "probit"): p = np.maximum(p, eps) p = np.minimum(p, 1-eps) x = scipy.stats.norm.ppf(p, loc=0, scale=1) # R-like implementation bw = bw_nrd0(x) myd = KDEUnivariate(x) myd.fit(bw=adj*bw, gridsize = 512) splinefit = sp.interpolate.splrep(myd.support, myd.density) y = sp.interpolate.splev(x, splinefit) # myd = density(x, adjust = 1.5) # R reference function # mys = smoothspline(x = myd.rx2('x'), y = myd.rx2('y')) # R reference function # y = predict(mys, x).rx2('y') # R reference function lfdr = pi0 * scipy.stats.norm.pdf(x) / y elif (transf == "logit"): x = np.log((p + eps) / (1 - p + eps)) # R-like implementation bw = bw_nrd0(x) myd = KDEUnivariate(x) myd.fit(bw=adj*bw, gridsize = 512) splinefit = sp.interpolate.splrep(myd.support, myd.density) y = sp.interpolate.splev(x, splinefit) # myd = density(x, adjust = 1.5) # R reference function # mys = smoothspline(x = myd.rx2('x'), y = myd.rx2('y')) # R reference function # y = predict(mys, x).rx2('y') # R reference function dx = np.exp(x) / np.power((1 + np.exp(x)),2) lfdr = (pi0 * dx) / y else: raise click.ClickException("Invalid local FDR method.") if (trunc): lfdr[lfdr > 1] = 1 if (monotone): lfdr = lfdr[p.ravel().argsort()] for i in range(1,len(x)): if (lfdr[i] < lfdr[i - 1]): lfdr[i] = lfdr[i - 1] lfdr = lfdr[scipy.stats.rankdata(p,"min")-1] lfdr_out[rm_na] = lfdr return lfdr_out
def lfdr(p_values, pi0, trunc = True, monotone = True, transf = "probit", adj = 1.5, eps = np.power(10.0,-8)): """ Estimate local FDR / posterior error probability from p-values according to bioconductor/qvalue """ p = np.array(p_values) # Compare to bioconductor/qvalue reference implementation # import rpy2 # import rpy2.robjects as robjects # from rpy2.robjects import pandas2ri # pandas2ri.activate() # density=robjects.r('density') # smoothspline=robjects.r('smooth.spline') # predict=robjects.r('predict') # Check inputs lfdr_out = p rm_na = np.isfinite(p) p = p[rm_na] if (min(p) < 0 or max(p) > 1): raise click.ClickException("p-values not in valid range [0,1].") elif (pi0 < 0 or pi0 > 1): raise click.ClickException("pi0 not in valid range [0,1].") # Local FDR method for both probit and logit transformations if (transf == "probit"): p = np.maximum(p, eps) p = np.minimum(p, 1-eps) x = scipy.stats.norm.ppf(p, loc=0, scale=1) # R-like implementation bw = bw_nrd0(x) myd = KDEUnivariate(x) myd.fit(bw=adj*bw, gridsize = 512) splinefit = sp.interpolate.splrep(myd.support, myd.density) y = sp.interpolate.splev(x, splinefit) # myd = density(x, adjust = 1.5) # R reference function # mys = smoothspline(x = myd.rx2('x'), y = myd.rx2('y')) # R reference function # y = predict(mys, x).rx2('y') # R reference function lfdr = pi0 * scipy.stats.norm.pdf(x) / y elif (transf == "logit"): x = np.log((p + eps) / (1 - p + eps)) # R-like implementation bw = bw_nrd0(x) myd = KDEUnivariate(x) myd.fit(bw=adj*bw, gridsize = 512) splinefit = sp.interpolate.splrep(myd.support, myd.density) y = sp.interpolate.splev(x, splinefit) # myd = density(x, adjust = 1.5) # R reference function # mys = smoothspline(x = myd.rx2('x'), y = myd.rx2('y')) # R reference function # y = predict(mys, x).rx2('y') # R reference function dx = np.exp(x) / np.power((1 + np.exp(x)),2) lfdr = (pi0 * dx) / y else: raise click.ClickException("Invalid local FDR method.") if (trunc): lfdr[lfdr > 1] = 1 if (monotone): lfdr = lfdr[p.ravel().argsort()] for i in range(1,len(x)): if (lfdr[i] < lfdr[i - 1]): lfdr[i] = lfdr[i - 1] lfdr = lfdr[scipy.stats.rankdata(p,"min")-1] lfdr_out[rm_na] = lfdr return lfdr_out
[ "Estimate", "local", "FDR", "/", "posterior", "error", "probability", "from", "p", "-", "values", "according", "to", "bioconductor", "/", "qvalue" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L275-L345
[ "def", "lfdr", "(", "p_values", ",", "pi0", ",", "trunc", "=", "True", ",", "monotone", "=", "True", ",", "transf", "=", "\"probit\"", ",", "adj", "=", "1.5", ",", "eps", "=", "np", ".", "power", "(", "10.0", ",", "-", "8", ")", ")", ":", "p", "=", "np", ".", "array", "(", "p_values", ")", "# Compare to bioconductor/qvalue reference implementation", "# import rpy2", "# import rpy2.robjects as robjects", "# from rpy2.robjects import pandas2ri", "# pandas2ri.activate()", "# density=robjects.r('density')", "# smoothspline=robjects.r('smooth.spline')", "# predict=robjects.r('predict')", "# Check inputs", "lfdr_out", "=", "p", "rm_na", "=", "np", ".", "isfinite", "(", "p", ")", "p", "=", "p", "[", "rm_na", "]", "if", "(", "min", "(", "p", ")", "<", "0", "or", "max", "(", "p", ")", ">", "1", ")", ":", "raise", "click", ".", "ClickException", "(", "\"p-values not in valid range [0,1].\"", ")", "elif", "(", "pi0", "<", "0", "or", "pi0", ">", "1", ")", ":", "raise", "click", ".", "ClickException", "(", "\"pi0 not in valid range [0,1].\"", ")", "# Local FDR method for both probit and logit transformations", "if", "(", "transf", "==", "\"probit\"", ")", ":", "p", "=", "np", ".", "maximum", "(", "p", ",", "eps", ")", "p", "=", "np", ".", "minimum", "(", "p", ",", "1", "-", "eps", ")", "x", "=", "scipy", ".", "stats", ".", "norm", ".", "ppf", "(", "p", ",", "loc", "=", "0", ",", "scale", "=", "1", ")", "# R-like implementation", "bw", "=", "bw_nrd0", "(", "x", ")", "myd", "=", "KDEUnivariate", "(", "x", ")", "myd", ".", "fit", "(", "bw", "=", "adj", "*", "bw", ",", "gridsize", "=", "512", ")", "splinefit", "=", "sp", ".", "interpolate", ".", "splrep", "(", "myd", ".", "support", ",", "myd", ".", "density", ")", "y", "=", "sp", ".", "interpolate", ".", "splev", "(", "x", ",", "splinefit", ")", "# myd = density(x, adjust = 1.5) # R reference function", "# mys = smoothspline(x = myd.rx2('x'), y = myd.rx2('y')) # R reference function", "# y = predict(mys, x).rx2('y') # R reference function", "lfdr", "=", "pi0", "*", "scipy", ".", "stats", ".", "norm", ".", "pdf", "(", "x", ")", "/", "y", "elif", "(", "transf", "==", "\"logit\"", ")", ":", "x", "=", "np", ".", "log", "(", "(", "p", "+", "eps", ")", "/", "(", "1", "-", "p", "+", "eps", ")", ")", "# R-like implementation", "bw", "=", "bw_nrd0", "(", "x", ")", "myd", "=", "KDEUnivariate", "(", "x", ")", "myd", ".", "fit", "(", "bw", "=", "adj", "*", "bw", ",", "gridsize", "=", "512", ")", "splinefit", "=", "sp", ".", "interpolate", ".", "splrep", "(", "myd", ".", "support", ",", "myd", ".", "density", ")", "y", "=", "sp", ".", "interpolate", ".", "splev", "(", "x", ",", "splinefit", ")", "# myd = density(x, adjust = 1.5) # R reference function", "# mys = smoothspline(x = myd.rx2('x'), y = myd.rx2('y')) # R reference function", "# y = predict(mys, x).rx2('y') # R reference function", "dx", "=", "np", ".", "exp", "(", "x", ")", "/", "np", ".", "power", "(", "(", "1", "+", "np", ".", "exp", "(", "x", ")", ")", ",", "2", ")", "lfdr", "=", "(", "pi0", "*", "dx", ")", "/", "y", "else", ":", "raise", "click", ".", "ClickException", "(", "\"Invalid local FDR method.\"", ")", "if", "(", "trunc", ")", ":", "lfdr", "[", "lfdr", ">", "1", "]", "=", "1", "if", "(", "monotone", ")", ":", "lfdr", "=", "lfdr", "[", "p", ".", "ravel", "(", ")", ".", "argsort", "(", ")", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "x", ")", ")", ":", "if", "(", "lfdr", "[", "i", "]", "<", "lfdr", "[", "i", "-", "1", "]", ")", ":", "lfdr", "[", "i", "]", "=", "lfdr", "[", "i", "-", "1", "]", "lfdr", "=", "lfdr", "[", "scipy", ".", "stats", ".", "rankdata", "(", "p", ",", "\"min\"", ")", "-", "1", "]", "lfdr_out", "[", "rm_na", "]", "=", "lfdr", "return", "lfdr_out" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
final_err_table
Create artificial cutoff sample points from given range of cutoff values in df, number of sample points is 'num_cut_offs'
pyprophet/stats.py
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 = (max_ - min_) * 0.05 sampled_cutoffs = np.linspace(min_ - margin, max_ + margin, num_cut_offs, dtype=np.float32) # find best matching row index for each sampled cut off: ix = find_nearest_matches(np.float32(df.cutoff.values), sampled_cutoffs) # create sub dataframe: sampled_df = df.iloc[ix].copy() sampled_df.cutoff = sampled_cutoffs # remove 'old' index from input df: sampled_df.reset_index(inplace=True, drop=True) return sampled_df
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 = (max_ - min_) * 0.05 sampled_cutoffs = np.linspace(min_ - margin, max_ + margin, num_cut_offs, dtype=np.float32) # find best matching row index for each sampled cut off: ix = find_nearest_matches(np.float32(df.cutoff.values), sampled_cutoffs) # create sub dataframe: sampled_df = df.iloc[ix].copy() sampled_df.cutoff = sampled_cutoffs # remove 'old' index from input df: sampled_df.reset_index(inplace=True, drop=True) return sampled_df
[ "Create", "artificial", "cutoff", "sample", "points", "from", "given", "range", "of", "cutoff", "values", "in", "df", "number", "of", "sample", "points", "is", "num_cut_offs" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L393-L413
[ "def", "final_err_table", "(", "df", ",", "num_cut_offs", "=", "51", ")", ":", "cutoffs", "=", "df", ".", "cutoff", ".", "values", "min_", "=", "min", "(", "cutoffs", ")", "max_", "=", "max", "(", "cutoffs", ")", "# extend max_ and min_ by 5 % of full range", "margin", "=", "(", "max_", "-", "min_", ")", "*", "0.05", "sampled_cutoffs", "=", "np", ".", "linspace", "(", "min_", "-", "margin", ",", "max_", "+", "margin", ",", "num_cut_offs", ",", "dtype", "=", "np", ".", "float32", ")", "# find best matching row index for each sampled cut off:", "ix", "=", "find_nearest_matches", "(", "np", ".", "float32", "(", "df", ".", "cutoff", ".", "values", ")", ",", "sampled_cutoffs", ")", "# create sub dataframe:", "sampled_df", "=", "df", ".", "iloc", "[", "ix", "]", ".", "copy", "(", ")", "sampled_df", ".", "cutoff", "=", "sampled_cutoffs", "# remove 'old' index from input df:", "sampled_df", ".", "reset_index", "(", "inplace", "=", "True", ",", "drop", "=", "True", ")", "return", "sampled_df" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
summary_err_table
Summary error table for some typical q-values
pyprophet/stats.py
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 sub table df_sub = df.iloc[ix].copy() # remove duplicate hits, mark them with None / NAN: for i_sub, (i0, i1) in enumerate(zip(ix, ix[1:])): if i1 == i0: df_sub.iloc[i_sub + 1, :] = None # attach q values column df_sub.qvalue = qvalues # remove old index from original df: df_sub.reset_index(inplace=True, drop=True) return df_sub[['qvalue','pvalue','svalue','pep','fdr','fnr','fpr','tp','tn','fp','fn','cutoff']]
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 sub table df_sub = df.iloc[ix].copy() # remove duplicate hits, mark them with None / NAN: for i_sub, (i0, i1) in enumerate(zip(ix, ix[1:])): if i1 == i0: df_sub.iloc[i_sub + 1, :] = None # attach q values column df_sub.qvalue = qvalues # remove old index from original df: df_sub.reset_index(inplace=True, drop=True) return df_sub[['qvalue','pvalue','svalue','pep','fdr','fnr','fpr','tp','tn','fp','fn','cutoff']]
[ "Summary", "error", "table", "for", "some", "typical", "q", "-", "values" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L417-L433
[ "def", "summary_err_table", "(", "df", ",", "qvalues", "=", "[", "0", ",", "0.01", ",", "0.02", ",", "0.05", ",", "0.1", ",", "0.2", ",", "0.3", ",", "0.4", ",", "0.5", "]", ")", ":", "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 sub table", "df_sub", "=", "df", ".", "iloc", "[", "ix", "]", ".", "copy", "(", ")", "# remove duplicate hits, mark them with None / NAN:", "for", "i_sub", ",", "(", "i0", ",", "i1", ")", "in", "enumerate", "(", "zip", "(", "ix", ",", "ix", "[", "1", ":", "]", ")", ")", ":", "if", "i1", "==", "i0", ":", "df_sub", ".", "iloc", "[", "i_sub", "+", "1", ",", ":", "]", "=", "None", "# attach q values column", "df_sub", ".", "qvalue", "=", "qvalues", "# remove old index from original df:", "df_sub", ".", "reset_index", "(", "inplace", "=", "True", ",", "drop", "=", "True", ")", "return", "df_sub", "[", "[", "'qvalue'", ",", "'pvalue'", ",", "'svalue'", ",", "'pep'", ",", "'fdr'", ",", "'fnr'", ",", "'fpr'", ",", "'tp'", ",", "'tn'", ",", "'fp'", ",", "'fn'", ",", "'cutoff'", "]", "]" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
error_statistics
Takes list of decoy and target scores and creates error statistics for target values
pyprophet/stats.py
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 target scores and creates error statistics for target values """ target_scores = to_one_dim_array(target_scores) target_scores = np.sort(target_scores[~np.isnan(target_scores)]) decoy_scores = to_one_dim_array(decoy_scores) decoy_scores = np.sort(decoy_scores[~np.isnan(decoy_scores)]) # compute p-values using decoy scores if parametric: # parametric target_pvalues = pnorm(target_scores, decoy_scores) else: # non-parametric target_pvalues = pemp(target_scores, decoy_scores) # estimate pi0 pi0 = pi0est(target_pvalues, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0) # compute q-value target_qvalues = qvalue(target_pvalues, pi0['pi0'], pfdr) # compute other metrics metrics = stat_metrics(target_pvalues, pi0['pi0'], pfdr) # generate main statistics table error_stat = pd.DataFrame({'cutoff': target_scores, 'pvalue': target_pvalues, 'qvalue': target_qvalues, 'svalue': metrics['svalue'], 'tp': metrics['tp'], 'fp': metrics['fp'], 'tn': metrics['tn'], 'fn': metrics['fn'], 'fpr': metrics['fpr'], 'fdr': metrics['fdr'], 'fnr': metrics['fnr']}) # compute lfdr / PEP if compute_lfdr: error_stat['pep'] = lfdr(target_pvalues, pi0['pi0'], lfdr_trunc, lfdr_monotone, lfdr_transf, lfdr_adj, lfdr_eps) return error_stat, pi0
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 target scores and creates error statistics for target values """ target_scores = to_one_dim_array(target_scores) target_scores = np.sort(target_scores[~np.isnan(target_scores)]) decoy_scores = to_one_dim_array(decoy_scores) decoy_scores = np.sort(decoy_scores[~np.isnan(decoy_scores)]) # compute p-values using decoy scores if parametric: # parametric target_pvalues = pnorm(target_scores, decoy_scores) else: # non-parametric target_pvalues = pemp(target_scores, decoy_scores) # estimate pi0 pi0 = pi0est(target_pvalues, pi0_lambda, pi0_method, pi0_smooth_df, pi0_smooth_log_pi0) # compute q-value target_qvalues = qvalue(target_pvalues, pi0['pi0'], pfdr) # compute other metrics metrics = stat_metrics(target_pvalues, pi0['pi0'], pfdr) # generate main statistics table error_stat = pd.DataFrame({'cutoff': target_scores, 'pvalue': target_pvalues, 'qvalue': target_qvalues, 'svalue': metrics['svalue'], 'tp': metrics['tp'], 'fp': metrics['fp'], 'tn': metrics['tn'], 'fn': metrics['fn'], 'fpr': metrics['fpr'], 'fdr': metrics['fdr'], 'fnr': metrics['fnr']}) # compute lfdr / PEP if compute_lfdr: error_stat['pep'] = lfdr(target_pvalues, pi0['pi0'], lfdr_trunc, lfdr_monotone, lfdr_transf, lfdr_adj, lfdr_eps) return error_stat, pi0
[ "Takes", "list", "of", "decoy", "and", "target", "scores", "and", "creates", "error", "statistics", "for", "target", "values" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L437-L470
[ "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", ")", ")", ":", "target_scores", "=", "to_one_dim_array", "(", "target_scores", ")", "target_scores", "=", "np", ".", "sort", "(", "target_scores", "[", "~", "np", ".", "isnan", "(", "target_scores", ")", "]", ")", "decoy_scores", "=", "to_one_dim_array", "(", "decoy_scores", ")", "decoy_scores", "=", "np", ".", "sort", "(", "decoy_scores", "[", "~", "np", ".", "isnan", "(", "decoy_scores", ")", "]", ")", "# compute p-values using decoy scores", "if", "parametric", ":", "# parametric", "target_pvalues", "=", "pnorm", "(", "target_scores", ",", "decoy_scores", ")", "else", ":", "# non-parametric", "target_pvalues", "=", "pemp", "(", "target_scores", ",", "decoy_scores", ")", "# estimate pi0", "pi0", "=", "pi0est", "(", "target_pvalues", ",", "pi0_lambda", ",", "pi0_method", ",", "pi0_smooth_df", ",", "pi0_smooth_log_pi0", ")", "# compute q-value", "target_qvalues", "=", "qvalue", "(", "target_pvalues", ",", "pi0", "[", "'pi0'", "]", ",", "pfdr", ")", "# compute other metrics", "metrics", "=", "stat_metrics", "(", "target_pvalues", ",", "pi0", "[", "'pi0'", "]", ",", "pfdr", ")", "# generate main statistics table", "error_stat", "=", "pd", ".", "DataFrame", "(", "{", "'cutoff'", ":", "target_scores", ",", "'pvalue'", ":", "target_pvalues", ",", "'qvalue'", ":", "target_qvalues", ",", "'svalue'", ":", "metrics", "[", "'svalue'", "]", ",", "'tp'", ":", "metrics", "[", "'tp'", "]", ",", "'fp'", ":", "metrics", "[", "'fp'", "]", ",", "'tn'", ":", "metrics", "[", "'tn'", "]", ",", "'fn'", ":", "metrics", "[", "'fn'", "]", ",", "'fpr'", ":", "metrics", "[", "'fpr'", "]", ",", "'fdr'", ":", "metrics", "[", "'fdr'", "]", ",", "'fnr'", ":", "metrics", "[", "'fnr'", "]", "}", ")", "# compute lfdr / PEP", "if", "compute_lfdr", ":", "error_stat", "[", "'pep'", "]", "=", "lfdr", "(", "target_pvalues", ",", "pi0", "[", "'pi0'", "]", ",", "lfdr_trunc", ",", "lfdr_monotone", ",", "lfdr_transf", ",", "lfdr_adj", ",", "lfdr_eps", ")", "return", "error_stat", ",", "pi0" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
find_cutoff
Finds cut off target score for specified false discovery rate fdr
pyprophet/stats.py
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_df, pi0_smooth_log_pi0, False) if not len(error_stat): raise click.ClickException("Too little data for calculating error statistcs.") i0 = (error_stat.qvalue - cutoff_fdr).abs().idxmin() cutoff = error_stat.iloc[i0]["cutoff"] return cutoff
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_df, pi0_smooth_log_pi0, False) if not len(error_stat): raise click.ClickException("Too little data for calculating error statistcs.") i0 = (error_stat.qvalue - cutoff_fdr).abs().idxmin() cutoff = error_stat.iloc[i0]["cutoff"] return cutoff
[ "Finds", "cut", "off", "target", "score", "for", "specified", "false", "discovery", "rate", "fdr" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/stats.py#L473-L481
[ "def", "find_cutoff", "(", "tt_scores", ",", "td_scores", ",", "cutoff_fdr", ",", "parametric", ",", "pfdr", ",", "pi0_lambda", ",", "pi0_method", ",", "pi0_smooth_df", ",", "pi0_smooth_log_pi0", ")", ":", "error_stat", ",", "pi0", "=", "error_statistics", "(", "tt_scores", ",", "td_scores", ",", "parametric", ",", "pfdr", ",", "pi0_lambda", ",", "pi0_method", ",", "pi0_smooth_df", ",", "pi0_smooth_log_pi0", ",", "False", ")", "if", "not", "len", "(", "error_stat", ")", ":", "raise", "click", ".", "ClickException", "(", "\"Too little data for calculating error statistcs.\"", ")", "i0", "=", "(", "error_stat", ".", "qvalue", "-", "cutoff_fdr", ")", ".", "abs", "(", ")", ".", "idxmin", "(", ")", "cutoff", "=", "error_stat", ".", "iloc", "[", "i0", "]", "[", "\"cutoff\"", "]", "return", "cutoff" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
score
Conduct semi-supervised learning and error-rate estimation for MS1, MS2 and transition-level data.
pyprophet/main.py
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, level, ipf_max_peakgroup_rank, ipf_max_peakgroup_pep, ipf_max_transition_isotope_overlap, ipf_min_transition_sn, tric_chromprob, threads, test): """ Conduct semi-supervised learning and error-rate estimation for MS1, MS2 and transition-level data. """ if outfile is None: outfile = infile else: outfile = outfile # Prepare XGBoost-specific parameters xgb_hyperparams = {'autotune': xgb_autotune, 'autotune_num_rounds': 10, 'num_boost_round': 100, 'early_stopping_rounds': 10, 'test_size': 0.33} xgb_params = {'eta': 0.3, 'gamma': 0, 'max_depth': 6, 'min_child_weight': 1, 'subsample': 1, 'colsample_bytree': 1, 'colsample_bylevel': 1, 'colsample_bynode': 1, 'lambda': 1, 'alpha': 0, 'scale_pos_weight': 1, 'silent': 1, 'objective': 'binary:logitraw', 'nthread': 1, 'eval_metric': 'auc'} xgb_params_space = {'eta': hp.uniform('eta', 0.0, 0.3), 'gamma': hp.uniform('gamma', 0.0, 0.5), 'max_depth': hp.quniform('max_depth', 2, 8, 1), 'min_child_weight': hp.quniform('min_child_weight', 1, 5, 1), 'subsample': 1, 'colsample_bytree': 1, 'colsample_bylevel': 1, 'colsample_bynode': 1, 'lambda': hp.uniform('lambda', 0.0, 1.0), 'alpha': hp.uniform('alpha', 0.0, 1.0), 'scale_pos_weight': 1.0, 'silent': 1, 'objective': 'binary:logitraw', 'nthread': 1, 'eval_metric': 'auc'} if not apply_weights: PyProphetLearner(infile, outfile, classifier, xgb_hyperparams, xgb_params, xgb_params_space, 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, level, ipf_max_peakgroup_rank, ipf_max_peakgroup_pep, ipf_max_transition_isotope_overlap, ipf_min_transition_sn, tric_chromprob, threads, test).run() else: PyProphetWeightApplier(infile, outfile, classifier, xgb_hyperparams, xgb_params, xgb_params_space, 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, level, ipf_max_peakgroup_rank, ipf_max_peakgroup_pep, ipf_max_transition_isotope_overlap, ipf_min_transition_sn, tric_chromprob, threads, test, apply_weights).run()
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, level, ipf_max_peakgroup_rank, ipf_max_peakgroup_pep, ipf_max_transition_isotope_overlap, ipf_min_transition_sn, tric_chromprob, threads, test): """ Conduct semi-supervised learning and error-rate estimation for MS1, MS2 and transition-level data. """ if outfile is None: outfile = infile else: outfile = outfile # Prepare XGBoost-specific parameters xgb_hyperparams = {'autotune': xgb_autotune, 'autotune_num_rounds': 10, 'num_boost_round': 100, 'early_stopping_rounds': 10, 'test_size': 0.33} xgb_params = {'eta': 0.3, 'gamma': 0, 'max_depth': 6, 'min_child_weight': 1, 'subsample': 1, 'colsample_bytree': 1, 'colsample_bylevel': 1, 'colsample_bynode': 1, 'lambda': 1, 'alpha': 0, 'scale_pos_weight': 1, 'silent': 1, 'objective': 'binary:logitraw', 'nthread': 1, 'eval_metric': 'auc'} xgb_params_space = {'eta': hp.uniform('eta', 0.0, 0.3), 'gamma': hp.uniform('gamma', 0.0, 0.5), 'max_depth': hp.quniform('max_depth', 2, 8, 1), 'min_child_weight': hp.quniform('min_child_weight', 1, 5, 1), 'subsample': 1, 'colsample_bytree': 1, 'colsample_bylevel': 1, 'colsample_bynode': 1, 'lambda': hp.uniform('lambda', 0.0, 1.0), 'alpha': hp.uniform('alpha', 0.0, 1.0), 'scale_pos_weight': 1.0, 'silent': 1, 'objective': 'binary:logitraw', 'nthread': 1, 'eval_metric': 'auc'} if not apply_weights: PyProphetLearner(infile, outfile, classifier, xgb_hyperparams, xgb_params, xgb_params_space, 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, level, ipf_max_peakgroup_rank, ipf_max_peakgroup_pep, ipf_max_transition_isotope_overlap, ipf_min_transition_sn, tric_chromprob, threads, test).run() else: PyProphetWeightApplier(infile, outfile, classifier, xgb_hyperparams, xgb_params, xgb_params_space, 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, level, ipf_max_peakgroup_rank, ipf_max_peakgroup_pep, ipf_max_transition_isotope_overlap, ipf_min_transition_sn, tric_chromprob, threads, test, apply_weights).run()
[ "Conduct", "semi", "-", "supervised", "learning", "and", "error", "-", "rate", "estimation", "for", "MS1", "MS2", "and", "transition", "-", "level", "data", "." ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L75-L95
[ "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", ",", "level", ",", "ipf_max_peakgroup_rank", ",", "ipf_max_peakgroup_pep", ",", "ipf_max_transition_isotope_overlap", ",", "ipf_min_transition_sn", ",", "tric_chromprob", ",", "threads", ",", "test", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "infile", "else", ":", "outfile", "=", "outfile", "# Prepare XGBoost-specific parameters", "xgb_hyperparams", "=", "{", "'autotune'", ":", "xgb_autotune", ",", "'autotune_num_rounds'", ":", "10", ",", "'num_boost_round'", ":", "100", ",", "'early_stopping_rounds'", ":", "10", ",", "'test_size'", ":", "0.33", "}", "xgb_params", "=", "{", "'eta'", ":", "0.3", ",", "'gamma'", ":", "0", ",", "'max_depth'", ":", "6", ",", "'min_child_weight'", ":", "1", ",", "'subsample'", ":", "1", ",", "'colsample_bytree'", ":", "1", ",", "'colsample_bylevel'", ":", "1", ",", "'colsample_bynode'", ":", "1", ",", "'lambda'", ":", "1", ",", "'alpha'", ":", "0", ",", "'scale_pos_weight'", ":", "1", ",", "'silent'", ":", "1", ",", "'objective'", ":", "'binary:logitraw'", ",", "'nthread'", ":", "1", ",", "'eval_metric'", ":", "'auc'", "}", "xgb_params_space", "=", "{", "'eta'", ":", "hp", ".", "uniform", "(", "'eta'", ",", "0.0", ",", "0.3", ")", ",", "'gamma'", ":", "hp", ".", "uniform", "(", "'gamma'", ",", "0.0", ",", "0.5", ")", ",", "'max_depth'", ":", "hp", ".", "quniform", "(", "'max_depth'", ",", "2", ",", "8", ",", "1", ")", ",", "'min_child_weight'", ":", "hp", ".", "quniform", "(", "'min_child_weight'", ",", "1", ",", "5", ",", "1", ")", ",", "'subsample'", ":", "1", ",", "'colsample_bytree'", ":", "1", ",", "'colsample_bylevel'", ":", "1", ",", "'colsample_bynode'", ":", "1", ",", "'lambda'", ":", "hp", ".", "uniform", "(", "'lambda'", ",", "0.0", ",", "1.0", ")", ",", "'alpha'", ":", "hp", ".", "uniform", "(", "'alpha'", ",", "0.0", ",", "1.0", ")", ",", "'scale_pos_weight'", ":", "1.0", ",", "'silent'", ":", "1", ",", "'objective'", ":", "'binary:logitraw'", ",", "'nthread'", ":", "1", ",", "'eval_metric'", ":", "'auc'", "}", "if", "not", "apply_weights", ":", "PyProphetLearner", "(", "infile", ",", "outfile", ",", "classifier", ",", "xgb_hyperparams", ",", "xgb_params", ",", "xgb_params_space", ",", "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", ",", "level", ",", "ipf_max_peakgroup_rank", ",", "ipf_max_peakgroup_pep", ",", "ipf_max_transition_isotope_overlap", ",", "ipf_min_transition_sn", ",", "tric_chromprob", ",", "threads", ",", "test", ")", ".", "run", "(", ")", "else", ":", "PyProphetWeightApplier", "(", "infile", ",", "outfile", ",", "classifier", ",", "xgb_hyperparams", ",", "xgb_params", ",", "xgb_params_space", ",", "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", ",", "level", ",", "ipf_max_peakgroup_rank", ",", "ipf_max_peakgroup_pep", ",", "ipf_max_transition_isotope_overlap", ",", "ipf_min_transition_sn", ",", "tric_chromprob", ",", "threads", ",", "test", ",", "apply_weights", ")", ".", "run", "(", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
ipf
Infer peptidoforms after scoring of MS1, MS2 and transition-level data.
pyprophet/main.py
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 = infile else: outfile = outfile infer_peptidoforms(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)
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 = infile else: outfile = outfile infer_peptidoforms(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", "." ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L112-L122
[ "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", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "infile", "else", ":", "outfile", "=", "outfile", "infer_peptidoforms", "(", "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", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
peptide
Infer peptides and conduct error-rate estimation in different contexts.
pyprophet/main.py
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 = infile else: outfile = outfile infer_peptides(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)
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 = infile else: outfile = outfile infer_peptides(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", "." ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L144-L154
[ "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", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "infile", "else", ":", "outfile", "=", "outfile", "infer_peptides", "(", "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", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
protein
Infer proteins and conduct error-rate estimation in different contexts.
pyprophet/main.py
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 = infile else: outfile = outfile infer_proteins(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)
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 = infile else: outfile = outfile infer_proteins(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", "." ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L176-L186
[ "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", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "infile", "else", ":", "outfile", "=", "outfile", "infer_proteins", "(", "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", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
subsample
Subsample OpenSWATH file to minimum for integrated scoring
pyprophet/main.py
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)
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)
[ "Subsample", "OpenSWATH", "file", "to", "minimum", "for", "integrated", "scoring" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L195-L205
[ "def", "subsample", "(", "infile", ",", "outfile", ",", "subsample_ratio", ",", "test", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "infile", "else", ":", "outfile", "=", "outfile", "subsample_osw", "(", "infile", ",", "outfile", ",", "subsample_ratio", ",", "test", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
reduce
Reduce scored PyProphet file to minimum for global scoring
pyprophet/main.py
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)
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)
[ "Reduce", "scored", "PyProphet", "file", "to", "minimum", "for", "global", "scoring" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L212-L222
[ "def", "reduce", "(", "infile", ",", "outfile", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "infile", "else", ":", "outfile", "=", "outfile", "reduce_osw", "(", "infile", ",", "outfile", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
merge
Merge multiple OSW files and (for large experiments, it is recommended to subsample first).
pyprophet/main.py
def merge(infiles, outfile, same_run, templatefile): """ Merge multiple OSW files and (for large experiments, it is recommended to subsample first). """ if len(infiles) < 1: raise click.ClickException("At least one PyProphet input file needs to be provided.") merge_osw(infiles, outfile, templatefile, same_run)
def merge(infiles, outfile, same_run, templatefile): """ Merge multiple OSW files and (for large experiments, it is recommended to subsample first). """ if len(infiles) < 1: raise click.ClickException("At least one PyProphet input file needs to be provided.") merge_osw(infiles, outfile, templatefile, same_run)
[ "Merge", "multiple", "OSW", "files", "and", "(", "for", "large", "experiments", "it", "is", "recommended", "to", "subsample", "first", ")", "." ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L231-L239
[ "def", "merge", "(", "infiles", ",", "outfile", ",", "same_run", ",", "templatefile", ")", ":", "if", "len", "(", "infiles", ")", "<", "1", ":", "raise", "click", ".", "ClickException", "(", "\"At least one PyProphet input file needs to be provided.\"", ")", "merge_osw", "(", "infiles", ",", "outfile", ",", "templatefile", ",", "same_run", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
backpropagate
Backpropagate multi-run peptide and protein scores to single files
pyprophet/main.py
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)
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)
[ "Backpropagate", "multi", "-", "run", "peptide", "and", "protein", "scores", "to", "single", "files" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L247-L257
[ "def", "backpropagate", "(", "infile", ",", "outfile", ",", "apply_scores", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "infile", "else", ":", "outfile", "=", "outfile", "backpropagate_oswr", "(", "infile", ",", "outfile", ",", "apply_scores", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
export
Export TSV/CSV tables
pyprophet/main.py
def export(infile, outfile, format, outcsv, transition_quantification, max_transition_pep, ipf, ipf_max_peptidoform_pep, max_rs_peakgroup_qvalue, peptide, max_global_peptide_qvalue, protein, max_global_protein_qvalue): """ Export TSV/CSV tables """ if format == "score_plots": export_score_plots(infile) else: if outfile is None: if outcsv: outfile = infile.split(".osw")[0] + ".csv" else: outfile = infile.split(".osw")[0] + ".tsv" else: outfile = outfile export_tsv(infile, outfile, format, outcsv, transition_quantification, max_transition_pep, ipf, ipf_max_peptidoform_pep, max_rs_peakgroup_qvalue, peptide, max_global_peptide_qvalue, protein, max_global_protein_qvalue)
def export(infile, outfile, format, outcsv, transition_quantification, max_transition_pep, ipf, ipf_max_peptidoform_pep, max_rs_peakgroup_qvalue, peptide, max_global_peptide_qvalue, protein, max_global_protein_qvalue): """ Export TSV/CSV tables """ if format == "score_plots": export_score_plots(infile) else: if outfile is None: if outcsv: outfile = infile.split(".osw")[0] + ".csv" else: outfile = infile.split(".osw")[0] + ".tsv" else: outfile = outfile export_tsv(infile, outfile, format, outcsv, transition_quantification, max_transition_pep, ipf, ipf_max_peptidoform_pep, max_rs_peakgroup_qvalue, peptide, max_global_peptide_qvalue, protein, max_global_protein_qvalue)
[ "Export", "TSV", "/", "CSV", "tables" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L277-L292
[ "def", "export", "(", "infile", ",", "outfile", ",", "format", ",", "outcsv", ",", "transition_quantification", ",", "max_transition_pep", ",", "ipf", ",", "ipf_max_peptidoform_pep", ",", "max_rs_peakgroup_qvalue", ",", "peptide", ",", "max_global_peptide_qvalue", ",", "protein", ",", "max_global_protein_qvalue", ")", ":", "if", "format", "==", "\"score_plots\"", ":", "export_score_plots", "(", "infile", ")", "else", ":", "if", "outfile", "is", "None", ":", "if", "outcsv", ":", "outfile", "=", "infile", ".", "split", "(", "\".osw\"", ")", "[", "0", "]", "+", "\".csv\"", "else", ":", "outfile", "=", "infile", ".", "split", "(", "\".osw\"", ")", "[", "0", "]", "+", "\".tsv\"", "else", ":", "outfile", "=", "outfile", "export_tsv", "(", "infile", ",", "outfile", ",", "format", ",", "outcsv", ",", "transition_quantification", ",", "max_transition_pep", ",", "ipf", ",", "ipf_max_peptidoform_pep", ",", "max_rs_peakgroup_qvalue", ",", "peptide", ",", "max_global_peptide_qvalue", ",", "protein", ",", "max_global_protein_qvalue", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
export_compound
Export Compound TSV/CSV tables
pyprophet/main.py
def export_compound(infile, outfile, format, outcsv, max_rs_peakgroup_qvalue): """ Export Compound TSV/CSV tables """ if format == "score_plots": export_score_plots(infile) else: if outfile is None: if outcsv: outfile = infile.split(".osw")[0] + ".csv" else: outfile = infile.split(".osw")[0] + ".tsv" else: outfile = outfile export_compound_tsv(infile, outfile, format, outcsv, max_rs_peakgroup_qvalue)
def export_compound(infile, outfile, format, outcsv, max_rs_peakgroup_qvalue): """ Export Compound TSV/CSV tables """ if format == "score_plots": export_score_plots(infile) else: if outfile is None: if outcsv: outfile = infile.split(".osw")[0] + ".csv" else: outfile = infile.split(".osw")[0] + ".tsv" else: outfile = outfile export_compound_tsv(infile, outfile, format, outcsv, max_rs_peakgroup_qvalue)
[ "Export", "Compound", "TSV", "/", "CSV", "tables" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L304-L319
[ "def", "export_compound", "(", "infile", ",", "outfile", ",", "format", ",", "outcsv", ",", "max_rs_peakgroup_qvalue", ")", ":", "if", "format", "==", "\"score_plots\"", ":", "export_score_plots", "(", "infile", ")", "else", ":", "if", "outfile", "is", "None", ":", "if", "outcsv", ":", "outfile", "=", "infile", ".", "split", "(", "\".osw\"", ")", "[", "0", "]", "+", "\".csv\"", "else", ":", "outfile", "=", "infile", ".", "split", "(", "\".osw\"", ")", "[", "0", "]", "+", "\".tsv\"", "else", ":", "outfile", "=", "outfile", "export_compound_tsv", "(", "infile", ",", "outfile", ",", "format", ",", "outcsv", ",", "max_rs_peakgroup_qvalue", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
filter
Filter sqMass files
pyprophet/main.py
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)
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)
[ "Filter", "sqMass", "files" ]
PyProphet/pyprophet
python
https://github.com/PyProphet/pyprophet/blob/f546ad171750cd7685afbde6785fe71f82cadb35/pyprophet/main.py#L329-L334
[ "def", "filter", "(", "sqmassfiles", ",", "infile", ",", "max_precursor_pep", ",", "max_peakgroup_pep", ",", "max_transition_pep", ")", ":", "filter_sqmass", "(", "sqmassfiles", ",", "infile", ",", "max_precursor_pep", ",", "max_peakgroup_pep", ",", "max_transition_pep", ")" ]
f546ad171750cd7685afbde6785fe71f82cadb35
test
GWS.search_groups
Returns a list of restclients.GroupReference objects matching the passed parameters. Valid parameters are: name: parts_of_name name may include the wild-card (*) character. stem: group_stem member: member netid owner: admin netid instructor: instructor netid stem="course" will be set when this parameter is passed. student: student netid stem="course" will be set when this parameter is passed. affiliate: affiliate_name type: search_type Values are 'direct' to search for direct membership and 'effective' to search for effective memberships. Default is direct membership. scope: search_scope Values are 'one' to limit results to one level of stem name and 'all' to return all groups.
uw_gws/__init__.py
def search_groups(self, **kwargs): """ Returns a list of restclients.GroupReference objects matching the passed parameters. Valid parameters are: name: parts_of_name name may include the wild-card (*) character. stem: group_stem member: member netid owner: admin netid instructor: instructor netid stem="course" will be set when this parameter is passed. student: student netid stem="course" will be set when this parameter is passed. affiliate: affiliate_name type: search_type Values are 'direct' to search for direct membership and 'effective' to search for effective memberships. Default is direct membership. scope: search_scope Values are 'one' to limit results to one level of stem name and 'all' to return all groups. """ kwargs = dict((k.lower(), kwargs[k].lower()) for k in kwargs) if 'type' in kwargs and ( kwargs['type'] != 'direct' and kwargs['type'] != 'effective'): del(kwargs['type']) if 'scope' in kwargs and ( kwargs['scope'] != 'one' and kwargs['scope'] != 'all'): del(kwargs['scope']) if "instructor" in kwargs or "student" in kwargs: kwargs["stem"] = "course" url = "{}/search?{}".format(self.API, urlencode(kwargs)) data = self._get_resource(url) groups = [] for datum in data.get('data', []): group = GroupReference() group.uwregid = datum.get('regid') group.display_name = datum.get('displayName') group.name = datum.get('id') group.url = datum.get('url') groups.append(group) return groups
def search_groups(self, **kwargs): """ Returns a list of restclients.GroupReference objects matching the passed parameters. Valid parameters are: name: parts_of_name name may include the wild-card (*) character. stem: group_stem member: member netid owner: admin netid instructor: instructor netid stem="course" will be set when this parameter is passed. student: student netid stem="course" will be set when this parameter is passed. affiliate: affiliate_name type: search_type Values are 'direct' to search for direct membership and 'effective' to search for effective memberships. Default is direct membership. scope: search_scope Values are 'one' to limit results to one level of stem name and 'all' to return all groups. """ kwargs = dict((k.lower(), kwargs[k].lower()) for k in kwargs) if 'type' in kwargs and ( kwargs['type'] != 'direct' and kwargs['type'] != 'effective'): del(kwargs['type']) if 'scope' in kwargs and ( kwargs['scope'] != 'one' and kwargs['scope'] != 'all'): del(kwargs['scope']) if "instructor" in kwargs or "student" in kwargs: kwargs["stem"] = "course" url = "{}/search?{}".format(self.API, urlencode(kwargs)) data = self._get_resource(url) groups = [] for datum in data.get('data', []): group = GroupReference() group.uwregid = datum.get('regid') group.display_name = datum.get('displayName') group.name = datum.get('id') group.url = datum.get('url') groups.append(group) return groups
[ "Returns", "a", "list", "of", "restclients", ".", "GroupReference", "objects", "matching", "the", "passed", "parameters", ".", "Valid", "parameters", "are", ":", "name", ":", "parts_of_name", "name", "may", "include", "the", "wild", "-", "card", "(", "*", ")", "character", ".", "stem", ":", "group_stem", "member", ":", "member", "netid", "owner", ":", "admin", "netid", "instructor", ":", "instructor", "netid", "stem", "=", "course", "will", "be", "set", "when", "this", "parameter", "is", "passed", ".", "student", ":", "student", "netid", "stem", "=", "course", "will", "be", "set", "when", "this", "parameter", "is", "passed", ".", "affiliate", ":", "affiliate_name", "type", ":", "search_type", "Values", "are", "direct", "to", "search", "for", "direct", "membership", "and", "effective", "to", "search", "for", "effective", "memberships", ".", "Default", "is", "direct", "membership", ".", "scope", ":", "search_scope", "Values", "are", "one", "to", "limit", "results", "to", "one", "level", "of", "stem", "name", "and", "all", "to", "return", "all", "groups", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L31-L78
[ "def", "search_groups", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "dict", "(", "(", "k", ".", "lower", "(", ")", ",", "kwargs", "[", "k", "]", ".", "lower", "(", ")", ")", "for", "k", "in", "kwargs", ")", "if", "'type'", "in", "kwargs", "and", "(", "kwargs", "[", "'type'", "]", "!=", "'direct'", "and", "kwargs", "[", "'type'", "]", "!=", "'effective'", ")", ":", "del", "(", "kwargs", "[", "'type'", "]", ")", "if", "'scope'", "in", "kwargs", "and", "(", "kwargs", "[", "'scope'", "]", "!=", "'one'", "and", "kwargs", "[", "'scope'", "]", "!=", "'all'", ")", ":", "del", "(", "kwargs", "[", "'scope'", "]", ")", "if", "\"instructor\"", "in", "kwargs", "or", "\"student\"", "in", "kwargs", ":", "kwargs", "[", "\"stem\"", "]", "=", "\"course\"", "url", "=", "\"{}/search?{}\"", ".", "format", "(", "self", ".", "API", ",", "urlencode", "(", "kwargs", ")", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "groups", "=", "[", "]", "for", "datum", "in", "data", ".", "get", "(", "'data'", ",", "[", "]", ")", ":", "group", "=", "GroupReference", "(", ")", "group", ".", "uwregid", "=", "datum", ".", "get", "(", "'regid'", ")", "group", ".", "display_name", "=", "datum", ".", "get", "(", "'displayName'", ")", "group", ".", "name", "=", "datum", ".", "get", "(", "'id'", ")", "group", ".", "url", "=", "datum", ".", "get", "(", "'url'", ")", "groups", ".", "append", "(", "group", ")", "return", "groups" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
GWS.get_group_by_id
Returns a restclients.Group object for the group identified by the passed group ID.
uw_gws/__init__.py
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._group_from_json(data.get("data"))
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._group_from_json(data.get("data"))
[ "Returns", "a", "restclients", ".", "Group", "object", "for", "the", "group", "identified", "by", "the", "passed", "group", "ID", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L80-L91
[ "def", "get_group_by_id", "(", "self", ",", "group_id", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "url", "=", "\"{}/group/{}\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "return", "self", ".", "_group_from_json", "(", "data", ".", "get", "(", "\"data\"", ")", ")" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
GWS.create_group
Creates a group from the passed restclients.Group object.
uw_gws/__init__.py
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=body) return self._group_from_json(data.get("data"))
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=body) return self._group_from_json(data.get("data"))
[ "Creates", "a", "group", "from", "the", "passed", "restclients", ".", "Group", "object", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L93-L104
[ "def", "create_group", "(", "self", ",", "group", ")", ":", "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", "=", "body", ")", "return", "self", ".", "_group_from_json", "(", "data", ".", "get", "(", "\"data\"", ")", ")" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
GWS.delete_group
Deletes the group identified by the passed group ID.
uw_gws/__init__.py
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
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
[ "Deletes", "the", "group", "identified", "by", "the", "passed", "group", "ID", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L120-L130
[ "def", "delete_group", "(", "self", ",", "group_id", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "url", "=", "\"{}/group/{}\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ")", "self", ".", "_delete_resource", "(", "url", ")", "return", "True" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
GWS.get_members
Returns a list of restclients.GroupMember objects for the group identified by the passed group ID.
uw_gws/__init__.py
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) members = [] for datum in data.get("data"): members.append(self._group_member_from_json(datum)) return members
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) members = [] for datum in data.get("data"): members.append(self._group_member_from_json(datum)) return members
[ "Returns", "a", "list", "of", "restclients", ".", "GroupMember", "objects", "for", "the", "group", "identified", "by", "the", "passed", "group", "ID", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L132-L146
[ "def", "get_members", "(", "self", ",", "group_id", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "url", "=", "\"{}/group/{}/member\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "members", "=", "[", "]", "for", "datum", "in", "data", ".", "get", "(", "\"data\"", ")", ":", "members", ".", "append", "(", "self", ".", "_group_member_from_json", "(", "datum", ")", ")", "return", "members" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
GWS.update_members
Updates the membership of the group represented by the passed group id. Returns a list of members not found.
uw_gws/__init__.py
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": "*"} url = "{}/group/{}/member".format(self.API, group_id) data = self._put_resource(url, headers, body) errors = data.get("errors", []) if len(errors): return errors[0].get("notFound", []) return []
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": "*"} url = "{}/group/{}/member".format(self.API, group_id) data = self._put_resource(url, headers, body) errors = data.get("errors", []) if len(errors): return errors[0].get("notFound", []) return []
[ "Updates", "the", "membership", "of", "the", "group", "represented", "by", "the", "passed", "group", "id", ".", "Returns", "a", "list", "of", "members", "not", "found", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L148-L164
[ "def", "update_members", "(", "self", ",", "group_id", ",", "members", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "body", "=", "{", "\"data\"", ":", "[", "m", ".", "json_data", "(", ")", "for", "m", "in", "members", "]", "}", "headers", "=", "{", "\"If-Match\"", ":", "\"*\"", "}", "url", "=", "\"{}/group/{}/member\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ")", "data", "=", "self", ".", "_put_resource", "(", "url", ",", "headers", ",", "body", ")", "errors", "=", "data", ".", "get", "(", "\"errors\"", ",", "[", "]", ")", "if", "len", "(", "errors", ")", ":", "return", "errors", "[", "0", "]", ".", "get", "(", "\"notFound\"", ",", "[", "]", ")", "return", "[", "]" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
GWS.get_effective_member_count
Returns a count of effective members for the group identified by the passed group ID.
uw_gws/__init__.py
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, group_id) data = self._get_resource(url) count = data.get("data").get("count") return int(count)
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, group_id) data = self._get_resource(url) count = data.get("data").get("count") return int(count)
[ "Returns", "a", "count", "of", "effective", "members", "for", "the", "group", "identified", "by", "the", "passed", "group", "ID", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L182-L195
[ "def", "get_effective_member_count", "(", "self", ",", "group_id", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "url", "=", "\"{}/group/{}/effective_member?view=count\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ")", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "count", "=", "data", ".", "get", "(", "\"data\"", ")", ".", "get", "(", "\"count\"", ")", "return", "int", "(", "count", ")" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
GWS.is_effective_member
Returns True if the netid is in the group, False otherwise.
uw_gws/__init__.py
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) url = "{}/group/{}/effective_member/{}".format(self.API, group_id, netid) try: data = self._get_resource(url) return True # 200 except DataFailureException as ex: if ex.status == 404: return False else: raise
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) url = "{}/group/{}/effective_member/{}".format(self.API, group_id, netid) try: data = self._get_resource(url) return True # 200 except DataFailureException as ex: if ex.status == 404: return False else: raise
[ "Returns", "True", "if", "the", "netid", "is", "in", "the", "group", "False", "otherwise", "." ]
uw-it-aca/uw-restclients-gws
python
https://github.com/uw-it-aca/uw-restclients-gws/blob/2aa6038d5f83027bae680e52fc38c2ec0cd192c5/uw_gws/__init__.py#L197-L217
[ "def", "is_effective_member", "(", "self", ",", "group_id", ",", "netid", ")", ":", "self", ".", "_valid_group_id", "(", "group_id", ")", "# GWS doesn't accept EPPNs on effective member checks, for UW users", "netid", "=", "re", ".", "sub", "(", "'@washington.edu'", ",", "''", ",", "netid", ")", "url", "=", "\"{}/group/{}/effective_member/{}\"", ".", "format", "(", "self", ".", "API", ",", "group_id", ",", "netid", ")", "try", ":", "data", "=", "self", ".", "_get_resource", "(", "url", ")", "return", "True", "# 200", "except", "DataFailureException", "as", "ex", ":", "if", "ex", ".", "status", "==", "404", ":", "return", "False", "else", ":", "raise" ]
2aa6038d5f83027bae680e52fc38c2ec0cd192c5
test
modify_conf
pip install redbaron
make_rtd.py
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 = red.find('name', value='extensions').parent ext_node.value.value.extend(extra_extensions) # Overwrite theme to read-the-docs theme_node = red.find('name', value='html_theme').parent theme_node.value.value = '"sphinx_rtd_theme"' ub.writeto(conf_path, red.dumps())
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 = red.find('name', value='extensions').parent ext_node.value.value.extend(extra_extensions) # Overwrite theme to read-the-docs theme_node = red.find('name', value='html_theme').parent theme_node.value.value = '"sphinx_rtd_theme"' ub.writeto(conf_path, red.dumps())
[ "pip", "install", "redbaron" ]
Erotemic/xdoctest
python
https://github.com/Erotemic/xdoctest/blob/1c85209498bcf3791c919985b3d1904ec2339768/make_rtd.py#L42-L65
[ "def", "modify_conf", "(", ")", ":", "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", "=", "red", ".", "find", "(", "'name'", ",", "value", "=", "'extensions'", ")", ".", "parent", "ext_node", ".", "value", ".", "value", ".", "extend", "(", "extra_extensions", ")", "# Overwrite theme to read-the-docs", "theme_node", "=", "red", ".", "find", "(", "'name'", ",", "value", "=", "'html_theme'", ")", ".", "parent", "theme_node", ".", "value", ".", "value", "=", "'\"sphinx_rtd_theme\"'", "ub", ".", "writeto", "(", "conf_path", ",", "red", ".", "dumps", "(", ")", ")" ]
1c85209498bcf3791c919985b3d1904ec2339768
test
parse_version
Statically parse the version number from __init__.py
setup.py
def parse_version(): """ Statically parse the version number from __init__.py """ from os.path import dirname, join import ast modname = setupkw['name'] init_fpath = join(dirname(__file__), modname, '__init__.py') with open(init_fpath) as file_: sourcecode = file_.read() pt = ast.parse(sourcecode) class VersionVisitor(ast.NodeVisitor): def visit_Assign(self, node): for target in node.targets: if target.id == '__version__': self.version = node.value.s visitor = VersionVisitor() visitor.visit(pt) return visitor.version
def parse_version(): """ Statically parse the version number from __init__.py """ from os.path import dirname, join import ast modname = setupkw['name'] init_fpath = join(dirname(__file__), modname, '__init__.py') with open(init_fpath) as file_: sourcecode = file_.read() pt = ast.parse(sourcecode) class VersionVisitor(ast.NodeVisitor): def visit_Assign(self, node): for target in node.targets: if target.id == '__version__': self.version = node.value.s visitor = VersionVisitor() visitor.visit(pt) return visitor.version
[ "Statically", "parse", "the", "version", "number", "from", "__init__", ".", "py" ]
Erotemic/xdoctest
python
https://github.com/Erotemic/xdoctest/blob/1c85209498bcf3791c919985b3d1904ec2339768/setup.py#L56-L72
[ "def", "parse_version", "(", ")", ":", "from", "os", ".", "path", "import", "dirname", ",", "join", "import", "ast", "modname", "=", "setupkw", "[", "'name'", "]", "init_fpath", "=", "join", "(", "dirname", "(", "__file__", ")", ",", "modname", ",", "'__init__.py'", ")", "with", "open", "(", "init_fpath", ")", "as", "file_", ":", "sourcecode", "=", "file_", ".", "read", "(", ")", "pt", "=", "ast", ".", "parse", "(", "sourcecode", ")", "class", "VersionVisitor", "(", "ast", ".", "NodeVisitor", ")", ":", "def", "visit_Assign", "(", "self", ",", "node", ")", ":", "for", "target", "in", "node", ".", "targets", ":", "if", "target", ".", "id", "==", "'__version__'", ":", "self", ".", "version", "=", "node", ".", "value", ".", "s", "visitor", "=", "VersionVisitor", "(", ")", "visitor", ".", "visit", "(", "pt", ")", "return", "visitor", ".", "version" ]
1c85209498bcf3791c919985b3d1904ec2339768
test
Group.create_dataset
Create 3 datasets in a group to represent the sparse array. Parameters ---------- sparse_format:
h5sparse/h5sparse.py
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_format: """ if isinstance(data, Dataset): assert sparse_format is None group = self.create_group(name) group.attrs['h5sparse_format'] = data.attrs['h5sparse_format'] group.attrs['h5sparse_shape'] = data.attrs['h5sparse_shape'] group.create_dataset('data', data=data.h5py_group['data'], dtype=dtype, **kwargs) group.create_dataset('indices', data=data.h5py_group['indices'], dtype=indices_dtype, **kwargs) group.create_dataset('indptr', data=data.h5py_group['indptr'], dtype=indptr_dtype, **kwargs) elif ss.issparse(data): if sparse_format is not None: format_class = get_format_class(sparse_format) data = format_class(data) group = self.create_group(name) group.attrs['h5sparse_format'] = get_format_str(data) group.attrs['h5sparse_shape'] = data.shape group.create_dataset('data', data=data.data, dtype=dtype, **kwargs) group.create_dataset('indices', data=data.indices, dtype=indices_dtype, **kwargs) group.create_dataset('indptr', data=data.indptr, dtype=indptr_dtype, **kwargs) elif data is None and sparse_format is not None: format_class = get_format_class(sparse_format) if dtype is None: dtype = np.float64 if shape is None: shape = (0, 0) data = format_class(shape, dtype=dtype) group = self.create_group(name) group.attrs['h5sparse_format'] = get_format_str(data) group.attrs['h5sparse_shape'] = data.shape group.create_dataset('data', data=data.data, dtype=dtype, **kwargs) group.create_dataset('indices', data=data.indices, dtype=indices_dtype, **kwargs) group.create_dataset('indptr', data=data.indptr, dtype=indptr_dtype, **kwargs) else: # forward the arguments to h5py assert sparse_format is None return super(Group, self).create_dataset( name, data=data, shape=shape, dtype=dtype, **kwargs) return Dataset(group)
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_format: """ if isinstance(data, Dataset): assert sparse_format is None group = self.create_group(name) group.attrs['h5sparse_format'] = data.attrs['h5sparse_format'] group.attrs['h5sparse_shape'] = data.attrs['h5sparse_shape'] group.create_dataset('data', data=data.h5py_group['data'], dtype=dtype, **kwargs) group.create_dataset('indices', data=data.h5py_group['indices'], dtype=indices_dtype, **kwargs) group.create_dataset('indptr', data=data.h5py_group['indptr'], dtype=indptr_dtype, **kwargs) elif ss.issparse(data): if sparse_format is not None: format_class = get_format_class(sparse_format) data = format_class(data) group = self.create_group(name) group.attrs['h5sparse_format'] = get_format_str(data) group.attrs['h5sparse_shape'] = data.shape group.create_dataset('data', data=data.data, dtype=dtype, **kwargs) group.create_dataset('indices', data=data.indices, dtype=indices_dtype, **kwargs) group.create_dataset('indptr', data=data.indptr, dtype=indptr_dtype, **kwargs) elif data is None and sparse_format is not None: format_class = get_format_class(sparse_format) if dtype is None: dtype = np.float64 if shape is None: shape = (0, 0) data = format_class(shape, dtype=dtype) group = self.create_group(name) group.attrs['h5sparse_format'] = get_format_str(data) group.attrs['h5sparse_shape'] = data.shape group.create_dataset('data', data=data.data, dtype=dtype, **kwargs) group.create_dataset('indices', data=data.indices, dtype=indices_dtype, **kwargs) group.create_dataset('indptr', data=data.indptr, dtype=indptr_dtype, **kwargs) else: # forward the arguments to h5py assert sparse_format is None return super(Group, self).create_dataset( name, data=data, shape=shape, dtype=dtype, **kwargs) return Dataset(group)
[ "Create", "3", "datasets", "in", "a", "group", "to", "represent", "the", "sparse", "array", "." ]
appier/h5sparse
python
https://github.com/appier/h5sparse/blob/b12ee65c624207d3020c283ce561cfcc7ab71731/h5sparse/h5sparse.py#L46-L94
[ "def", "create_dataset", "(", "self", ",", "name", ",", "shape", "=", "None", ",", "dtype", "=", "None", ",", "data", "=", "None", ",", "sparse_format", "=", "None", ",", "indptr_dtype", "=", "np", ".", "int64", ",", "indices_dtype", "=", "np", ".", "int32", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "data", ",", "Dataset", ")", ":", "assert", "sparse_format", "is", "None", "group", "=", "self", ".", "create_group", "(", "name", ")", "group", ".", "attrs", "[", "'h5sparse_format'", "]", "=", "data", ".", "attrs", "[", "'h5sparse_format'", "]", "group", ".", "attrs", "[", "'h5sparse_shape'", "]", "=", "data", ".", "attrs", "[", "'h5sparse_shape'", "]", "group", ".", "create_dataset", "(", "'data'", ",", "data", "=", "data", ".", "h5py_group", "[", "'data'", "]", ",", "dtype", "=", "dtype", ",", "*", "*", "kwargs", ")", "group", ".", "create_dataset", "(", "'indices'", ",", "data", "=", "data", ".", "h5py_group", "[", "'indices'", "]", ",", "dtype", "=", "indices_dtype", ",", "*", "*", "kwargs", ")", "group", ".", "create_dataset", "(", "'indptr'", ",", "data", "=", "data", ".", "h5py_group", "[", "'indptr'", "]", ",", "dtype", "=", "indptr_dtype", ",", "*", "*", "kwargs", ")", "elif", "ss", ".", "issparse", "(", "data", ")", ":", "if", "sparse_format", "is", "not", "None", ":", "format_class", "=", "get_format_class", "(", "sparse_format", ")", "data", "=", "format_class", "(", "data", ")", "group", "=", "self", ".", "create_group", "(", "name", ")", "group", ".", "attrs", "[", "'h5sparse_format'", "]", "=", "get_format_str", "(", "data", ")", "group", ".", "attrs", "[", "'h5sparse_shape'", "]", "=", "data", ".", "shape", "group", ".", "create_dataset", "(", "'data'", ",", "data", "=", "data", ".", "data", ",", "dtype", "=", "dtype", ",", "*", "*", "kwargs", ")", "group", ".", "create_dataset", "(", "'indices'", ",", "data", "=", "data", ".", "indices", ",", "dtype", "=", "indices_dtype", ",", "*", "*", "kwargs", ")", "group", ".", "create_dataset", "(", "'indptr'", ",", "data", "=", "data", ".", "indptr", ",", "dtype", "=", "indptr_dtype", ",", "*", "*", "kwargs", ")", "elif", "data", "is", "None", "and", "sparse_format", "is", "not", "None", ":", "format_class", "=", "get_format_class", "(", "sparse_format", ")", "if", "dtype", "is", "None", ":", "dtype", "=", "np", ".", "float64", "if", "shape", "is", "None", ":", "shape", "=", "(", "0", ",", "0", ")", "data", "=", "format_class", "(", "shape", ",", "dtype", "=", "dtype", ")", "group", "=", "self", ".", "create_group", "(", "name", ")", "group", ".", "attrs", "[", "'h5sparse_format'", "]", "=", "get_format_str", "(", "data", ")", "group", ".", "attrs", "[", "'h5sparse_shape'", "]", "=", "data", ".", "shape", "group", ".", "create_dataset", "(", "'data'", ",", "data", "=", "data", ".", "data", ",", "dtype", "=", "dtype", ",", "*", "*", "kwargs", ")", "group", ".", "create_dataset", "(", "'indices'", ",", "data", "=", "data", ".", "indices", ",", "dtype", "=", "indices_dtype", ",", "*", "*", "kwargs", ")", "group", ".", "create_dataset", "(", "'indptr'", ",", "data", "=", "data", ".", "indptr", ",", "dtype", "=", "indptr_dtype", ",", "*", "*", "kwargs", ")", "else", ":", "# forward the arguments to h5py", "assert", "sparse_format", "is", "None", "return", "super", "(", "Group", ",", "self", ")", ".", "create_dataset", "(", "name", ",", "data", "=", "data", ",", "shape", "=", "shape", ",", "dtype", "=", "dtype", ",", "*", "*", "kwargs", ")", "return", "Dataset", "(", "group", ")" ]
b12ee65c624207d3020c283ce561cfcc7ab71731
test
cli_decrypt
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.
swiftly/cli/decrypt.py
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: with context.io_manager.with_stdin() as stdin: crypt_type = stdin.read(1) if crypt_type == AES256CBC: for chunk in aes_decrypt(key, stdin): stdout.write(chunk) stdout.flush() else: raise ReturnCode( 'contents encrypted with unsupported type %r' % crypt_type)
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: with context.io_manager.with_stdin() as stdin: crypt_type = stdin.read(1) if crypt_type == AES256CBC: for chunk in aes_decrypt(key, stdin): stdout.write(chunk) stdout.flush() else: raise ReturnCode( 'contents encrypted with unsupported type %r' % crypt_type)
[ "Decrypts", "context", ".", "io_manager", "s", "stdin", "and", "sends", "that", "to", "context", ".", "io_manager", "s", "stdout", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/decrypt.py#L31-L49
[ "def", "cli_decrypt", "(", "context", ",", "key", ")", ":", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "stdout", ":", "with", "context", ".", "io_manager", ".", "with_stdin", "(", ")", "as", "stdin", ":", "crypt_type", "=", "stdin", ".", "read", "(", "1", ")", "if", "crypt_type", "==", "AES256CBC", ":", "for", "chunk", "in", "aes_decrypt", "(", "key", ",", "stdin", ")", ":", "stdout", ".", "write", "(", "chunk", ")", "stdout", ".", "flush", "(", ")", "else", ":", "raise", "ReturnCode", "(", "'contents encrypted with unsupported type %r'", "%", "crypt_type", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Concurrency.spawn
Returns immediately to the caller and begins executing the func in the background. Use get_results and the ident given to retrieve the results of the func. If the func causes an exception, this exception will be caught and the sys.exc_info() will be returned via get_results. :param ident: An identifier to find the results of the func from get_results. This identifier can be anything unique to the Concurrency instance. :param func: The function to execute concurrently. :param args: The args to give the func. :param kwargs: The keyword args to the give the func. :returns: None
swiftly/concurrency.py
def spawn(self, ident, func, *args, **kwargs): """ Returns immediately to the caller and begins executing the func in the background. Use get_results and the ident given to retrieve the results of the func. If the func causes an exception, this exception will be caught and the sys.exc_info() will be returned via get_results. :param ident: An identifier to find the results of the func from get_results. This identifier can be anything unique to the Concurrency instance. :param func: The function to execute concurrently. :param args: The args to give the func. :param kwargs: The keyword args to the give the func. :returns: None """ if self._pool: self._pool.spawn_n(self._spawner, ident, func, *args, **kwargs) sleep() else: self._spawner(ident, func, *args, **kwargs)
def spawn(self, ident, func, *args, **kwargs): """ Returns immediately to the caller and begins executing the func in the background. Use get_results and the ident given to retrieve the results of the func. If the func causes an exception, this exception will be caught and the sys.exc_info() will be returned via get_results. :param ident: An identifier to find the results of the func from get_results. This identifier can be anything unique to the Concurrency instance. :param func: The function to execute concurrently. :param args: The args to give the func. :param kwargs: The keyword args to the give the func. :returns: None """ if self._pool: self._pool.spawn_n(self._spawner, ident, func, *args, **kwargs) sleep() else: self._spawner(ident, func, *args, **kwargs)
[ "Returns", "immediately", "to", "the", "caller", "and", "begins", "executing", "the", "func", "in", "the", "background", ".", "Use", "get_results", "and", "the", "ident", "given", "to", "retrieve", "the", "results", "of", "the", "func", ".", "If", "the", "func", "causes", "an", "exception", "this", "exception", "will", "be", "caught", "and", "the", "sys", ".", "exc_info", "()", "will", "be", "returned", "via", "get_results", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/concurrency.py#L57-L77
[ "def", "spawn", "(", "self", ",", "ident", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_pool", ":", "self", ".", "_pool", ".", "spawn_n", "(", "self", ".", "_spawner", ",", "ident", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", "sleep", "(", ")", "else", ":", "self", ".", "_spawner", "(", "ident", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Concurrency.get_results
Returns a dict of the results currently available. The keys are the ident values given with the calls to spawn. The values are tuples of (exc_type, exc_value, exc_tb, result) where: ========= ============================================ exc_type The type of any exception raised. exc_value The actual exception if any was raised. exc_tb The traceback if any exception was raised. result If no exception was raised, this will be the return value of the called function. ========= ============================================
swiftly/concurrency.py
def get_results(self): """ Returns a dict of the results currently available. The keys are the ident values given with the calls to spawn. The values are tuples of (exc_type, exc_value, exc_tb, result) where: ========= ============================================ exc_type The type of any exception raised. exc_value The actual exception if any was raised. exc_tb The traceback if any exception was raised. result If no exception was raised, this will be the return value of the called function. ========= ============================================ """ try: while True: ident, value = self._queue.get(block=False) self._results[ident] = value except queue.Empty: pass return self._results
def get_results(self): """ Returns a dict of the results currently available. The keys are the ident values given with the calls to spawn. The values are tuples of (exc_type, exc_value, exc_tb, result) where: ========= ============================================ exc_type The type of any exception raised. exc_value The actual exception if any was raised. exc_tb The traceback if any exception was raised. result If no exception was raised, this will be the return value of the called function. ========= ============================================ """ try: while True: ident, value = self._queue.get(block=False) self._results[ident] = value except queue.Empty: pass return self._results
[ "Returns", "a", "dict", "of", "the", "results", "currently", "available", ".", "The", "keys", "are", "the", "ident", "values", "given", "with", "the", "calls", "to", "spawn", ".", "The", "values", "are", "tuples", "of", "(", "exc_type", "exc_value", "exc_tb", "result", ")", "where", ":" ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/concurrency.py#L79-L100
[ "def", "get_results", "(", "self", ")", ":", "try", ":", "while", "True", ":", "ident", ",", "value", "=", "self", ".", "_queue", ".", "get", "(", "block", "=", "False", ")", "self", ".", "_results", "[", "ident", "]", "=", "value", "except", "queue", ".", "Empty", ":", "pass", "return", "self", ".", "_results" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.client_path_to_os_path
Converts a client path into the operating system's path by replacing instances of '/' with os.path.sep. Note: If the client path contains any instances of os.path.sep already, they will be replaced with '-'.
swiftly/cli/iomanager.py
def client_path_to_os_path(self, client_path): """ Converts a client path into the operating system's path by replacing instances of '/' with os.path.sep. Note: If the client path contains any instances of os.path.sep already, they will be replaced with '-'. """ if os.path.sep == '/': return client_path return client_path.replace(os.path.sep, '-').replace('/', os.path.sep)
def client_path_to_os_path(self, client_path): """ Converts a client path into the operating system's path by replacing instances of '/' with os.path.sep. Note: If the client path contains any instances of os.path.sep already, they will be replaced with '-'. """ if os.path.sep == '/': return client_path return client_path.replace(os.path.sep, '-').replace('/', os.path.sep)
[ "Converts", "a", "client", "path", "into", "the", "operating", "system", "s", "path", "by", "replacing", "instances", "of", "/", "with", "os", ".", "path", ".", "sep", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L86-L96
[ "def", "client_path_to_os_path", "(", "self", ",", "client_path", ")", ":", "if", "os", ".", "path", ".", "sep", "==", "'/'", ":", "return", "client_path", "return", "client_path", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'-'", ")", ".", "replace", "(", "'/'", ",", "os", ".", "path", ".", "sep", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.os_path_to_client_path
Converts an operating system path into a client path by replacing instances of os.path.sep with '/'. Note: If the client path contains any instances of '/' already, they will be replaced with '-'.
swiftly/cli/iomanager.py
def os_path_to_client_path(self, os_path): """ Converts an operating system path into a client path by replacing instances of os.path.sep with '/'. Note: If the client path contains any instances of '/' already, they will be replaced with '-'. """ if os.path.sep == '/': return os_path return os_path.replace('/', '-').replace(os.path.sep, '/')
def os_path_to_client_path(self, os_path): """ Converts an operating system path into a client path by replacing instances of os.path.sep with '/'. Note: If the client path contains any instances of '/' already, they will be replaced with '-'. """ if os.path.sep == '/': return os_path return os_path.replace('/', '-').replace(os.path.sep, '/')
[ "Converts", "an", "operating", "system", "path", "into", "a", "client", "path", "by", "replacing", "instances", "of", "os", ".", "path", ".", "sep", "with", "/", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L98-L108
[ "def", "os_path_to_client_path", "(", "self", ",", "os_path", ")", ":", "if", "os", ".", "path", ".", "sep", "==", "'/'", ":", "return", "os_path", "return", "os_path", ".", "replace", "(", "'/'", ",", "'-'", ")", ".", "replace", "(", "os", ".", "path", ".", "sep", ",", "'/'", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.get_stdin
Returns a stdin-suitable file-like object based on the optional os_path and optionally skipping any configured sub-command.
swiftly/cli/iomanager.py
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, path = self._get_in_and_path( self.stdin, self.stdin_root, sub_command, os_path) if hasattr(inn, 'stdout'): return inn.stdout return inn
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, path = self._get_in_and_path( self.stdin, self.stdin_root, sub_command, os_path) if hasattr(inn, 'stdout'): return inn.stdout return inn
[ "Returns", "a", "stdin", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L149-L160
[ "def", "get_stdin", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "stdin_sub_command", "inn", ",", "path", "=", "self", ".", "_get_in_and_path", "(", "self", ".", "stdin", ",", "self", ".", "stdin_root", ",", "sub_command", ",", "os_path", ")", "if", "hasattr", "(", "inn", ",", "'stdout'", ")", ":", "return", "inn", ".", "stdout", "return", "inn" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.get_stdout
Returns a stdout-suitable file-like object based on the optional os_path and optionally skipping any configured sub-command.
swiftly/cli/iomanager.py
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, path = self._get_out_and_path( self.stdout, self.stdout_root, sub_command, os_path) if hasattr(out, 'stdin'): return out.stdin return out
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, path = self._get_out_and_path( self.stdout, self.stdout_root, sub_command, os_path) if hasattr(out, 'stdin'): return out.stdin return out
[ "Returns", "a", "stdout", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L162-L173
[ "def", "get_stdout", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "stdout_sub_command", "out", ",", "path", "=", "self", ".", "_get_out_and_path", "(", "self", ".", "stdout", ",", "self", ".", "stdout_root", ",", "sub_command", ",", "os_path", ")", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "return", "out", ".", "stdin", "return", "out" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.get_stderr
Returns a stderr-suitable file-like object based on the optional os_path and optionally skipping any configured sub-command.
swiftly/cli/iomanager.py
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, path = self._get_out_and_path( self.stderr, self.stderr_root, sub_command, os_path) if hasattr(out, 'stdin'): return out.stdin return out
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, path = self._get_out_and_path( self.stderr, self.stderr_root, sub_command, os_path) if hasattr(out, 'stdin'): return out.stdin return out
[ "Returns", "a", "stderr", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L175-L186
[ "def", "get_stderr", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "stderr_sub_command", "out", ",", "path", "=", "self", ".", "_get_out_and_path", "(", "self", ".", "stderr", ",", "self", ".", "stderr_root", ",", "sub_command", ",", "os_path", ")", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "return", "out", ".", "stdin", "return", "out" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.get_debug
Returns a debug-output-suitable file-like object based on the optional os_path and optionally skipping any configured sub-command.
swiftly/cli/iomanager.py
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 out, path = self._get_out_and_path( self.debug, self.debug_root, sub_command, os_path) if hasattr(out, 'stdin'): return out.stdin return out
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 out, path = self._get_out_and_path( self.debug, self.debug_root, sub_command, os_path) if hasattr(out, 'stdin'): return out.stdin return out
[ "Returns", "a", "debug", "-", "output", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L188-L199
[ "def", "get_debug", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "debug_sub_command", "out", ",", "path", "=", "self", ".", "_get_out_and_path", "(", "self", ".", "debug", ",", "self", ".", "debug_root", ",", "sub_command", ",", "os_path", ")", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "return", "out", ".", "stdin", "return", "out" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.with_stdin
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 path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it.
swiftly/cli/iomanager.py
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 path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.stdin_sub_command inn, path = self._get_in_and_path( self.stdin, self.stdin_root, sub_command, os_path) try: if hasattr(inn, 'stdout'): yield inn.stdout else: yield inn finally: if hasattr(inn, 'stdout'): self._close(inn.stdout) self._wait(inn, path) self._close(inn) if disk_closed_callback and path: disk_closed_callback(path)
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 path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.stdin_sub_command inn, path = self._get_in_and_path( self.stdin, self.stdin_root, sub_command, os_path) try: if hasattr(inn, 'stdout'): yield inn.stdout else: yield inn finally: if hasattr(inn, 'stdout'): self._close(inn.stdout) self._wait(inn, path) self._close(inn) if disk_closed_callback and path: disk_closed_callback(path)
[ "A", "context", "manager", "yielding", "a", "stdin", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L221-L251
[ "def", "with_stdin", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ",", "disk_closed_callback", "=", "None", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "stdin_sub_command", "inn", ",", "path", "=", "self", ".", "_get_in_and_path", "(", "self", ".", "stdin", ",", "self", ".", "stdin_root", ",", "sub_command", ",", "os_path", ")", "try", ":", "if", "hasattr", "(", "inn", ",", "'stdout'", ")", ":", "yield", "inn", ".", "stdout", "else", ":", "yield", "inn", "finally", ":", "if", "hasattr", "(", "inn", ",", "'stdout'", ")", ":", "self", ".", "_close", "(", "inn", ".", "stdout", ")", "self", ".", "_wait", "(", "inn", ",", "path", ")", "self", ".", "_close", "(", "inn", ")", "if", "disk_closed_callback", "and", "path", ":", "disk_closed_callback", "(", "path", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.with_stdout
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it.
swiftly/cli/iomanager.py
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.stdout_sub_command out, path = self._get_out_and_path( self.stdout, self.stdout_root, sub_command, os_path) try: if hasattr(out, 'stdin'): yield out.stdin else: yield out finally: if hasattr(out, 'stdin'): self._close(out.stdin) self._wait(out, path) self._close(out) if disk_closed_callback and path: disk_closed_callback(path)
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.stdout_sub_command out, path = self._get_out_and_path( self.stdout, self.stdout_root, sub_command, os_path) try: if hasattr(out, 'stdin'): yield out.stdin else: yield out finally: if hasattr(out, 'stdin'): self._close(out.stdin) self._wait(out, path) self._close(out) if disk_closed_callback and path: disk_closed_callback(path)
[ "A", "context", "manager", "yielding", "a", "stdout", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L254-L284
[ "def", "with_stdout", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ",", "disk_closed_callback", "=", "None", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "stdout_sub_command", "out", ",", "path", "=", "self", ".", "_get_out_and_path", "(", "self", ".", "stdout", ",", "self", ".", "stdout_root", ",", "sub_command", ",", "os_path", ")", "try", ":", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "yield", "out", ".", "stdin", "else", ":", "yield", "out", "finally", ":", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "self", ".", "_close", "(", "out", ".", "stdin", ")", "self", ".", "_wait", "(", "out", ",", "path", ")", "self", ".", "_close", "(", "out", ")", "if", "disk_closed_callback", "and", "path", ":", "disk_closed_callback", "(", "path", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.with_stderr
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it.
swiftly/cli/iomanager.py
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.stderr_sub_command out, path = self._get_out_and_path( self.stderr, self.stderr_root, sub_command, os_path) try: if hasattr(out, 'stdin'): yield out.stdin else: yield out finally: if hasattr(out, 'stdin'): self._close(out.stdin) self._wait(out, path) self._close(out) if disk_closed_callback and path: disk_closed_callback(path)
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.stderr_sub_command out, path = self._get_out_and_path( self.stderr, self.stderr_root, sub_command, os_path) try: if hasattr(out, 'stdin'): yield out.stdin else: yield out finally: if hasattr(out, 'stdin'): self._close(out.stdin) self._wait(out, path) self._close(out) if disk_closed_callback and path: disk_closed_callback(path)
[ "A", "context", "manager", "yielding", "a", "stderr", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L287-L317
[ "def", "with_stderr", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ",", "disk_closed_callback", "=", "None", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "stderr_sub_command", "out", ",", "path", "=", "self", ".", "_get_out_and_path", "(", "self", ".", "stderr", ",", "self", ".", "stderr_root", ",", "sub_command", ",", "os_path", ")", "try", ":", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "yield", "out", ".", "stdin", "else", ":", "yield", "out", "finally", ":", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "self", ".", "_close", "(", "out", ".", "stdin", ")", "self", ".", "_wait", "(", "out", ",", "path", ")", "self", ".", "_close", "(", "out", ")", "if", "disk_closed_callback", "and", "path", ":", "disk_closed_callback", "(", "path", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
IOManager.with_debug
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it.
swiftly/cli/iomanager.py
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.debug_sub_command out, path = self._get_out_and_path( self.debug, self.debug_root, sub_command, os_path) try: if hasattr(out, 'stdin'): yield out.stdin else: yield out finally: if hasattr(out, 'stdin'): self._close(out.stdin) self._wait(out, path) self._close(out) if disk_closed_callback and path: disk_closed_callback(path)
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: Optional path to base the file-like object on. :param skip_sub_command: Set True to skip any configured sub-command filter. :param disk_closed_callback: If the backing of the file-like object is an actual file that will be closed, disk_closed_callback (if set) will be called with the on-disk path just after closing it. """ sub_command = None if skip_sub_command else self.debug_sub_command out, path = self._get_out_and_path( self.debug, self.debug_root, sub_command, os_path) try: if hasattr(out, 'stdin'): yield out.stdin else: yield out finally: if hasattr(out, 'stdin'): self._close(out.stdin) self._wait(out, path) self._close(out) if disk_closed_callback and path: disk_closed_callback(path)
[ "A", "context", "manager", "yielding", "a", "debug", "-", "output", "-", "suitable", "file", "-", "like", "object", "based", "on", "the", "optional", "os_path", "and", "optionally", "skipping", "any", "configured", "sub", "-", "command", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/iomanager.py#L320-L350
[ "def", "with_debug", "(", "self", ",", "os_path", "=", "None", ",", "skip_sub_command", "=", "False", ",", "disk_closed_callback", "=", "None", ")", ":", "sub_command", "=", "None", "if", "skip_sub_command", "else", "self", ".", "debug_sub_command", "out", ",", "path", "=", "self", ".", "_get_out_and_path", "(", "self", ".", "debug", ",", "self", ".", "debug_root", ",", "sub_command", ",", "os_path", ")", "try", ":", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "yield", "out", ".", "stdin", "else", ":", "yield", "out", "finally", ":", "if", "hasattr", "(", "out", ",", "'stdin'", ")", ":", "self", ".", "_close", "(", "out", ".", "stdin", ")", "self", ".", "_wait", "(", "out", ",", "path", ")", "self", ".", "_close", "(", "out", ")", "if", "disk_closed_callback", "and", "path", ":", "disk_closed_callback", "(", "path", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_empty_account
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 objects revert to previous versions or if new objects or containers otherwise arise during the process, the account may not be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty and delete the containers. Note until_empty=True could run forever if something else is making new items faster than they're being deleted. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information.
swiftly/cli/delete.py
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 objects revert to previous versions or if new objects or containers otherwise arise during the process, the account may not be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty and delete the containers. Note until_empty=True could run forever if something else is making new items faster than they're being deleted. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information. """ if not yes_empty_account: raise ReturnCode( 'called cli_empty_account without setting yes_empty_account=True') marker = None while True: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( marker=marker, headers=context.headers, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode('listing account: %s %s' % (status, reason)) if not contents: if until_empty and marker: marker = None continue break for item in contents: cli_delete( context, item['name'], context.headers, recursive=True) marker = item['name']
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 objects revert to previous versions or if new objects or containers otherwise arise during the process, the account may not be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty and delete the containers. Note until_empty=True could run forever if something else is making new items faster than they're being deleted. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information. """ if not yes_empty_account: raise ReturnCode( 'called cli_empty_account without setting yes_empty_account=True') marker = None while True: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( marker=marker, headers=context.headers, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode('listing account: %s %s' % (status, reason)) if not contents: if until_empty and marker: marker = None continue break for item in contents: cli_delete( context, item['name'], context.headers, recursive=True) marker = item['name']
[ "Deletes", "all", "objects", "and", "containers", "in", "the", "account", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/delete.py#L38-L80
[ "def", "cli_empty_account", "(", "context", ",", "yes_empty_account", "=", "False", ",", "until_empty", "=", "False", ")", ":", "if", "not", "yes_empty_account", ":", "raise", "ReturnCode", "(", "'called cli_empty_account without setting yes_empty_account=True'", ")", "marker", "=", "None", "while", "True", ":", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_account", "(", "marker", "=", "marker", ",", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "raise", "ReturnCode", "(", "'listing account: %s %s'", "%", "(", "status", ",", "reason", ")", ")", "if", "not", "contents", ":", "if", "until_empty", "and", "marker", ":", "marker", "=", "None", "continue", "break", "for", "item", "in", "contents", ":", "cli_delete", "(", "context", ",", "item", "[", "'name'", "]", ",", "context", ".", "headers", ",", "recursive", "=", "True", ")", "marker", "=", "item", "[", "'name'", "]" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_empty_container
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 be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty the container. Note until_empty=True could run forever if something else is making new objects faster than they're being deleted. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information.
swiftly/cli/delete.py
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 be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty the container. Note until_empty=True could run forever if something else is making new objects faster than they're being deleted. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information. """ path = path.rstrip('/').decode('utf8') conc = Concurrency(context.concurrency) def check_conc(): for (exc_type, exc_value, exc_tb, result) in \ six.itervalues(conc.get_results()): if exc_value: with context.io_manager.with_stderr() as fp: fp.write(str(exc_value)) fp.write('\n') fp.flush() marker = None while True: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, marker=marker, headers=context.headers, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) if not contents: if until_empty and marker: marker = None continue break for item in contents: newpath = '%s/%s' % (path, item['name']) new_context = context.copy() new_context.ignore_404 = True check_conc() conc.spawn(newpath, cli_delete, new_context, newpath) marker = item['name'] conc.join() check_conc()
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 be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty the container. Note until_empty=True could run forever if something else is making new objects faster than they're being deleted. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information. """ path = path.rstrip('/').decode('utf8') conc = Concurrency(context.concurrency) def check_conc(): for (exc_type, exc_value, exc_tb, result) in \ six.itervalues(conc.get_results()): if exc_value: with context.io_manager.with_stderr() as fp: fp.write(str(exc_value)) fp.write('\n') fp.flush() marker = None while True: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, marker=marker, headers=context.headers, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) if not contents: if until_empty and marker: marker = None continue break for item in contents: newpath = '%s/%s' % (path, item['name']) new_context = context.copy() new_context.ignore_404 = True check_conc() conc.spawn(newpath, cli_delete, new_context, newpath) marker = item['name'] conc.join() check_conc()
[ "Deletes", "all", "objects", "in", "the", "container", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/delete.py#L83-L137
[ "def", "cli_empty_container", "(", "context", ",", "path", ",", "until_empty", "=", "False", ")", ":", "path", "=", "path", ".", "rstrip", "(", "'/'", ")", ".", "decode", "(", "'utf8'", ")", "conc", "=", "Concurrency", "(", "context", ".", "concurrency", ")", "def", "check_conc", "(", ")", ":", "for", "(", "exc_type", ",", "exc_value", ",", "exc_tb", ",", "result", ")", "in", "six", ".", "itervalues", "(", "conc", ".", "get_results", "(", ")", ")", ":", "if", "exc_value", ":", "with", "context", ".", "io_manager", ".", "with_stderr", "(", ")", "as", "fp", ":", "fp", ".", "write", "(", "str", "(", "exc_value", ")", ")", "fp", ".", "write", "(", "'\\n'", ")", "fp", ".", "flush", "(", ")", "marker", "=", "None", "while", "True", ":", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_container", "(", "path", ",", "marker", "=", "marker", ",", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "raise", "ReturnCode", "(", "'listing container %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")", "if", "not", "contents", ":", "if", "until_empty", "and", "marker", ":", "marker", "=", "None", "continue", "break", "for", "item", "in", "contents", ":", "newpath", "=", "'%s/%s'", "%", "(", "path", ",", "item", "[", "'name'", "]", ")", "new_context", "=", "context", ".", "copy", "(", ")", "new_context", ".", "ignore_404", "=", "True", "check_conc", "(", ")", "conc", ".", "spawn", "(", "newpath", ",", "cli_delete", ",", "new_context", ",", "newpath", ")", "marker", "=", "item", "[", "'name'", "]", "conc", ".", "join", "(", ")", "check_conc", "(", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_delete
Deletes the item (account, container, or object) at the path. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param path: The path of the item (acount, container, or object) to delete. :param body: The body to send with the DELETE request. Bodies are not normally sent with DELETE requests, but this can be useful with bulk deletes for instance. :param recursive: If True and the item is an account or container, deletes will be issued for any containing items as well. This does one pass at the deletion; so if objects revert to previous versions or if new objects otherwise arise during the process, the container(s) may not be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty the containers. :param until_empty: If True and recursive is True, this will cause Swiftly to keep looping through the deletes until the containers are completely empty. Useful if you have object versioning turned on or otherwise have objects that seemingly reappear after being deleted. It could also run forever if you have something that's uploading objects at a faster rate than they are deleted. :param yes_empty_account: This must be set to True for verification when the item is an account and recursive is True. :param yes_delete_account: This must be set to True for verification when the item is an account and you really wish a delete to be issued for the account itself.
swiftly/cli/delete.py
def cli_delete(context, path, body=None, recursive=False, yes_empty_account=False, yes_delete_account=False, until_empty=False): """ Deletes the item (account, container, or object) at the path. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param path: The path of the item (acount, container, or object) to delete. :param body: The body to send with the DELETE request. Bodies are not normally sent with DELETE requests, but this can be useful with bulk deletes for instance. :param recursive: If True and the item is an account or container, deletes will be issued for any containing items as well. This does one pass at the deletion; so if objects revert to previous versions or if new objects otherwise arise during the process, the container(s) may not be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty the containers. :param until_empty: If True and recursive is True, this will cause Swiftly to keep looping through the deletes until the containers are completely empty. Useful if you have object versioning turned on or otherwise have objects that seemingly reappear after being deleted. It could also run forever if you have something that's uploading objects at a faster rate than they are deleted. :param yes_empty_account: This must be set to True for verification when the item is an account and recursive is True. :param yes_delete_account: This must be set to True for verification when the item is an account and you really wish a delete to be issued for the account itself. """ path = path.lstrip('/') if path else '' if not path: if yes_empty_account: cli_empty_account( context, yes_empty_account=yes_empty_account, until_empty=until_empty) if yes_delete_account: with context.client_manager.with_client() as client: status, reason, headers, contents = client.delete_account( headers=context.headers, query=context.query, cdn=context.cdn, body=body, yes_i_mean_delete_the_account=yes_delete_account) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'deleting account: %s %s' % (status, reason)) elif '/' not in path.rstrip('/'): path = path.rstrip('/') if recursive: cli_empty_container(context, path, until_empty=until_empty) with context.client_manager.with_client() as client: status, reason, headers, contents = client.delete_container( path, headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'deleting container %r: %s %s' % (path, status, reason)) else: with context.client_manager.with_client() as client: status, reason, headers, contents = client.delete_object( *path.split('/', 1), headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'deleting object %r: %s %s' % (path, status, reason))
def cli_delete(context, path, body=None, recursive=False, yes_empty_account=False, yes_delete_account=False, until_empty=False): """ Deletes the item (account, container, or object) at the path. See :py:mod:`swiftly.cli.delete` for context usage information. See :py:class:`CLIDelete` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param path: The path of the item (acount, container, or object) to delete. :param body: The body to send with the DELETE request. Bodies are not normally sent with DELETE requests, but this can be useful with bulk deletes for instance. :param recursive: If True and the item is an account or container, deletes will be issued for any containing items as well. This does one pass at the deletion; so if objects revert to previous versions or if new objects otherwise arise during the process, the container(s) may not be empty once done. Set `until_empty` to True if you want multiple passes to keep trying to fully empty the containers. :param until_empty: If True and recursive is True, this will cause Swiftly to keep looping through the deletes until the containers are completely empty. Useful if you have object versioning turned on or otherwise have objects that seemingly reappear after being deleted. It could also run forever if you have something that's uploading objects at a faster rate than they are deleted. :param yes_empty_account: This must be set to True for verification when the item is an account and recursive is True. :param yes_delete_account: This must be set to True for verification when the item is an account and you really wish a delete to be issued for the account itself. """ path = path.lstrip('/') if path else '' if not path: if yes_empty_account: cli_empty_account( context, yes_empty_account=yes_empty_account, until_empty=until_empty) if yes_delete_account: with context.client_manager.with_client() as client: status, reason, headers, contents = client.delete_account( headers=context.headers, query=context.query, cdn=context.cdn, body=body, yes_i_mean_delete_the_account=yes_delete_account) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'deleting account: %s %s' % (status, reason)) elif '/' not in path.rstrip('/'): path = path.rstrip('/') if recursive: cli_empty_container(context, path, until_empty=until_empty) with context.client_manager.with_client() as client: status, reason, headers, contents = client.delete_container( path, headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'deleting container %r: %s %s' % (path, status, reason)) else: with context.client_manager.with_client() as client: status, reason, headers, contents = client.delete_object( *path.split('/', 1), headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'deleting object %r: %s %s' % (path, status, reason))
[ "Deletes", "the", "item", "(", "account", "container", "or", "object", ")", "at", "the", "path", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/delete.py#L140-L217
[ "def", "cli_delete", "(", "context", ",", "path", ",", "body", "=", "None", ",", "recursive", "=", "False", ",", "yes_empty_account", "=", "False", ",", "yes_delete_account", "=", "False", ",", "until_empty", "=", "False", ")", ":", "path", "=", "path", ".", "lstrip", "(", "'/'", ")", "if", "path", "else", "''", "if", "not", "path", ":", "if", "yes_empty_account", ":", "cli_empty_account", "(", "context", ",", "yes_empty_account", "=", "yes_empty_account", ",", "until_empty", "=", "until_empty", ")", "if", "yes_delete_account", ":", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "delete_account", "(", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ",", "body", "=", "body", ",", "yes_i_mean_delete_the_account", "=", "yes_delete_account", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "raise", "ReturnCode", "(", "'deleting account: %s %s'", "%", "(", "status", ",", "reason", ")", ")", "elif", "'/'", "not", "in", "path", ".", "rstrip", "(", "'/'", ")", ":", "path", "=", "path", ".", "rstrip", "(", "'/'", ")", "if", "recursive", ":", "cli_empty_container", "(", "context", ",", "path", ",", "until_empty", "=", "until_empty", ")", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "delete_container", "(", "path", ",", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ",", "body", "=", "body", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "raise", "ReturnCode", "(", "'deleting container %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")", "else", ":", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "delete_object", "(", "*", "path", ".", "split", "(", "'/'", ",", "1", ")", ",", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ",", "body", "=", "body", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "raise", "ReturnCode", "(", "'deleting object %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
_stdout_filed
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.
swiftly/cli/optionparser.py
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) elif self.io_manager: with self.io_manager.with_stdout() as stdout: return func(self, file=stdout) else: return func(self, file=sys.stdout) wrapper.__doc__ = func.__doc__ return wrapper
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) elif self.io_manager: with self.io_manager.with_stdout() as stdout: return func(self, file=stdout) else: return func(self, file=sys.stdout) wrapper.__doc__ = func.__doc__ return wrapper
[ "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", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/optionparser.py#L25-L40
[ "def", "_stdout_filed", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "file", "=", "None", ")", ":", "if", "file", ":", "return", "func", "(", "self", ",", "file", "=", "file", ")", "elif", "self", ".", "io_manager", ":", "with", "self", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "stdout", ":", "return", "func", "(", "self", ",", "file", "=", "stdout", ")", "else", ":", "return", "func", "(", "self", ",", "file", "=", "sys", ".", "stdout", ")", "wrapper", ".", "__doc__", "=", "func", ".", "__doc__", "return", "wrapper" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
_stderr_filed
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.
swiftly/cli/optionparser.py
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, file=file) elif self.io_manager: with self.io_manager.with_stderr() as stderr: return func(self, msg, file=stderr) else: return func(self, msg, file=sys.stderr) wrapper.__doc__ = func.__doc__ return wrapper
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, file=file) elif self.io_manager: with self.io_manager.with_stderr() as stderr: return func(self, msg, file=stderr) else: return func(self, msg, file=sys.stderr) wrapper.__doc__ = func.__doc__ return wrapper
[ "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", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/optionparser.py#L43-L58
[ "def", "_stderr_filed", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "msg", ",", "file", "=", "None", ")", ":", "if", "file", ":", "return", "func", "(", "self", ",", "msg", ",", "file", "=", "file", ")", "elif", "self", ".", "io_manager", ":", "with", "self", ".", "io_manager", ".", "with_stderr", "(", ")", "as", "stderr", ":", "return", "func", "(", "self", ",", "msg", ",", "file", "=", "stderr", ")", "else", ":", "return", "func", "(", "self", ",", "msg", ",", "file", "=", "sys", ".", "stderr", ")", "wrapper", ".", "__doc__", "=", "func", ".", "__doc__", "return", "wrapper" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
OptionParser.error
Outputs the error msg to the file if specified, or to the io_manager's stderr if available, or to sys.stderr.
swiftly/cli/optionparser.py
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.flush()
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.flush()
[ "Outputs", "the", "error", "msg", "to", "the", "file", "if", "specified", "or", "to", "the", "io_manager", "s", "stderr", "if", "available", "or", "to", "sys", ".", "stderr", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/optionparser.py#L97-L106
[ "def", "error", "(", "self", ",", "msg", ",", "file", "=", "None", ")", ":", "self", ".", "error_encountered", "=", "True", "file", ".", "write", "(", "self", ".", "error_prefix", ")", "file", ".", "write", "(", "msg", ")", "file", ".", "write", "(", "'\\n'", ")", "file", ".", "flush", "(", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
OptionParser.exit
Immediately exits Python with the given status (or 0) as the exit code and optionally outputs the msg using self.error.
swiftly/cli/optionparser.py
def exit(self, status=0, msg=None): """ Immediately exits Python with the given status (or 0) as the exit code and optionally outputs the msg using self.error. """ if msg: self.error(msg) sys.exit(status)
def exit(self, status=0, msg=None): """ Immediately exits Python with the given status (or 0) as the exit code and optionally outputs the msg using self.error. """ if msg: self.error(msg) sys.exit(status)
[ "Immediately", "exits", "Python", "with", "the", "given", "status", "(", "or", "0", ")", "as", "the", "exit", "code", "and", "optionally", "outputs", "the", "msg", "using", "self", ".", "error", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/optionparser.py#L108-L115
[ "def", "exit", "(", "self", ",", "status", "=", "0", ",", "msg", "=", "None", ")", ":", "if", "msg", ":", "self", ".", "error", "(", "msg", ")", "sys", ".", "exit", "(", "status", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
OptionParser.print_help
Outputs help information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout.
swiftly/cli/optionparser.py
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.flush()
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.flush()
[ "Outputs", "help", "information", "to", "the", "file", "if", "specified", "or", "to", "the", "io_manager", "s", "stdout", "if", "available", "or", "to", "sys", ".", "stdout", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/optionparser.py#L118-L126
[ "def", "print_help", "(", "self", ",", "file", "=", "None", ")", ":", "optparse", ".", "OptionParser", ".", "print_help", "(", "self", ",", "file", ")", "if", "self", ".", "raw_epilog", ":", "file", ".", "write", "(", "self", ".", "raw_epilog", ")", "file", ".", "flush", "(", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
OptionParser.print_usage
Outputs usage information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout.
swiftly/cli/optionparser.py
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()
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()
[ "Outputs", "usage", "information", "to", "the", "file", "if", "specified", "or", "to", "the", "io_manager", "s", "stdout", "if", "available", "or", "to", "sys", ".", "stdout", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/optionparser.py#L129-L135
[ "def", "print_usage", "(", "self", ",", "file", "=", "None", ")", ":", "optparse", ".", "OptionParser", ".", "print_usage", "(", "self", ",", "file", ")", "file", ".", "flush", "(", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
OptionParser.print_version
Outputs version information to the file if specified, or to the io_manager's stdout if available, or to sys.stdout.
swiftly/cli/optionparser.py
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()
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()
[ "Outputs", "version", "information", "to", "the", "file", "if", "specified", "or", "to", "the", "io_manager", "s", "stdout", "if", "available", "or", "to", "sys", ".", "stdout", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/optionparser.py#L138-L144
[ "def", "print_version", "(", "self", ",", "file", "=", "None", ")", ":", "optparse", ".", "OptionParser", ".", "print_version", "(", "self", ",", "file", ")", "file", ".", "flush", "(", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
CLICommand.parse_args_and_create_context
Helper method that will parse the args into options and remaining args as well as create an initial :py:class:`swiftly.cli.context.CLIContext`. The new context will be a copy of :py:attr:`swiftly.cli.cli.CLI.context` with the following attributes added: ======================= =================================== muted_account_headers The headers to omit when outputting account headers. muted_container_headers The headers to omit when outputting container headers. muted_object_headers The headers to omit when outputting object headers. ======================= =================================== :returns: options, args, context
swiftly/cli/command.py
def parse_args_and_create_context(self, args): """ Helper method that will parse the args into options and remaining args as well as create an initial :py:class:`swiftly.cli.context.CLIContext`. The new context will be a copy of :py:attr:`swiftly.cli.cli.CLI.context` with the following attributes added: ======================= =================================== muted_account_headers The headers to omit when outputting account headers. muted_container_headers The headers to omit when outputting container headers. muted_object_headers The headers to omit when outputting object headers. ======================= =================================== :returns: options, args, context """ original_args = args try: options, args = self.option_parser.parse_args(args) except UnboundLocalError: # Happens sometimes with an error handler that doesn't raise its # own exception. We'll catch the error below with # error_encountered. pass if self.option_parser.error_encountered: if '-?' in original_args or '-h' in original_args or \ '--help' in original_args: self.option_parser.print_help() raise ReturnCode() if options.help: self.option_parser.print_help() raise ReturnCode() if self.min_args is not None and len(args) < self.min_args: raise ReturnCode( 'requires at least %s args.' % self.min_args) if self.max_args is not None and len(args) > self.max_args: raise ReturnCode( 'requires no more than %s args.' % self.max_args) context = self.cli.context.copy() context.muted_account_headers = [ 'accept-ranges', 'content-length', 'content-type', 'date'] context.muted_container_headers = [ 'accept-ranges', 'content-length', 'content-type', 'date'] context.muted_object_headers = ['accept-ranges', 'date'] return options, args, context
def parse_args_and_create_context(self, args): """ Helper method that will parse the args into options and remaining args as well as create an initial :py:class:`swiftly.cli.context.CLIContext`. The new context will be a copy of :py:attr:`swiftly.cli.cli.CLI.context` with the following attributes added: ======================= =================================== muted_account_headers The headers to omit when outputting account headers. muted_container_headers The headers to omit when outputting container headers. muted_object_headers The headers to omit when outputting object headers. ======================= =================================== :returns: options, args, context """ original_args = args try: options, args = self.option_parser.parse_args(args) except UnboundLocalError: # Happens sometimes with an error handler that doesn't raise its # own exception. We'll catch the error below with # error_encountered. pass if self.option_parser.error_encountered: if '-?' in original_args or '-h' in original_args or \ '--help' in original_args: self.option_parser.print_help() raise ReturnCode() if options.help: self.option_parser.print_help() raise ReturnCode() if self.min_args is not None and len(args) < self.min_args: raise ReturnCode( 'requires at least %s args.' % self.min_args) if self.max_args is not None and len(args) > self.max_args: raise ReturnCode( 'requires no more than %s args.' % self.max_args) context = self.cli.context.copy() context.muted_account_headers = [ 'accept-ranges', 'content-length', 'content-type', 'date'] context.muted_container_headers = [ 'accept-ranges', 'content-length', 'content-type', 'date'] context.muted_object_headers = ['accept-ranges', 'date'] return options, args, context
[ "Helper", "method", "that", "will", "parse", "the", "args", "into", "options", "and", "remaining", "args", "as", "well", "as", "create", "an", "initial", ":", "py", ":", "class", ":", "swiftly", ".", "cli", ".", "context", ".", "CLIContext", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/command.py#L78-L127
[ "def", "parse_args_and_create_context", "(", "self", ",", "args", ")", ":", "original_args", "=", "args", "try", ":", "options", ",", "args", "=", "self", ".", "option_parser", ".", "parse_args", "(", "args", ")", "except", "UnboundLocalError", ":", "# Happens sometimes with an error handler that doesn't raise its", "# own exception. We'll catch the error below with", "# error_encountered.", "pass", "if", "self", ".", "option_parser", ".", "error_encountered", ":", "if", "'-?'", "in", "original_args", "or", "'-h'", "in", "original_args", "or", "'--help'", "in", "original_args", ":", "self", ".", "option_parser", ".", "print_help", "(", ")", "raise", "ReturnCode", "(", ")", "if", "options", ".", "help", ":", "self", ".", "option_parser", ".", "print_help", "(", ")", "raise", "ReturnCode", "(", ")", "if", "self", ".", "min_args", "is", "not", "None", "and", "len", "(", "args", ")", "<", "self", ".", "min_args", ":", "raise", "ReturnCode", "(", "'requires at least %s args.'", "%", "self", ".", "min_args", ")", "if", "self", ".", "max_args", "is", "not", "None", "and", "len", "(", "args", ")", ">", "self", ".", "max_args", ":", "raise", "ReturnCode", "(", "'requires no more than %s args.'", "%", "self", ".", "max_args", ")", "context", "=", "self", ".", "cli", ".", "context", ".", "copy", "(", ")", "context", ".", "muted_account_headers", "=", "[", "'accept-ranges'", ",", "'content-length'", ",", "'content-type'", ",", "'date'", "]", "context", ".", "muted_container_headers", "=", "[", "'accept-ranges'", ",", "'content-length'", ",", "'content-type'", ",", "'date'", "]", "context", ".", "muted_object_headers", "=", "[", "'accept-ranges'", ",", "'date'", "]", "return", "options", ",", "args", ",", "context" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
CLICommand.options_list_to_lowered_dict
Helper function that will convert an options list into a dict of key/values. This is used for the quite common -hheader:value and -qparameter=value command line options, like this:: context.headers = self.options_list_to_lowered_dict(options.header) context.query = self.options_list_to_lowered_dict(options.query) For a full example, see :py:func:`swiftly.cli.get.CLIGet.__call__`.
swiftly/cli/command.py
def options_list_to_lowered_dict(self, options_list): """ Helper function that will convert an options list into a dict of key/values. This is used for the quite common -hheader:value and -qparameter=value command line options, like this:: context.headers = self.options_list_to_lowered_dict(options.header) context.query = self.options_list_to_lowered_dict(options.query) For a full example, see :py:func:`swiftly.cli.get.CLIGet.__call__`. """ result = {} if options_list: for key in options_list: key = key.lstrip() colon = key.find(':') if colon < 1: colon = None equal = key.find('=') if equal < 1: equal = None if colon and (not equal or colon < equal): key, value = key.split(':', 1) elif equal: key, value = key.split('=', 1) else: value = '' result[key.lower()] = value.lstrip() return result
def options_list_to_lowered_dict(self, options_list): """ Helper function that will convert an options list into a dict of key/values. This is used for the quite common -hheader:value and -qparameter=value command line options, like this:: context.headers = self.options_list_to_lowered_dict(options.header) context.query = self.options_list_to_lowered_dict(options.query) For a full example, see :py:func:`swiftly.cli.get.CLIGet.__call__`. """ result = {} if options_list: for key in options_list: key = key.lstrip() colon = key.find(':') if colon < 1: colon = None equal = key.find('=') if equal < 1: equal = None if colon and (not equal or colon < equal): key, value = key.split(':', 1) elif equal: key, value = key.split('=', 1) else: value = '' result[key.lower()] = value.lstrip() return result
[ "Helper", "function", "that", "will", "convert", "an", "options", "list", "into", "a", "dict", "of", "key", "/", "values", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/command.py#L129-L160
[ "def", "options_list_to_lowered_dict", "(", "self", ",", "options_list", ")", ":", "result", "=", "{", "}", "if", "options_list", ":", "for", "key", "in", "options_list", ":", "key", "=", "key", ".", "lstrip", "(", ")", "colon", "=", "key", ".", "find", "(", "':'", ")", "if", "colon", "<", "1", ":", "colon", "=", "None", "equal", "=", "key", ".", "find", "(", "'='", ")", "if", "equal", "<", "1", ":", "equal", "=", "None", "if", "colon", "and", "(", "not", "equal", "or", "colon", "<", "equal", ")", ":", "key", ",", "value", "=", "key", ".", "split", "(", "':'", ",", "1", ")", "elif", "equal", ":", "key", ",", "value", "=", "key", ".", "split", "(", "'='", ",", "1", ")", "else", ":", "value", "=", "''", "result", "[", "key", ".", "lower", "(", ")", "]", "=", "value", ".", "lstrip", "(", ")", "return", "result" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.request
Performs a direct HTTP request to the Swift service. :param method: The request method ('GET', 'HEAD', etc.) :param path: The request path. :param contents: The body of the request. May be a string or a file-like object. :param headers: A dict of request headers and values. :param decode_json: If set True, the response body will be treated as JSON and decoded result returned instead of the raw contents. :param stream: If set True, the response body will return as a file-like object; otherwise, the response body will be read in its entirety and returned as a string. Overrides decode_json. :param query: A dict of query parameters and values to append to the path. :param cdn: If set True, the request will be sent to the CDN management endpoint instead of the default storage endpoint. :returns: A tuple of (status, reason, headers, contents). :status: An int for the HTTP status code. :reason: The str for the HTTP status (ex: "Ok"). :headers: A dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: Depending on the decode_json and stream settings, this will either be the raw response string, the JSON decoded object, or a file-like object.
swiftly/client/client.py
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 contents: The body of the request. May be a string or a file-like object. :param headers: A dict of request headers and values. :param decode_json: If set True, the response body will be treated as JSON and decoded result returned instead of the raw contents. :param stream: If set True, the response body will return as a file-like object; otherwise, the response body will be read in its entirety and returned as a string. Overrides decode_json. :param query: A dict of query parameters and values to append to the path. :param cdn: If set True, the request will be sent to the CDN management endpoint instead of the default storage endpoint. :returns: A tuple of (status, reason, headers, contents). :status: An int for the HTTP status code. :reason: The str for the HTTP status (ex: "Ok"). :headers: A dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: Depending on the decode_json and stream settings, this will either be the raw response string, the JSON decoded object, or a file-like object. """ raise Exception('request method not implemented')
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 contents: The body of the request. May be a string or a file-like object. :param headers: A dict of request headers and values. :param decode_json: If set True, the response body will be treated as JSON and decoded result returned instead of the raw contents. :param stream: If set True, the response body will return as a file-like object; otherwise, the response body will be read in its entirety and returned as a string. Overrides decode_json. :param query: A dict of query parameters and values to append to the path. :param cdn: If set True, the request will be sent to the CDN management endpoint instead of the default storage endpoint. :returns: A tuple of (status, reason, headers, contents). :status: An int for the HTTP status code. :reason: The str for the HTTP status (ex: "Ok"). :headers: A dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: Depending on the decode_json and stream settings, this will either be the raw response string, the JSON decoded object, or a file-like object. """ raise Exception('request method not implemented')
[ "Performs", "a", "direct", "HTTP", "request", "to", "the", "Swift", "service", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L58-L92
[ "def", "request", "(", "self", ",", "method", ",", "path", ",", "contents", ",", "headers", ",", "decode_json", "=", "False", ",", "stream", "=", "False", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "raise", "Exception", "(", "'request method not implemented'", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.head_account
HEADs the account and returns the results. Useful headers returned are: =========================== ================================= x-account-bytes-used Object storage used for the account, in bytes. x-account-container-count The number of containers in the account. x-account-object-count The number of objects in the account. =========================== ================================= Also, any user headers beginning with x-account-meta- are returned. These values can be delayed depending the Swift cluster. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
def head_account(self, headers=None, query=None, cdn=False): """ HEADs the account and returns the results. Useful headers returned are: =========================== ================================= x-account-bytes-used Object storage used for the account, in bytes. x-account-container-count The number of containers in the account. x-account-object-count The number of objects in the account. =========================== ================================= Also, any user headers beginning with x-account-meta- are returned. These values can be delayed depending the Swift cluster. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ return self.request( 'HEAD', '', '', headers, query=query, cdn=cdn)
def head_account(self, headers=None, query=None, cdn=False): """ HEADs the account and returns the results. Useful headers returned are: =========================== ================================= x-account-bytes-used Object storage used for the account, in bytes. x-account-container-count The number of containers in the account. x-account-object-count The number of objects in the account. =========================== ================================= Also, any user headers beginning with x-account-meta- are returned. These values can be delayed depending the Swift cluster. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ return self.request( 'HEAD', '', '', headers, query=query, cdn=cdn)
[ "HEADs", "the", "account", "and", "returns", "the", "results", ".", "Useful", "headers", "returned", "are", ":" ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L114-L148
[ "def", "head_account", "(", "self", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "return", "self", ".", "request", "(", "'HEAD'", ",", "''", ",", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.get_account
GETs the account and returns the results. This is done to list the containers for the account. Some useful headers are also returned: =========================== ================================= x-account-bytes-used Object storage used for the account, in bytes. x-account-container-count The number of containers in the account. x-account-object-count The number of objects in the account. =========================== ================================= Also, any user headers beginning with x-account-meta- are returned. These values can be delayed depending the Swift cluster. :param headers: Additional headers to send with the request. :param prefix: The prefix container names must match to be listed. :param delimiter: The delimiter for the listing. Delimiters indicate how far to progress through container names before "rolling them up". For instance, a delimiter='.' query on an account with the containers:: one.one one.two two three.one would return the JSON value of:: [{'subdir': 'one.'}, {'count': 0, 'bytes': 0, 'name': 'two'}, {'subdir': 'three.'}] Using this with prefix can allow you to traverse a psuedo hierarchy. :param marker: Only container names after this marker will be returned. Swift returns a limited number of containers per request (often 10,000). To get the next batch of names, you issue another query with the marker set to the last name you received. You can continue to issue requests until you receive no more names. :param end_marker: Only container names before this marker will be returned. :param limit: Limits the size of the list returned per request. The default and maximum depends on the Swift cluster (usually 10,000). :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param decode_json: If set False, the usual decoding of the JSON response will be skipped and the raw contents will be returned instead. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the decoded JSON response or the raw str for the HTTP body.
swiftly/client/client.py
def get_account(self, headers=None, prefix=None, delimiter=None, marker=None, end_marker=None, limit=None, query=None, cdn=False, decode_json=True): """ GETs the account and returns the results. This is done to list the containers for the account. Some useful headers are also returned: =========================== ================================= x-account-bytes-used Object storage used for the account, in bytes. x-account-container-count The number of containers in the account. x-account-object-count The number of objects in the account. =========================== ================================= Also, any user headers beginning with x-account-meta- are returned. These values can be delayed depending the Swift cluster. :param headers: Additional headers to send with the request. :param prefix: The prefix container names must match to be listed. :param delimiter: The delimiter for the listing. Delimiters indicate how far to progress through container names before "rolling them up". For instance, a delimiter='.' query on an account with the containers:: one.one one.two two three.one would return the JSON value of:: [{'subdir': 'one.'}, {'count': 0, 'bytes': 0, 'name': 'two'}, {'subdir': 'three.'}] Using this with prefix can allow you to traverse a psuedo hierarchy. :param marker: Only container names after this marker will be returned. Swift returns a limited number of containers per request (often 10,000). To get the next batch of names, you issue another query with the marker set to the last name you received. You can continue to issue requests until you receive no more names. :param end_marker: Only container names before this marker will be returned. :param limit: Limits the size of the list returned per request. The default and maximum depends on the Swift cluster (usually 10,000). :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param decode_json: If set False, the usual decoding of the JSON response will be skipped and the raw contents will be returned instead. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the decoded JSON response or the raw str for the HTTP body. """ query = dict(query or {}) query['format'] = 'json' if prefix: query['prefix'] = prefix if delimiter: query['delimiter'] = delimiter if marker: query['marker'] = marker if end_marker: query['end_marker'] = end_marker if limit: query['limit'] = limit return self.request( 'GET', '', '', headers, decode_json=decode_json, query=query, cdn=cdn)
def get_account(self, headers=None, prefix=None, delimiter=None, marker=None, end_marker=None, limit=None, query=None, cdn=False, decode_json=True): """ GETs the account and returns the results. This is done to list the containers for the account. Some useful headers are also returned: =========================== ================================= x-account-bytes-used Object storage used for the account, in bytes. x-account-container-count The number of containers in the account. x-account-object-count The number of objects in the account. =========================== ================================= Also, any user headers beginning with x-account-meta- are returned. These values can be delayed depending the Swift cluster. :param headers: Additional headers to send with the request. :param prefix: The prefix container names must match to be listed. :param delimiter: The delimiter for the listing. Delimiters indicate how far to progress through container names before "rolling them up". For instance, a delimiter='.' query on an account with the containers:: one.one one.two two three.one would return the JSON value of:: [{'subdir': 'one.'}, {'count': 0, 'bytes': 0, 'name': 'two'}, {'subdir': 'three.'}] Using this with prefix can allow you to traverse a psuedo hierarchy. :param marker: Only container names after this marker will be returned. Swift returns a limited number of containers per request (often 10,000). To get the next batch of names, you issue another query with the marker set to the last name you received. You can continue to issue requests until you receive no more names. :param end_marker: Only container names before this marker will be returned. :param limit: Limits the size of the list returned per request. The default and maximum depends on the Swift cluster (usually 10,000). :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param decode_json: If set False, the usual decoding of the JSON response will be skipped and the raw contents will be returned instead. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the decoded JSON response or the raw str for the HTTP body. """ query = dict(query or {}) query['format'] = 'json' if prefix: query['prefix'] = prefix if delimiter: query['delimiter'] = delimiter if marker: query['marker'] = marker if end_marker: query['end_marker'] = end_marker if limit: query['limit'] = limit return self.request( 'GET', '', '', headers, decode_json=decode_json, query=query, cdn=cdn)
[ "GETs", "the", "account", "and", "returns", "the", "results", ".", "This", "is", "done", "to", "list", "the", "containers", "for", "the", "account", ".", "Some", "useful", "headers", "are", "also", "returned", ":" ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L150-L235
[ "def", "get_account", "(", "self", ",", "headers", "=", "None", ",", "prefix", "=", "None", ",", "delimiter", "=", "None", ",", "marker", "=", "None", ",", "end_marker", "=", "None", ",", "limit", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ",", "decode_json", "=", "True", ")", ":", "query", "=", "dict", "(", "query", "or", "{", "}", ")", "query", "[", "'format'", "]", "=", "'json'", "if", "prefix", ":", "query", "[", "'prefix'", "]", "=", "prefix", "if", "delimiter", ":", "query", "[", "'delimiter'", "]", "=", "delimiter", "if", "marker", ":", "query", "[", "'marker'", "]", "=", "marker", "if", "end_marker", ":", "query", "[", "'end_marker'", "]", "=", "end_marker", "if", "limit", ":", "query", "[", "'limit'", "]", "=", "limit", "return", "self", ".", "request", "(", "'GET'", ",", "''", ",", "''", ",", "headers", ",", "decode_json", "=", "decode_json", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.put_account
PUTs the account and returns the results. This is usually done with the extract-archive bulk upload request and has no other use I know of (but the call is left open in case there ever is). :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some account PUT requests, like the extract-archive bulk upload request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
def put_account(self, headers=None, query=None, cdn=False, body=None): """ PUTs the account and returns the results. This is usually done with the extract-archive bulk upload request and has no other use I know of (but the call is left open in case there ever is). :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some account PUT requests, like the extract-archive bulk upload request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ return self.request( 'PUT', '', body or '', headers, query=query, cdn=cdn)
def put_account(self, headers=None, query=None, cdn=False, body=None): """ PUTs the account and returns the results. This is usually done with the extract-archive bulk upload request and has no other use I know of (but the call is left open in case there ever is). :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some account PUT requests, like the extract-archive bulk upload request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ return self.request( 'PUT', '', body or '', headers, query=query, cdn=cdn)
[ "PUTs", "the", "account", "and", "returns", "the", "results", ".", "This", "is", "usually", "done", "with", "the", "extract", "-", "archive", "bulk", "upload", "request", "and", "has", "no", "other", "use", "I", "know", "of", "(", "but", "the", "call", "is", "left", "open", "in", "case", "there", "ever", "is", ")", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L237-L261
[ "def", "put_account", "(", "self", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ",", "body", "=", "None", ")", ":", "return", "self", ".", "request", "(", "'PUT'", ",", "''", ",", "body", "or", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.post_account
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 header, send the header with an empty string as its value. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: No known Swift POSTs take a body; but the option is there for the future. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
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 header, send the header with an empty string as its value. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: No known Swift POSTs take a body; but the option is there for the future. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ return self.request( 'POST', '', body or '', headers, query=query, cdn=cdn)
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 header, send the header with an empty string as its value. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: No known Swift POSTs take a body; but the option is there for the future. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ return self.request( 'POST', '', body or '', headers, query=query, cdn=cdn)
[ "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", "header", "send", "the", "header", "with", "an", "empty", "string", "as", "its", "value", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L263-L288
[ "def", "post_account", "(", "self", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ",", "body", "=", "None", ")", ":", "return", "self", ".", "request", "(", "'POST'", ",", "''", ",", "body", "or", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.delete_account
Sends a DELETE request to the account and returns the results. With ``query['bulk-delete'] = ''`` this might mean a bulk delete request where the body of the request is new-line separated, url-encoded list of names to delete. Be careful with this! One wrong move and you might mark your account for deletion of you have the access to do so! For a plain DELETE to the account, on clusters that support it and, assuming you have permissions to do so, the account will be marked as deleted and immediately begin removing the objects from the cluster in the backgound. THERE IS NO GOING BACK! :param headers: Additional headers to send with the request. :param yes_i_mean_delete_the_account: Set to True to verify you really mean to delete the entire account. This is required unless ``body and 'bulk-delete' in query``. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some account DELETE requests, like the bulk delete request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
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 delete request where the body of the request is new-line separated, url-encoded list of names to delete. Be careful with this! One wrong move and you might mark your account for deletion of you have the access to do so! For a plain DELETE to the account, on clusters that support it and, assuming you have permissions to do so, the account will be marked as deleted and immediately begin removing the objects from the cluster in the backgound. THERE IS NO GOING BACK! :param headers: Additional headers to send with the request. :param yes_i_mean_delete_the_account: Set to True to verify you really mean to delete the entire account. This is required unless ``body and 'bulk-delete' in query``. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some account DELETE requests, like the bulk delete request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ if not yes_i_mean_delete_the_account and ( not body or not query or 'bulk-delete' not in query): return (0, 'yes_i_mean_delete_the_account was not set to True', {}, '') return self.request( 'DELETE', '', body or '', headers, query=query, cdn=cdn)
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 delete request where the body of the request is new-line separated, url-encoded list of names to delete. Be careful with this! One wrong move and you might mark your account for deletion of you have the access to do so! For a plain DELETE to the account, on clusters that support it and, assuming you have permissions to do so, the account will be marked as deleted and immediately begin removing the objects from the cluster in the backgound. THERE IS NO GOING BACK! :param headers: Additional headers to send with the request. :param yes_i_mean_delete_the_account: Set to True to verify you really mean to delete the entire account. This is required unless ``body and 'bulk-delete' in query``. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some account DELETE requests, like the bulk delete request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ if not yes_i_mean_delete_the_account and ( not body or not query or 'bulk-delete' not in query): return (0, 'yes_i_mean_delete_the_account was not set to True', {}, '') return self.request( 'DELETE', '', body or '', headers, query=query, cdn=cdn)
[ "Sends", "a", "DELETE", "request", "to", "the", "account", "and", "returns", "the", "results", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L290-L333
[ "def", "delete_account", "(", "self", ",", "headers", "=", "None", ",", "yes_i_mean_delete_the_account", "=", "False", ",", "query", "=", "None", ",", "cdn", "=", "False", ",", "body", "=", "None", ")", ":", "if", "not", "yes_i_mean_delete_the_account", "and", "(", "not", "body", "or", "not", "query", "or", "'bulk-delete'", "not", "in", "query", ")", ":", "return", "(", "0", ",", "'yes_i_mean_delete_the_account was not set to True'", ",", "{", "}", ",", "''", ")", "return", "self", ".", "request", "(", "'DELETE'", ",", "''", ",", "body", "or", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.head_container
HEADs the container and returns the results. Useful headers returned are: =========================== ================================= x-container-bytes-used Object storage used for the container, in bytes. x-container-object-count The number of objects in the container. =========================== ================================= Also, any user headers beginning with x-container-meta- are returned. These values can be delayed depending the Swift cluster. :param container: The name of the container. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
def head_container(self, container, headers=None, query=None, cdn=False): """ HEADs the container and returns the results. Useful headers returned are: =========================== ================================= x-container-bytes-used Object storage used for the container, in bytes. x-container-object-count The number of objects in the container. =========================== ================================= Also, any user headers beginning with x-container-meta- are returned. These values can be delayed depending the Swift cluster. :param container: The name of the container. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._container_path(container) return self.request( 'HEAD', path, '', headers, query=query, cdn=cdn)
def head_container(self, container, headers=None, query=None, cdn=False): """ HEADs the container and returns the results. Useful headers returned are: =========================== ================================= x-container-bytes-used Object storage used for the container, in bytes. x-container-object-count The number of objects in the container. =========================== ================================= Also, any user headers beginning with x-container-meta- are returned. These values can be delayed depending the Swift cluster. :param container: The name of the container. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._container_path(container) return self.request( 'HEAD', path, '', headers, query=query, cdn=cdn)
[ "HEADs", "the", "container", "and", "returns", "the", "results", ".", "Useful", "headers", "returned", "are", ":" ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L335-L369
[ "def", "head_container", "(", "self", ",", "container", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "path", "=", "self", ".", "_container_path", "(", "container", ")", "return", "self", ".", "request", "(", "'HEAD'", ",", "path", ",", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.get_container
GETs the container and returns the results. This is done to list the objects for the container. Some useful headers are also returned: =========================== ================================= x-container-bytes-used Object storage used for the container, in bytes. x-container-object-count The number of objects in the container. =========================== ================================= Also, any user headers beginning with x-container-meta- are returned. These values can be delayed depending the Swift cluster. :param container: The name of the container. :param headers: Additional headers to send with the request. :param prefix: The prefix object names must match to be listed. :param delimiter: The delimiter for the listing. Delimiters indicate how far to progress through object names before "rolling them up". For instance, a delimiter='/' query on an container with the objects:: one/one one/two two three/one would return the JSON value of:: [{'subdir': 'one/'}, {'count': 0, 'bytes': 0, 'name': 'two'}, {'subdir': 'three/'}] Using this with prefix can allow you to traverse a psuedo hierarchy. :param marker: Only object names after this marker will be returned. Swift returns a limited number of objects per request (often 10,000). To get the next batch of names, you issue another query with the marker set to the last name you received. You can continue to issue requests until you receive no more names. :param end_marker: Only object names before this marker will be returned. :param limit: Limits the size of the list returned per request. The default and maximum depends on the Swift cluster (usually 10,000). :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param decode_json: If set False, the usual decoding of the JSON response will be skipped and the raw contents will be returned instead. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the decoded JSON response or the raw str for the HTTP body.
swiftly/client/client.py
def get_container(self, container, headers=None, prefix=None, delimiter=None, marker=None, end_marker=None, limit=None, query=None, cdn=False, decode_json=True): """ GETs the container and returns the results. This is done to list the objects for the container. Some useful headers are also returned: =========================== ================================= x-container-bytes-used Object storage used for the container, in bytes. x-container-object-count The number of objects in the container. =========================== ================================= Also, any user headers beginning with x-container-meta- are returned. These values can be delayed depending the Swift cluster. :param container: The name of the container. :param headers: Additional headers to send with the request. :param prefix: The prefix object names must match to be listed. :param delimiter: The delimiter for the listing. Delimiters indicate how far to progress through object names before "rolling them up". For instance, a delimiter='/' query on an container with the objects:: one/one one/two two three/one would return the JSON value of:: [{'subdir': 'one/'}, {'count': 0, 'bytes': 0, 'name': 'two'}, {'subdir': 'three/'}] Using this with prefix can allow you to traverse a psuedo hierarchy. :param marker: Only object names after this marker will be returned. Swift returns a limited number of objects per request (often 10,000). To get the next batch of names, you issue another query with the marker set to the last name you received. You can continue to issue requests until you receive no more names. :param end_marker: Only object names before this marker will be returned. :param limit: Limits the size of the list returned per request. The default and maximum depends on the Swift cluster (usually 10,000). :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param decode_json: If set False, the usual decoding of the JSON response will be skipped and the raw contents will be returned instead. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the decoded JSON response or the raw str for the HTTP body. """ query = dict(query or {}) query['format'] = 'json' if prefix: query['prefix'] = prefix if delimiter: query['delimiter'] = delimiter if marker: query['marker'] = marker if end_marker: query['end_marker'] = end_marker if limit: query['limit'] = limit return self.request( 'GET', self._container_path(container), '', headers, decode_json=decode_json, query=query, cdn=cdn)
def get_container(self, container, headers=None, prefix=None, delimiter=None, marker=None, end_marker=None, limit=None, query=None, cdn=False, decode_json=True): """ GETs the container and returns the results. This is done to list the objects for the container. Some useful headers are also returned: =========================== ================================= x-container-bytes-used Object storage used for the container, in bytes. x-container-object-count The number of objects in the container. =========================== ================================= Also, any user headers beginning with x-container-meta- are returned. These values can be delayed depending the Swift cluster. :param container: The name of the container. :param headers: Additional headers to send with the request. :param prefix: The prefix object names must match to be listed. :param delimiter: The delimiter for the listing. Delimiters indicate how far to progress through object names before "rolling them up". For instance, a delimiter='/' query on an container with the objects:: one/one one/two two three/one would return the JSON value of:: [{'subdir': 'one/'}, {'count': 0, 'bytes': 0, 'name': 'two'}, {'subdir': 'three/'}] Using this with prefix can allow you to traverse a psuedo hierarchy. :param marker: Only object names after this marker will be returned. Swift returns a limited number of objects per request (often 10,000). To get the next batch of names, you issue another query with the marker set to the last name you received. You can continue to issue requests until you receive no more names. :param end_marker: Only object names before this marker will be returned. :param limit: Limits the size of the list returned per request. The default and maximum depends on the Swift cluster (usually 10,000). :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param decode_json: If set False, the usual decoding of the JSON response will be skipped and the raw contents will be returned instead. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the decoded JSON response or the raw str for the HTTP body. """ query = dict(query or {}) query['format'] = 'json' if prefix: query['prefix'] = prefix if delimiter: query['delimiter'] = delimiter if marker: query['marker'] = marker if end_marker: query['end_marker'] = end_marker if limit: query['limit'] = limit return self.request( 'GET', self._container_path(container), '', headers, decode_json=decode_json, query=query, cdn=cdn)
[ "GETs", "the", "container", "and", "returns", "the", "results", ".", "This", "is", "done", "to", "list", "the", "objects", "for", "the", "container", ".", "Some", "useful", "headers", "are", "also", "returned", ":" ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L371-L455
[ "def", "get_container", "(", "self", ",", "container", ",", "headers", "=", "None", ",", "prefix", "=", "None", ",", "delimiter", "=", "None", ",", "marker", "=", "None", ",", "end_marker", "=", "None", ",", "limit", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ",", "decode_json", "=", "True", ")", ":", "query", "=", "dict", "(", "query", "or", "{", "}", ")", "query", "[", "'format'", "]", "=", "'json'", "if", "prefix", ":", "query", "[", "'prefix'", "]", "=", "prefix", "if", "delimiter", ":", "query", "[", "'delimiter'", "]", "=", "delimiter", "if", "marker", ":", "query", "[", "'marker'", "]", "=", "marker", "if", "end_marker", ":", "query", "[", "'end_marker'", "]", "=", "end_marker", "if", "limit", ":", "query", "[", "'limit'", "]", "=", "limit", "return", "self", ".", "request", "(", "'GET'", ",", "self", ".", "_container_path", "(", "container", ")", ",", "''", ",", "headers", ",", "decode_json", "=", "decode_json", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.put_container
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 already exists, any existing X-Container-Meta-xxx headers will remain untouched. To remove an X-Container-Meta-xxx header, send the header with an empty string as its value. :param container: The name of the container. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some container PUT requests, like the extract-archive bulk upload request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
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 already exists, any existing X-Container-Meta-xxx headers will remain untouched. To remove an X-Container-Meta-xxx header, send the header with an empty string as its value. :param container: The name of the container. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some container PUT requests, like the extract-archive bulk upload request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._container_path(container) return self.request( 'PUT', path, body or '', headers, query=query, cdn=cdn)
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 already exists, any existing X-Container-Meta-xxx headers will remain untouched. To remove an X-Container-Meta-xxx header, send the header with an empty string as its value. :param container: The name of the container. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: Some container PUT requests, like the extract-archive bulk upload request, take a body. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._container_path(container) return self.request( 'PUT', path, body or '', headers, query=query, cdn=cdn)
[ "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", "already", "exists", "any", "existing", "X", "-", "Container", "-", "Meta", "-", "xxx", "headers", "will", "remain", "untouched", ".", "To", "remove", "an", "X", "-", "Container", "-", "Meta", "-", "xxx", "header", "send", "the", "header", "with", "an", "empty", "string", "as", "its", "value", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L457-L486
[ "def", "put_container", "(", "self", ",", "container", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ",", "body", "=", "None", ")", ":", "path", "=", "self", ".", "_container_path", "(", "container", ")", "return", "self", ".", "request", "(", "'PUT'", ",", "path", ",", "body", "or", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.head_object
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 query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
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 query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._object_path(container, obj) return self.request( 'HEAD', path, '', headers, query=query, cdn=cdn)
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 query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._object_path(container, obj) return self.request( 'HEAD', path, '', headers, query=query, cdn=cdn)
[ "HEADs", "the", "object", "and", "returns", "the", "results", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L544-L566
[ "def", "head_object", "(", "self", ",", "container", ",", "obj", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "path", "=", "self", ".", "_object_path", "(", "container", ",", "obj", ")", "return", "self", ".", "request", "(", "'HEAD'", ",", "path", ",", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.get_object
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 with the request. :param stream: Indicates whether to stream the contents or preread them fully and return them as a str. Default: True to stream the contents. When streaming, contents will have the standard file-like-object read function, which accepts an optional size parameter to limit how much data is read per call. When streaming is on, be certain to fully read the contents before issuing another request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: if *stream* was True, *contents* is a file-like-object of the contents of the HTTP body. If *stream* was False, *contents* is just a simple str of the HTTP body.
swiftly/client/client.py
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 with the request. :param stream: Indicates whether to stream the contents or preread them fully and return them as a str. Default: True to stream the contents. When streaming, contents will have the standard file-like-object read function, which accepts an optional size parameter to limit how much data is read per call. When streaming is on, be certain to fully read the contents before issuing another request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: if *stream* was True, *contents* is a file-like-object of the contents of the HTTP body. If *stream* was False, *contents* is just a simple str of the HTTP body. """ path = self._object_path(container, obj) return self.request( 'GET', path, '', headers, query=query, stream=stream, cdn=cdn)
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 with the request. :param stream: Indicates whether to stream the contents or preread them fully and return them as a str. Default: True to stream the contents. When streaming, contents will have the standard file-like-object read function, which accepts an optional size parameter to limit how much data is read per call. When streaming is on, be certain to fully read the contents before issuing another request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: if *stream* was True, *contents* is a file-like-object of the contents of the HTTP body. If *stream* was False, *contents* is just a simple str of the HTTP body. """ path = self._object_path(container, obj) return self.request( 'GET', path, '', headers, query=query, stream=stream, cdn=cdn)
[ "GETs", "the", "object", "and", "returns", "the", "results", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L568-L602
[ "def", "get_object", "(", "self", ",", "container", ",", "obj", ",", "headers", "=", "None", ",", "stream", "=", "True", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "path", "=", "self", ".", "_object_path", "(", "container", ",", "obj", ")", "return", "self", ".", "request", "(", "'GET'", ",", "path", ",", "''", ",", "headers", ",", "query", "=", "query", ",", "stream", "=", "stream", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.put_object
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, Content-Encoding and other standard HTTP headers can often also be set, depending on the Swift cluster. Note that you can set the ETag header to the MD5 sum of the contents for extra verification the object was stored correctly. :param container: The name of the container. :param obj: The name of the object. :param contents: The contents of the object to store. This can be a simple str, or a file-like-object with at least a read function. If the file-like-object also has tell and seek functions, the PUT can be reattempted on any server error. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
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, Content-Encoding and other standard HTTP headers can often also be set, depending on the Swift cluster. Note that you can set the ETag header to the MD5 sum of the contents for extra verification the object was stored correctly. :param container: The name of the container. :param obj: The name of the object. :param contents: The contents of the object to store. This can be a simple str, or a file-like-object with at least a read function. If the file-like-object also has tell and seek functions, the PUT can be reattempted on any server error. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._object_path(container, obj) return self.request( 'PUT', path, contents, headers, query=query, cdn=cdn)
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, Content-Encoding and other standard HTTP headers can often also be set, depending on the Swift cluster. Note that you can set the ETag header to the MD5 sum of the contents for extra verification the object was stored correctly. :param container: The name of the container. :param obj: The name of the object. :param contents: The contents of the object to store. This can be a simple str, or a file-like-object with at least a read function. If the file-like-object also has tell and seek functions, the PUT can be reattempted on any server error. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._object_path(container, obj) return self.request( 'PUT', path, contents, headers, query=query, cdn=cdn)
[ "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", "Content", "-", "Encoding", "and", "other", "standard", "HTTP", "headers", "can", "often", "also", "be", "set", "depending", "on", "the", "Swift", "cluster", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L604-L640
[ "def", "put_object", "(", "self", ",", "container", ",", "obj", ",", "contents", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "path", "=", "self", ".", "_object_path", "(", "container", ",", "obj", ")", "return", "self", ".", "request", "(", "'PUT'", ",", "path", ",", "contents", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
Client.post_object
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 POSTs. With account and container POSTs, existing headers are untouched. But with object POSTs, any existing headers are removed. The full list of supported headers depends on the Swift cluster, but usually include Content-Type, Content-Encoding, and any X-Object-Meta-xxx headers. :param container: The name of the container. :param obj: The name of the object. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: No known Swift POSTs take a body; but the option is there for the future. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body.
swiftly/client/client.py
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 POSTs. With account and container POSTs, existing headers are untouched. But with object POSTs, any existing headers are removed. The full list of supported headers depends on the Swift cluster, but usually include Content-Type, Content-Encoding, and any X-Object-Meta-xxx headers. :param container: The name of the container. :param obj: The name of the object. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: No known Swift POSTs take a body; but the option is there for the future. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._object_path(container, obj) return self.request( 'POST', path, body or '', headers, query=query, cdn=cdn)
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 POSTs. With account and container POSTs, existing headers are untouched. But with object POSTs, any existing headers are removed. The full list of supported headers depends on the Swift cluster, but usually include Content-Type, Content-Encoding, and any X-Object-Meta-xxx headers. :param container: The name of the container. :param obj: The name of the object. :param headers: Additional headers to send with the request. :param query: Set to a dict of query values to send on the query string of the request. :param cdn: If set True, the CDN management interface will be used. :param body: No known Swift POSTs take a body; but the option is there for the future. :returns: A tuple of (status, reason, headers, contents). :status: is an int for the HTTP status code. :reason: is the str for the HTTP status (ex: "Ok"). :headers: is a dict with all lowercase keys of the HTTP headers; if a header has multiple values, it will be a list. :contents: is the str for the HTTP body. """ path = self._object_path(container, obj) return self.request( 'POST', path, body or '', headers, query=query, cdn=cdn)
[ "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", "POSTs", ".", "With", "account", "and", "container", "POSTs", "existing", "headers", "are", "untouched", ".", "But", "with", "object", "POSTs", "any", "existing", "headers", "are", "removed", ".", "The", "full", "list", "of", "supported", "headers", "depends", "on", "the", "Swift", "cluster", "but", "usually", "include", "Content", "-", "Type", "Content", "-", "Encoding", "and", "any", "X", "-", "Object", "-", "Meta", "-", "xxx", "headers", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/client.py#L642-L674
[ "def", "post_object", "(", "self", ",", "container", ",", "obj", ",", "headers", "=", "None", ",", "query", "=", "None", ",", "cdn", "=", "False", ",", "body", "=", "None", ")", ":", "path", "=", "self", ".", "_object_path", "(", "container", ",", "obj", ")", "return", "self", ".", "request", "(", "'POST'", ",", "path", ",", "body", "or", "''", ",", "headers", ",", "query", "=", "query", ",", "cdn", "=", "cdn", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_ping
Performs a ping test. See :py:mod:`swiftly.cli.ping` for context usage information. See :py:class:`CLIPing` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param prefix: The container name prefix to use. Default: swiftly-ping
swiftly/cli/ping.py
def cli_ping(context, prefix): """ Performs a ping test. See :py:mod:`swiftly.cli.ping` for context usage information. See :py:class:`CLIPing` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param prefix: The container name prefix to use. Default: swiftly-ping """ if not prefix: prefix = 'swiftly-ping' ping_ring_object_puts = collections.defaultdict(lambda: []) ping_ring_object_gets = collections.defaultdict(lambda: []) ping_ring_object_deletes = collections.defaultdict(lambda: []) context.ping_begin = context.ping_begin_last = time.time() container = prefix + '-' + uuid.uuid4().hex objects = [uuid.uuid4().hex for x in moves.range(context.ping_count)] conc = Concurrency(context.concurrency) with context.client_manager.with_client() as client: client.auth() _cli_ping_status(context, 'auth', '-', None, None, None, None) _cli_ping_status(context, 'account head', '-', *client.head_account()) _cli_ping_status( context, 'container put', '-', *client.put_container(container)) if _cli_ping_objects( context, 'put', conc, container, objects, _cli_ping_object_put, ping_ring_object_puts): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR put objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() if _cli_ping_objects( context, 'get', conc, container, objects, _cli_ping_object_get, ping_ring_object_gets): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR get objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() if _cli_ping_objects( context, 'delete', conc, container, objects, _cli_ping_object_delete, ping_ring_object_deletes): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR delete objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() for attempt in moves.range(5): if attempt: sleep(2**attempt) with context.client_manager.with_client() as client: try: _cli_ping_status( context, 'container delete', '-', *client.delete_container(container)) break except ReturnCode as err: with context.io_manager.with_stderr() as fp: fp.write(str(err)) fp.write('\n') fp.flush() else: with context.io_manager.with_stderr() as fp: fp.write( 'ERROR could not confirm deletion of container due to ' 'previous error; but continuing\n') fp.flush() end = time.time() with context.io_manager.with_stdout() as fp: if context.graphite: fp.write( '%s.ping_overall %.02f %d\n' % ( context.graphite, end - context.ping_begin, time.time())) if context.ping_verbose: fp.write('% 6.02fs total\n' % (end - context.ping_begin)) elif not context.graphite: fp.write('%.02fs\n' % (end - context.ping_begin)) fp.flush() ping_ring_overall = collections.defaultdict(lambda: []) _cli_ping_ring_report(context, ping_ring_object_puts, 'PUT') for ip, timings in six.iteritems(ping_ring_object_puts): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_object_gets, 'GET') for ip, timings in six.iteritems(ping_ring_object_gets): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_object_deletes, 'DELETE') for ip, timings in six.iteritems(ping_ring_object_deletes): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_overall, 'overall')
def cli_ping(context, prefix): """ Performs a ping test. See :py:mod:`swiftly.cli.ping` for context usage information. See :py:class:`CLIPing` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param prefix: The container name prefix to use. Default: swiftly-ping """ if not prefix: prefix = 'swiftly-ping' ping_ring_object_puts = collections.defaultdict(lambda: []) ping_ring_object_gets = collections.defaultdict(lambda: []) ping_ring_object_deletes = collections.defaultdict(lambda: []) context.ping_begin = context.ping_begin_last = time.time() container = prefix + '-' + uuid.uuid4().hex objects = [uuid.uuid4().hex for x in moves.range(context.ping_count)] conc = Concurrency(context.concurrency) with context.client_manager.with_client() as client: client.auth() _cli_ping_status(context, 'auth', '-', None, None, None, None) _cli_ping_status(context, 'account head', '-', *client.head_account()) _cli_ping_status( context, 'container put', '-', *client.put_container(container)) if _cli_ping_objects( context, 'put', conc, container, objects, _cli_ping_object_put, ping_ring_object_puts): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR put objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() if _cli_ping_objects( context, 'get', conc, container, objects, _cli_ping_object_get, ping_ring_object_gets): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR get objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() if _cli_ping_objects( context, 'delete', conc, container, objects, _cli_ping_object_delete, ping_ring_object_deletes): with context.io_manager.with_stderr() as fp: fp.write( 'ERROR delete objects did not complete successfully due to ' 'previous error; but continuing\n') fp.flush() for attempt in moves.range(5): if attempt: sleep(2**attempt) with context.client_manager.with_client() as client: try: _cli_ping_status( context, 'container delete', '-', *client.delete_container(container)) break except ReturnCode as err: with context.io_manager.with_stderr() as fp: fp.write(str(err)) fp.write('\n') fp.flush() else: with context.io_manager.with_stderr() as fp: fp.write( 'ERROR could not confirm deletion of container due to ' 'previous error; but continuing\n') fp.flush() end = time.time() with context.io_manager.with_stdout() as fp: if context.graphite: fp.write( '%s.ping_overall %.02f %d\n' % ( context.graphite, end - context.ping_begin, time.time())) if context.ping_verbose: fp.write('% 6.02fs total\n' % (end - context.ping_begin)) elif not context.graphite: fp.write('%.02fs\n' % (end - context.ping_begin)) fp.flush() ping_ring_overall = collections.defaultdict(lambda: []) _cli_ping_ring_report(context, ping_ring_object_puts, 'PUT') for ip, timings in six.iteritems(ping_ring_object_puts): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_object_gets, 'GET') for ip, timings in six.iteritems(ping_ring_object_gets): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_object_deletes, 'DELETE') for ip, timings in six.iteritems(ping_ring_object_deletes): ping_ring_overall[ip].extend(timings) _cli_ping_ring_report(context, ping_ring_overall, 'overall')
[ "Performs", "a", "ping", "test", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/ping.py#L271-L364
[ "def", "cli_ping", "(", "context", ",", "prefix", ")", ":", "if", "not", "prefix", ":", "prefix", "=", "'swiftly-ping'", "ping_ring_object_puts", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "ping_ring_object_gets", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "ping_ring_object_deletes", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "context", ".", "ping_begin", "=", "context", ".", "ping_begin_last", "=", "time", ".", "time", "(", ")", "container", "=", "prefix", "+", "'-'", "+", "uuid", ".", "uuid4", "(", ")", ".", "hex", "objects", "=", "[", "uuid", ".", "uuid4", "(", ")", ".", "hex", "for", "x", "in", "moves", ".", "range", "(", "context", ".", "ping_count", ")", "]", "conc", "=", "Concurrency", "(", "context", ".", "concurrency", ")", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "client", ".", "auth", "(", ")", "_cli_ping_status", "(", "context", ",", "'auth'", ",", "'-'", ",", "None", ",", "None", ",", "None", ",", "None", ")", "_cli_ping_status", "(", "context", ",", "'account head'", ",", "'-'", ",", "*", "client", ".", "head_account", "(", ")", ")", "_cli_ping_status", "(", "context", ",", "'container put'", ",", "'-'", ",", "*", "client", ".", "put_container", "(", "container", ")", ")", "if", "_cli_ping_objects", "(", "context", ",", "'put'", ",", "conc", ",", "container", ",", "objects", ",", "_cli_ping_object_put", ",", "ping_ring_object_puts", ")", ":", "with", "context", ".", "io_manager", ".", "with_stderr", "(", ")", "as", "fp", ":", "fp", ".", "write", "(", "'ERROR put objects did not complete successfully due to '", "'previous error; but continuing\\n'", ")", "fp", ".", "flush", "(", ")", "if", "_cli_ping_objects", "(", "context", ",", "'get'", ",", "conc", ",", "container", ",", "objects", ",", "_cli_ping_object_get", ",", "ping_ring_object_gets", ")", ":", "with", "context", ".", "io_manager", ".", "with_stderr", "(", ")", "as", "fp", ":", "fp", ".", "write", "(", "'ERROR get objects did not complete successfully due to '", "'previous error; but continuing\\n'", ")", "fp", ".", "flush", "(", ")", "if", "_cli_ping_objects", "(", "context", ",", "'delete'", ",", "conc", ",", "container", ",", "objects", ",", "_cli_ping_object_delete", ",", "ping_ring_object_deletes", ")", ":", "with", "context", ".", "io_manager", ".", "with_stderr", "(", ")", "as", "fp", ":", "fp", ".", "write", "(", "'ERROR delete objects did not complete successfully due to '", "'previous error; but continuing\\n'", ")", "fp", ".", "flush", "(", ")", "for", "attempt", "in", "moves", ".", "range", "(", "5", ")", ":", "if", "attempt", ":", "sleep", "(", "2", "**", "attempt", ")", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "try", ":", "_cli_ping_status", "(", "context", ",", "'container delete'", ",", "'-'", ",", "*", "client", ".", "delete_container", "(", "container", ")", ")", "break", "except", "ReturnCode", "as", "err", ":", "with", "context", ".", "io_manager", ".", "with_stderr", "(", ")", "as", "fp", ":", "fp", ".", "write", "(", "str", "(", "err", ")", ")", "fp", ".", "write", "(", "'\\n'", ")", "fp", ".", "flush", "(", ")", "else", ":", "with", "context", ".", "io_manager", ".", "with_stderr", "(", ")", "as", "fp", ":", "fp", ".", "write", "(", "'ERROR could not confirm deletion of container due to '", "'previous error; but continuing\\n'", ")", "fp", ".", "flush", "(", ")", "end", "=", "time", ".", "time", "(", ")", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "fp", ":", "if", "context", ".", "graphite", ":", "fp", ".", "write", "(", "'%s.ping_overall %.02f %d\\n'", "%", "(", "context", ".", "graphite", ",", "end", "-", "context", ".", "ping_begin", ",", "time", ".", "time", "(", ")", ")", ")", "if", "context", ".", "ping_verbose", ":", "fp", ".", "write", "(", "'% 6.02fs total\\n'", "%", "(", "end", "-", "context", ".", "ping_begin", ")", ")", "elif", "not", "context", ".", "graphite", ":", "fp", ".", "write", "(", "'%.02fs\\n'", "%", "(", "end", "-", "context", ".", "ping_begin", ")", ")", "fp", ".", "flush", "(", ")", "ping_ring_overall", "=", "collections", ".", "defaultdict", "(", "lambda", ":", "[", "]", ")", "_cli_ping_ring_report", "(", "context", ",", "ping_ring_object_puts", ",", "'PUT'", ")", "for", "ip", ",", "timings", "in", "six", ".", "iteritems", "(", "ping_ring_object_puts", ")", ":", "ping_ring_overall", "[", "ip", "]", ".", "extend", "(", "timings", ")", "_cli_ping_ring_report", "(", "context", ",", "ping_ring_object_gets", ",", "'GET'", ")", "for", "ip", ",", "timings", "in", "six", ".", "iteritems", "(", "ping_ring_object_gets", ")", ":", "ping_ring_overall", "[", "ip", "]", ".", "extend", "(", "timings", ")", "_cli_ping_ring_report", "(", "context", ",", "ping_ring_object_deletes", ",", "'DELETE'", ")", "for", "ip", ",", "timings", "in", "six", ".", "iteritems", "(", "ping_ring_object_deletes", ")", ":", "ping_ring_overall", "[", "ip", "]", ".", "extend", "(", "timings", ")", "_cli_ping_ring_report", "(", "context", ",", "ping_ring_overall", ",", "'overall'", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_get_account_listing
Performs a GET on the account as a listing request. See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information.
swiftly/cli/get.py
def cli_get_account_listing(context): """ Performs a GET on the account as a listing request. See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information. """ limit = context.query.get('limit') delimiter = context.query.get('delimiter') prefix = context.query.get('prefix') marker = context.query.get('marker') end_marker = context.query.get('end_marker') if context.raw: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( decode_json=False, headers=context.headers, limit=limit, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if hasattr(contents, 'read'): contents = contents.read() if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode('listing account: %s %s' % (status, reason)) with context.io_manager.with_stdout() as fp: if context.output_headers: context.write_headers( fp, headers, context.muted_account_headers) fp.write(contents) fp.flush() return with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( headers=context.headers, limit=limit, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode('listing account: %s %s' % (status, reason)) if context.output_headers and not context.all_objects: with context.io_manager.with_stdout() as fp: context.write_headers( fp, headers, context.muted_account_headers) while contents: if context.all_objects: new_context = context.copy() new_context.query = dict(new_context.query) for remove in ( 'limit', 'delimiter', 'prefix', 'marker', 'end_marker'): if remove in new_context.query: del new_context.query[remove] for item in contents: if 'name' in item: new_path = item['name'].encode('utf8') cli_get_container_listing(new_context, new_path) else: with context.io_manager.with_stdout() as fp: for item in contents: if context.full: fp.write('%13s %13s ' % ( item.get('bytes', '-'), item.get('count', '-'))) fp.write(item.get( 'name', item.get('subdir'))) fp.write('\n') fp.flush() if limit: break marker = contents[-1].get('name', contents[-1].get('subdir', '')) with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( headers=context.headers, limit=limit, delimiter=delimiter, prefix=prefix, end_marker=end_marker, marker=marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode('listing account: %s %s' % (status, reason))
def cli_get_account_listing(context): """ Performs a GET on the account as a listing request. See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information. """ limit = context.query.get('limit') delimiter = context.query.get('delimiter') prefix = context.query.get('prefix') marker = context.query.get('marker') end_marker = context.query.get('end_marker') if context.raw: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( decode_json=False, headers=context.headers, limit=limit, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if hasattr(contents, 'read'): contents = contents.read() if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode('listing account: %s %s' % (status, reason)) with context.io_manager.with_stdout() as fp: if context.output_headers: context.write_headers( fp, headers, context.muted_account_headers) fp.write(contents) fp.flush() return with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( headers=context.headers, limit=limit, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode('listing account: %s %s' % (status, reason)) if context.output_headers and not context.all_objects: with context.io_manager.with_stdout() as fp: context.write_headers( fp, headers, context.muted_account_headers) while contents: if context.all_objects: new_context = context.copy() new_context.query = dict(new_context.query) for remove in ( 'limit', 'delimiter', 'prefix', 'marker', 'end_marker'): if remove in new_context.query: del new_context.query[remove] for item in contents: if 'name' in item: new_path = item['name'].encode('utf8') cli_get_container_listing(new_context, new_path) else: with context.io_manager.with_stdout() as fp: for item in contents: if context.full: fp.write('%13s %13s ' % ( item.get('bytes', '-'), item.get('count', '-'))) fp.write(item.get( 'name', item.get('subdir'))) fp.write('\n') fp.flush() if limit: break marker = contents[-1].get('name', contents[-1].get('subdir', '')) with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_account( headers=context.headers, limit=limit, delimiter=delimiter, prefix=prefix, end_marker=end_marker, marker=marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode('listing account: %s %s' % (status, reason))
[ "Performs", "a", "GET", "on", "the", "account", "as", "a", "listing", "request", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/get.py#L79-L161
[ "def", "cli_get_account_listing", "(", "context", ")", ":", "limit", "=", "context", ".", "query", ".", "get", "(", "'limit'", ")", "delimiter", "=", "context", ".", "query", ".", "get", "(", "'delimiter'", ")", "prefix", "=", "context", ".", "query", ".", "get", "(", "'prefix'", ")", "marker", "=", "context", ".", "query", ".", "get", "(", "'marker'", ")", "end_marker", "=", "context", ".", "query", ".", "get", "(", "'end_marker'", ")", "if", "context", ".", "raw", ":", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_account", "(", "decode_json", "=", "False", ",", "headers", "=", "context", ".", "headers", ",", "limit", "=", "limit", ",", "marker", "=", "marker", ",", "end_marker", "=", "end_marker", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "hasattr", "(", "contents", ",", "'read'", ")", ":", "contents", "=", "contents", ".", "read", "(", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "raise", "ReturnCode", "(", "'listing account: %s %s'", "%", "(", "status", ",", "reason", ")", ")", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "fp", ":", "if", "context", ".", "output_headers", ":", "context", ".", "write_headers", "(", "fp", ",", "headers", ",", "context", ".", "muted_account_headers", ")", "fp", ".", "write", "(", "contents", ")", "fp", ".", "flush", "(", ")", "return", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_account", "(", "headers", "=", "context", ".", "headers", ",", "limit", "=", "limit", ",", "marker", "=", "marker", ",", "end_marker", "=", "end_marker", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "if", "hasattr", "(", "contents", ",", "'read'", ")", ":", "contents", ".", "read", "(", ")", "raise", "ReturnCode", "(", "'listing account: %s %s'", "%", "(", "status", ",", "reason", ")", ")", "if", "context", ".", "output_headers", "and", "not", "context", ".", "all_objects", ":", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "fp", ":", "context", ".", "write_headers", "(", "fp", ",", "headers", ",", "context", ".", "muted_account_headers", ")", "while", "contents", ":", "if", "context", ".", "all_objects", ":", "new_context", "=", "context", ".", "copy", "(", ")", "new_context", ".", "query", "=", "dict", "(", "new_context", ".", "query", ")", "for", "remove", "in", "(", "'limit'", ",", "'delimiter'", ",", "'prefix'", ",", "'marker'", ",", "'end_marker'", ")", ":", "if", "remove", "in", "new_context", ".", "query", ":", "del", "new_context", ".", "query", "[", "remove", "]", "for", "item", "in", "contents", ":", "if", "'name'", "in", "item", ":", "new_path", "=", "item", "[", "'name'", "]", ".", "encode", "(", "'utf8'", ")", "cli_get_container_listing", "(", "new_context", ",", "new_path", ")", "else", ":", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "fp", ":", "for", "item", "in", "contents", ":", "if", "context", ".", "full", ":", "fp", ".", "write", "(", "'%13s %13s '", "%", "(", "item", ".", "get", "(", "'bytes'", ",", "'-'", ")", ",", "item", ".", "get", "(", "'count'", ",", "'-'", ")", ")", ")", "fp", ".", "write", "(", "item", ".", "get", "(", "'name'", ",", "item", ".", "get", "(", "'subdir'", ")", ")", ")", "fp", ".", "write", "(", "'\\n'", ")", "fp", ".", "flush", "(", ")", "if", "limit", ":", "break", "marker", "=", "contents", "[", "-", "1", "]", ".", "get", "(", "'name'", ",", "contents", "[", "-", "1", "]", ".", "get", "(", "'subdir'", ",", "''", ")", ")", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_account", "(", "headers", "=", "context", ".", "headers", ",", "limit", "=", "limit", ",", "delimiter", "=", "delimiter", ",", "prefix", "=", "prefix", ",", "end_marker", "=", "end_marker", ",", "marker", "=", "marker", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "if", "hasattr", "(", "contents", ",", "'read'", ")", ":", "contents", ".", "read", "(", ")", "raise", "ReturnCode", "(", "'listing account: %s %s'", "%", "(", "status", ",", "reason", ")", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_get_container_listing
Performs a GET on the container as a listing request. See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information.
swiftly/cli/get.py
def cli_get_container_listing(context, path=None): """ Performs a GET on the container as a listing request. See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information. """ path = path.strip('/') if path else None if not path or '/' in path: raise ReturnCode( 'tried to get a container listing for non-container path %r' % path) context.suppress_container_name = True limit = context.query.get('limit') delimiter = context.query.get('delimiter') prefix = context.query.get('prefix') marker = context.query.get('marker') end_marker = context.query.get('end_marker') if context.raw: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, decode_json=False, headers=context.headers, limit=limit, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if hasattr(contents, 'read'): contents = contents.read() if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) with context.io_manager.with_stdout() as fp: if context.output_headers: context.write_headers( fp, headers, context.muted_container_headers) fp.write(contents) fp.flush() return with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, headers=context.headers, limit=limit, delimiter=delimiter, prefix=prefix, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) if context.output_headers and not context.all_objects: with context.io_manager.with_stdout() as fp: context.write_headers( fp, headers, context.muted_container_headers) conc = Concurrency(context.concurrency) while contents: if context.all_objects: new_context = context.copy() new_context.query = dict(new_context.query) for remove in ( 'limit', 'delimiter', 'prefix', 'marker', 'end_marker'): if remove in new_context.query: del new_context.query[remove] for item in contents: if 'name' in item: for (exc_type, exc_value, exc_tb, result) in \ six.itervalues(conc.get_results()): if exc_value: conc.join() raise exc_value new_path = path + '/' + item['name'].encode('utf8') conc.spawn(new_path, cli_get, new_context, new_path) else: with context.io_manager.with_stdout() as fp: for item in contents: if context.full: fp.write('%13s %22s %32s %25s ' % ( item.get('bytes', '-'), item.get('last_modified', '-')[:22].replace( 'T', ' '), item.get('hash', '-'), item.get('content_type', '-'))) fp.write(item.get( 'name', item.get('subdir'))) fp.write('\n') fp.flush() if limit: break marker = contents[-1].get('name', contents[-1].get('subdir', '')) with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, headers=context.headers, limit=limit, delimiter=delimiter, prefix=prefix, end_marker=end_marker, marker=marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) conc.join() for (exc_type, exc_value, exc_tb, result) in \ six.itervalues(conc.get_results()): if exc_value: raise exc_value
def cli_get_container_listing(context, path=None): """ Performs a GET on the container as a listing request. See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information. """ path = path.strip('/') if path else None if not path or '/' in path: raise ReturnCode( 'tried to get a container listing for non-container path %r' % path) context.suppress_container_name = True limit = context.query.get('limit') delimiter = context.query.get('delimiter') prefix = context.query.get('prefix') marker = context.query.get('marker') end_marker = context.query.get('end_marker') if context.raw: with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, decode_json=False, headers=context.headers, limit=limit, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if hasattr(contents, 'read'): contents = contents.read() if status // 100 != 2: if status == 404 and context.ignore_404: return raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) with context.io_manager.with_stdout() as fp: if context.output_headers: context.write_headers( fp, headers, context.muted_container_headers) fp.write(contents) fp.flush() return with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, headers=context.headers, limit=limit, delimiter=delimiter, prefix=prefix, marker=marker, end_marker=end_marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) if context.output_headers and not context.all_objects: with context.io_manager.with_stdout() as fp: context.write_headers( fp, headers, context.muted_container_headers) conc = Concurrency(context.concurrency) while contents: if context.all_objects: new_context = context.copy() new_context.query = dict(new_context.query) for remove in ( 'limit', 'delimiter', 'prefix', 'marker', 'end_marker'): if remove in new_context.query: del new_context.query[remove] for item in contents: if 'name' in item: for (exc_type, exc_value, exc_tb, result) in \ six.itervalues(conc.get_results()): if exc_value: conc.join() raise exc_value new_path = path + '/' + item['name'].encode('utf8') conc.spawn(new_path, cli_get, new_context, new_path) else: with context.io_manager.with_stdout() as fp: for item in contents: if context.full: fp.write('%13s %22s %32s %25s ' % ( item.get('bytes', '-'), item.get('last_modified', '-')[:22].replace( 'T', ' '), item.get('hash', '-'), item.get('content_type', '-'))) fp.write(item.get( 'name', item.get('subdir'))) fp.write('\n') fp.flush() if limit: break marker = contents[-1].get('name', contents[-1].get('subdir', '')) with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_container( path, headers=context.headers, limit=limit, delimiter=delimiter, prefix=prefix, end_marker=end_marker, marker=marker, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode( 'listing container %r: %s %s' % (path, status, reason)) conc.join() for (exc_type, exc_value, exc_tb, result) in \ six.itervalues(conc.get_results()): if exc_value: raise exc_value
[ "Performs", "a", "GET", "on", "the", "container", "as", "a", "listing", "request", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/get.py#L164-L270
[ "def", "cli_get_container_listing", "(", "context", ",", "path", "=", "None", ")", ":", "path", "=", "path", ".", "strip", "(", "'/'", ")", "if", "path", "else", "None", "if", "not", "path", "or", "'/'", "in", "path", ":", "raise", "ReturnCode", "(", "'tried to get a container listing for non-container path %r'", "%", "path", ")", "context", ".", "suppress_container_name", "=", "True", "limit", "=", "context", ".", "query", ".", "get", "(", "'limit'", ")", "delimiter", "=", "context", ".", "query", ".", "get", "(", "'delimiter'", ")", "prefix", "=", "context", ".", "query", ".", "get", "(", "'prefix'", ")", "marker", "=", "context", ".", "query", ".", "get", "(", "'marker'", ")", "end_marker", "=", "context", ".", "query", ".", "get", "(", "'end_marker'", ")", "if", "context", ".", "raw", ":", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_container", "(", "path", ",", "decode_json", "=", "False", ",", "headers", "=", "context", ".", "headers", ",", "limit", "=", "limit", ",", "marker", "=", "marker", ",", "end_marker", "=", "end_marker", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "hasattr", "(", "contents", ",", "'read'", ")", ":", "contents", "=", "contents", ".", "read", "(", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "raise", "ReturnCode", "(", "'listing container %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "fp", ":", "if", "context", ".", "output_headers", ":", "context", ".", "write_headers", "(", "fp", ",", "headers", ",", "context", ".", "muted_container_headers", ")", "fp", ".", "write", "(", "contents", ")", "fp", ".", "flush", "(", ")", "return", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_container", "(", "path", ",", "headers", "=", "context", ".", "headers", ",", "limit", "=", "limit", ",", "delimiter", "=", "delimiter", ",", "prefix", "=", "prefix", ",", "marker", "=", "marker", ",", "end_marker", "=", "end_marker", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "if", "hasattr", "(", "contents", ",", "'read'", ")", ":", "contents", ".", "read", "(", ")", "raise", "ReturnCode", "(", "'listing container %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")", "if", "context", ".", "output_headers", "and", "not", "context", ".", "all_objects", ":", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "fp", ":", "context", ".", "write_headers", "(", "fp", ",", "headers", ",", "context", ".", "muted_container_headers", ")", "conc", "=", "Concurrency", "(", "context", ".", "concurrency", ")", "while", "contents", ":", "if", "context", ".", "all_objects", ":", "new_context", "=", "context", ".", "copy", "(", ")", "new_context", ".", "query", "=", "dict", "(", "new_context", ".", "query", ")", "for", "remove", "in", "(", "'limit'", ",", "'delimiter'", ",", "'prefix'", ",", "'marker'", ",", "'end_marker'", ")", ":", "if", "remove", "in", "new_context", ".", "query", ":", "del", "new_context", ".", "query", "[", "remove", "]", "for", "item", "in", "contents", ":", "if", "'name'", "in", "item", ":", "for", "(", "exc_type", ",", "exc_value", ",", "exc_tb", ",", "result", ")", "in", "six", ".", "itervalues", "(", "conc", ".", "get_results", "(", ")", ")", ":", "if", "exc_value", ":", "conc", ".", "join", "(", ")", "raise", "exc_value", "new_path", "=", "path", "+", "'/'", "+", "item", "[", "'name'", "]", ".", "encode", "(", "'utf8'", ")", "conc", ".", "spawn", "(", "new_path", ",", "cli_get", ",", "new_context", ",", "new_path", ")", "else", ":", "with", "context", ".", "io_manager", ".", "with_stdout", "(", ")", "as", "fp", ":", "for", "item", "in", "contents", ":", "if", "context", ".", "full", ":", "fp", ".", "write", "(", "'%13s %22s %32s %25s '", "%", "(", "item", ".", "get", "(", "'bytes'", ",", "'-'", ")", ",", "item", ".", "get", "(", "'last_modified'", ",", "'-'", ")", "[", ":", "22", "]", ".", "replace", "(", "'T'", ",", "' '", ")", ",", "item", ".", "get", "(", "'hash'", ",", "'-'", ")", ",", "item", ".", "get", "(", "'content_type'", ",", "'-'", ")", ")", ")", "fp", ".", "write", "(", "item", ".", "get", "(", "'name'", ",", "item", ".", "get", "(", "'subdir'", ")", ")", ")", "fp", ".", "write", "(", "'\\n'", ")", "fp", ".", "flush", "(", ")", "if", "limit", ":", "break", "marker", "=", "contents", "[", "-", "1", "]", ".", "get", "(", "'name'", ",", "contents", "[", "-", "1", "]", ".", "get", "(", "'subdir'", ",", "''", ")", ")", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_container", "(", "path", ",", "headers", "=", "context", ".", "headers", ",", "limit", "=", "limit", ",", "delimiter", "=", "delimiter", ",", "prefix", "=", "prefix", ",", "end_marker", "=", "end_marker", ",", "marker", "=", "marker", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "if", "hasattr", "(", "contents", ",", "'read'", ")", ":", "contents", ".", "read", "(", ")", "raise", "ReturnCode", "(", "'listing container %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")", "conc", ".", "join", "(", ")", "for", "(", "exc_type", ",", "exc_value", ",", "exc_tb", ",", "result", ")", "in", "six", ".", "itervalues", "(", "conc", ".", "get_results", "(", ")", ")", ":", "if", "exc_value", ":", "raise", "exc_value" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_get
Performs a GET on the item (account, container, or object). See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information.
swiftly/cli/get.py
def cli_get(context, path=None): """ Performs a GET on the item (account, container, or object). See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information. """ path = path.lstrip('/') if path else None if not path: return cli_get_account_listing(context) elif '/' not in path.rstrip('/'): return cli_get_container_listing(context, path) status, reason, headers, contents = 0, 'Unknown', {}, '' with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_object( *path.split('/', 1), headers=context.headers, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode( 'getting object %r: %s %s' % (path, status, reason)) if context.decrypt: crypt_type = contents.read(1) if crypt_type == AES256CBC: contents = FileLikeIter(aes_decrypt( context.decrypt, contents, chunk_size=getattr(client, 'chunk_size', 65536))) else: raise ReturnCode( 'getting object %r: contents encrypted with unsupported ' 'type %r' % (path, crypt_type)) def disk_closed_callback(disk_path): if context.remove_empty_files and not os.path.getsize(disk_path): os.unlink(disk_path) if context.io_manager.stdout_root: dirname = os.path.dirname(disk_path) while dirname and dirname.startswith( context.io_manager.stdout_root): try: os.rmdir(dirname) except OSError: pass dirname = os.path.dirname(dirname) return if (headers.get('content-type') in ['text/directory', 'application/directory'] and headers.get('content-length') == '0'): os.unlink(disk_path) os.makedirs(disk_path) mtime = 0 if 'x-object-meta-mtime' in headers: mtime = float(headers['x-object-meta-mtime']) elif 'last-modified' in headers: mtime = time.mktime(time.strptime( headers['last-modified'], '%a, %d %b %Y %H:%M:%S %Z')) if mtime: os.utime(disk_path, (mtime, mtime)) out_path = path if context.suppress_container_name: out_path = out_path.split('/', 1)[1] out_path = context.io_manager.client_path_to_os_path(out_path) with context.io_manager.with_stdout( out_path, disk_closed_callback=disk_closed_callback) as fp: if context.output_headers: context.write_headers( fp, headers, context.muted_object_headers) fp.write('\n') chunk = contents.read(65536) while chunk: fp.write(chunk) chunk = contents.read(65536) fp.flush()
def cli_get(context, path=None): """ Performs a GET on the item (account, container, or object). See :py:mod:`swiftly.cli.get` for context usage information. See :py:class:`CLIGet` for more information. """ path = path.lstrip('/') if path else None if not path: return cli_get_account_listing(context) elif '/' not in path.rstrip('/'): return cli_get_container_listing(context, path) status, reason, headers, contents = 0, 'Unknown', {}, '' with context.client_manager.with_client() as client: status, reason, headers, contents = client.get_object( *path.split('/', 1), headers=context.headers, query=context.query, cdn=context.cdn) if status // 100 != 2: if status == 404 and context.ignore_404: return if hasattr(contents, 'read'): contents.read() raise ReturnCode( 'getting object %r: %s %s' % (path, status, reason)) if context.decrypt: crypt_type = contents.read(1) if crypt_type == AES256CBC: contents = FileLikeIter(aes_decrypt( context.decrypt, contents, chunk_size=getattr(client, 'chunk_size', 65536))) else: raise ReturnCode( 'getting object %r: contents encrypted with unsupported ' 'type %r' % (path, crypt_type)) def disk_closed_callback(disk_path): if context.remove_empty_files and not os.path.getsize(disk_path): os.unlink(disk_path) if context.io_manager.stdout_root: dirname = os.path.dirname(disk_path) while dirname and dirname.startswith( context.io_manager.stdout_root): try: os.rmdir(dirname) except OSError: pass dirname = os.path.dirname(dirname) return if (headers.get('content-type') in ['text/directory', 'application/directory'] and headers.get('content-length') == '0'): os.unlink(disk_path) os.makedirs(disk_path) mtime = 0 if 'x-object-meta-mtime' in headers: mtime = float(headers['x-object-meta-mtime']) elif 'last-modified' in headers: mtime = time.mktime(time.strptime( headers['last-modified'], '%a, %d %b %Y %H:%M:%S %Z')) if mtime: os.utime(disk_path, (mtime, mtime)) out_path = path if context.suppress_container_name: out_path = out_path.split('/', 1)[1] out_path = context.io_manager.client_path_to_os_path(out_path) with context.io_manager.with_stdout( out_path, disk_closed_callback=disk_closed_callback) as fp: if context.output_headers: context.write_headers( fp, headers, context.muted_object_headers) fp.write('\n') chunk = contents.read(65536) while chunk: fp.write(chunk) chunk = contents.read(65536) fp.flush()
[ "Performs", "a", "GET", "on", "the", "item", "(", "account", "container", "or", "object", ")", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/get.py#L273-L350
[ "def", "cli_get", "(", "context", ",", "path", "=", "None", ")", ":", "path", "=", "path", ".", "lstrip", "(", "'/'", ")", "if", "path", "else", "None", "if", "not", "path", ":", "return", "cli_get_account_listing", "(", "context", ")", "elif", "'/'", "not", "in", "path", ".", "rstrip", "(", "'/'", ")", ":", "return", "cli_get_container_listing", "(", "context", ",", "path", ")", "status", ",", "reason", ",", "headers", ",", "contents", "=", "0", ",", "'Unknown'", ",", "{", "}", ",", "''", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "get_object", "(", "*", "path", ".", "split", "(", "'/'", ",", "1", ")", ",", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ")", "if", "status", "//", "100", "!=", "2", ":", "if", "status", "==", "404", "and", "context", ".", "ignore_404", ":", "return", "if", "hasattr", "(", "contents", ",", "'read'", ")", ":", "contents", ".", "read", "(", ")", "raise", "ReturnCode", "(", "'getting object %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")", "if", "context", ".", "decrypt", ":", "crypt_type", "=", "contents", ".", "read", "(", "1", ")", "if", "crypt_type", "==", "AES256CBC", ":", "contents", "=", "FileLikeIter", "(", "aes_decrypt", "(", "context", ".", "decrypt", ",", "contents", ",", "chunk_size", "=", "getattr", "(", "client", ",", "'chunk_size'", ",", "65536", ")", ")", ")", "else", ":", "raise", "ReturnCode", "(", "'getting object %r: contents encrypted with unsupported '", "'type %r'", "%", "(", "path", ",", "crypt_type", ")", ")", "def", "disk_closed_callback", "(", "disk_path", ")", ":", "if", "context", ".", "remove_empty_files", "and", "not", "os", ".", "path", ".", "getsize", "(", "disk_path", ")", ":", "os", ".", "unlink", "(", "disk_path", ")", "if", "context", ".", "io_manager", ".", "stdout_root", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "disk_path", ")", "while", "dirname", "and", "dirname", ".", "startswith", "(", "context", ".", "io_manager", ".", "stdout_root", ")", ":", "try", ":", "os", ".", "rmdir", "(", "dirname", ")", "except", "OSError", ":", "pass", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "dirname", ")", "return", "if", "(", "headers", ".", "get", "(", "'content-type'", ")", "in", "[", "'text/directory'", ",", "'application/directory'", "]", "and", "headers", ".", "get", "(", "'content-length'", ")", "==", "'0'", ")", ":", "os", ".", "unlink", "(", "disk_path", ")", "os", ".", "makedirs", "(", "disk_path", ")", "mtime", "=", "0", "if", "'x-object-meta-mtime'", "in", "headers", ":", "mtime", "=", "float", "(", "headers", "[", "'x-object-meta-mtime'", "]", ")", "elif", "'last-modified'", "in", "headers", ":", "mtime", "=", "time", ".", "mktime", "(", "time", ".", "strptime", "(", "headers", "[", "'last-modified'", "]", ",", "'%a, %d %b %Y %H:%M:%S %Z'", ")", ")", "if", "mtime", ":", "os", ".", "utime", "(", "disk_path", ",", "(", "mtime", ",", "mtime", ")", ")", "out_path", "=", "path", "if", "context", ".", "suppress_container_name", ":", "out_path", "=", "out_path", ".", "split", "(", "'/'", ",", "1", ")", "[", "1", "]", "out_path", "=", "context", ".", "io_manager", ".", "client_path_to_os_path", "(", "out_path", ")", "with", "context", ".", "io_manager", ".", "with_stdout", "(", "out_path", ",", "disk_closed_callback", "=", "disk_closed_callback", ")", "as", "fp", ":", "if", "context", ".", "output_headers", ":", "context", ".", "write_headers", "(", "fp", ",", "headers", ",", "context", ".", "muted_object_headers", ")", "fp", ".", "write", "(", "'\\n'", ")", "chunk", "=", "contents", ".", "read", "(", "65536", ")", "while", "chunk", ":", "fp", ".", "write", "(", "chunk", ")", "chunk", "=", "contents", ".", "read", "(", "65536", ")", "fp", ".", "flush", "(", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
LocalClient.request
See :py:func:`swiftly.client.client.Client.request`
swiftly/client/localclient.py
def request(self, method, path, contents, headers, decode_json=False, stream=False, query=None, cdn=False): """ See :py:func:`swiftly.client.client.Client.request` """ if cdn: raise Exception('CDN not yet supported with LocalClient') if isinstance(contents, six.string_types): contents = StringIO(contents) if not headers: headers = {} if not query: query = {} rpath = path.lstrip('/') if '/' in rpath: container_name, object_name = rpath.split('/', 1) else: container_name = rpath object_name = '' if not container_name: status, reason, hdrs, body = self._account( method, contents, headers, stream, query, cdn) elif not object_name: status, reason, hdrs, body = self._container( method, container_name, contents, headers, stream, query, cdn) else: status, reason, hdrs, body = self._object( method, container_name, object_name, contents, headers, stream, query, cdn) if status and status // 100 != 5: if not stream and decode_json and status // 100 == 2: if body: body = loads(body) else: body = None return (status, reason, hdrs, body) raise Exception('%s %s failed: %s %s' % (method, path, status, reason))
def request(self, method, path, contents, headers, decode_json=False, stream=False, query=None, cdn=False): """ See :py:func:`swiftly.client.client.Client.request` """ if cdn: raise Exception('CDN not yet supported with LocalClient') if isinstance(contents, six.string_types): contents = StringIO(contents) if not headers: headers = {} if not query: query = {} rpath = path.lstrip('/') if '/' in rpath: container_name, object_name = rpath.split('/', 1) else: container_name = rpath object_name = '' if not container_name: status, reason, hdrs, body = self._account( method, contents, headers, stream, query, cdn) elif not object_name: status, reason, hdrs, body = self._container( method, container_name, contents, headers, stream, query, cdn) else: status, reason, hdrs, body = self._object( method, container_name, object_name, contents, headers, stream, query, cdn) if status and status // 100 != 5: if not stream and decode_json and status // 100 == 2: if body: body = loads(body) else: body = None return (status, reason, hdrs, body) raise Exception('%s %s failed: %s %s' % (method, path, status, reason))
[ "See", ":", "py", ":", "func", ":", "swiftly", ".", "client", ".", "client", ".", "Client", ".", "request" ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/localclient.py#L125-L161
[ "def", "request", "(", "self", ",", "method", ",", "path", ",", "contents", ",", "headers", ",", "decode_json", "=", "False", ",", "stream", "=", "False", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "if", "cdn", ":", "raise", "Exception", "(", "'CDN not yet supported with LocalClient'", ")", "if", "isinstance", "(", "contents", ",", "six", ".", "string_types", ")", ":", "contents", "=", "StringIO", "(", "contents", ")", "if", "not", "headers", ":", "headers", "=", "{", "}", "if", "not", "query", ":", "query", "=", "{", "}", "rpath", "=", "path", ".", "lstrip", "(", "'/'", ")", "if", "'/'", "in", "rpath", ":", "container_name", ",", "object_name", "=", "rpath", ".", "split", "(", "'/'", ",", "1", ")", "else", ":", "container_name", "=", "rpath", "object_name", "=", "''", "if", "not", "container_name", ":", "status", ",", "reason", ",", "hdrs", ",", "body", "=", "self", ".", "_account", "(", "method", ",", "contents", ",", "headers", ",", "stream", ",", "query", ",", "cdn", ")", "elif", "not", "object_name", ":", "status", ",", "reason", ",", "hdrs", ",", "body", "=", "self", ".", "_container", "(", "method", ",", "container_name", ",", "contents", ",", "headers", ",", "stream", ",", "query", ",", "cdn", ")", "else", ":", "status", ",", "reason", ",", "hdrs", ",", "body", "=", "self", ".", "_object", "(", "method", ",", "container_name", ",", "object_name", ",", "contents", ",", "headers", ",", "stream", ",", "query", ",", "cdn", ")", "if", "status", "and", "status", "//", "100", "!=", "5", ":", "if", "not", "stream", "and", "decode_json", "and", "status", "//", "100", "==", "2", ":", "if", "body", ":", "body", "=", "loads", "(", "body", ")", "else", ":", "body", "=", "None", "return", "(", "status", ",", "reason", ",", "hdrs", ",", "body", ")", "raise", "Exception", "(", "'%s %s failed: %s %s'", "%", "(", "method", ",", "path", ",", "status", ",", "reason", ")", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
CLI._resolve_option
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 instance as returned by optparse. :param option_name: The name of the option, such as ``auth_url``. :param section_name: The name of the section, such as ``swiftly``.
swiftly/cli/cli.py
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 instance as returned by optparse. :param option_name: The name of the option, such as ``auth_url``. :param section_name: The name of the section, such as ``swiftly``. """ if getattr(options, option_name, None) is not None: return if option_name.startswith(section_name + '_'): environ_name = option_name.upper() conf_name = option_name[len(section_name) + 1:] else: environ_name = (section_name + '_' + option_name).upper() conf_name = option_name setattr( options, option_name, os.environ.get( environ_name, (self.context.conf.get(section_name, {})).get(conf_name)))
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 instance as returned by optparse. :param option_name: The name of the option, such as ``auth_url``. :param section_name: The name of the section, such as ``swiftly``. """ if getattr(options, option_name, None) is not None: return if option_name.startswith(section_name + '_'): environ_name = option_name.upper() conf_name = option_name[len(section_name) + 1:] else: environ_name = (section_name + '_' + option_name).upper() conf_name = option_name setattr( options, option_name, os.environ.get( environ_name, (self.context.conf.get(section_name, {})).get(conf_name)))
[ "Resolves", "an", "option", "value", "into", "options", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/cli.py#L433-L458
[ "def", "_resolve_option", "(", "self", ",", "options", ",", "option_name", ",", "section_name", ")", ":", "if", "getattr", "(", "options", ",", "option_name", ",", "None", ")", "is", "not", "None", ":", "return", "if", "option_name", ".", "startswith", "(", "section_name", "+", "'_'", ")", ":", "environ_name", "=", "option_name", ".", "upper", "(", ")", "conf_name", "=", "option_name", "[", "len", "(", "section_name", ")", "+", "1", ":", "]", "else", ":", "environ_name", "=", "(", "section_name", "+", "'_'", "+", "option_name", ")", ".", "upper", "(", ")", "conf_name", "=", "option_name", "setattr", "(", "options", ",", "option_name", ",", "os", ".", "environ", ".", "get", "(", "environ_name", ",", "(", "self", ".", "context", ".", "conf", ".", "get", "(", "section_name", ",", "{", "}", ")", ")", ".", "get", "(", "conf_name", ")", ")", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
cli_post
Performs a POST on the item (account, container, or object). See :py:mod:`swiftly.cli.post` for context usage information. See :py:class:`CLIPost` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param path: The path to the item to issue a POST for. :param body: The body send along with the POST.
swiftly/cli/post.py
def cli_post(context, path, body=None): """ Performs a POST on the item (account, container, or object). See :py:mod:`swiftly.cli.post` for context usage information. See :py:class:`CLIPost` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param path: The path to the item to issue a POST for. :param body: The body send along with the POST. """ path = path.lstrip('/') if path else '' status, reason, headers, contents = 0, 'Unknown', {}, '' with context.client_manager.with_client() as client: if not path: status, reason, headers, contents = client.post_account( headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: raise ReturnCode('posting account: %s %s' % (status, reason)) elif '/' not in path.rstrip('/'): path = path.rstrip('/') status, reason, headers, contents = client.post_container( path, headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: raise ReturnCode( 'posting container %r: %s %s' % (path, status, reason)) else: status, reason, headers, contents = client.post_object( *path.split('/', 1), headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: raise ReturnCode( 'posting object %r: %s %s' % (path, status, reason))
def cli_post(context, path, body=None): """ Performs a POST on the item (account, container, or object). See :py:mod:`swiftly.cli.post` for context usage information. See :py:class:`CLIPost` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param path: The path to the item to issue a POST for. :param body: The body send along with the POST. """ path = path.lstrip('/') if path else '' status, reason, headers, contents = 0, 'Unknown', {}, '' with context.client_manager.with_client() as client: if not path: status, reason, headers, contents = client.post_account( headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: raise ReturnCode('posting account: %s %s' % (status, reason)) elif '/' not in path.rstrip('/'): path = path.rstrip('/') status, reason, headers, contents = client.post_container( path, headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: raise ReturnCode( 'posting container %r: %s %s' % (path, status, reason)) else: status, reason, headers, contents = client.post_object( *path.split('/', 1), headers=context.headers, query=context.query, cdn=context.cdn, body=body) if status // 100 != 2: raise ReturnCode( 'posting object %r: %s %s' % (path, status, reason))
[ "Performs", "a", "POST", "on", "the", "item", "(", "account", "container", "or", "object", ")", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/post.py#L33-L69
[ "def", "cli_post", "(", "context", ",", "path", ",", "body", "=", "None", ")", ":", "path", "=", "path", ".", "lstrip", "(", "'/'", ")", "if", "path", "else", "''", "status", ",", "reason", ",", "headers", ",", "contents", "=", "0", ",", "'Unknown'", ",", "{", "}", ",", "''", "with", "context", ".", "client_manager", ".", "with_client", "(", ")", "as", "client", ":", "if", "not", "path", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "post_account", "(", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ",", "body", "=", "body", ")", "if", "status", "//", "100", "!=", "2", ":", "raise", "ReturnCode", "(", "'posting account: %s %s'", "%", "(", "status", ",", "reason", ")", ")", "elif", "'/'", "not", "in", "path", ".", "rstrip", "(", "'/'", ")", ":", "path", "=", "path", ".", "rstrip", "(", "'/'", ")", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "post_container", "(", "path", ",", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ",", "body", "=", "body", ")", "if", "status", "//", "100", "!=", "2", ":", "raise", "ReturnCode", "(", "'posting container %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")", "else", ":", "status", ",", "reason", ",", "headers", ",", "contents", "=", "client", ".", "post_object", "(", "*", "path", ".", "split", "(", "'/'", ",", "1", ")", ",", "headers", "=", "context", ".", "headers", ",", "query", "=", "context", ".", "query", ",", "cdn", "=", "context", ".", "cdn", ",", "body", "=", "body", ")", "if", "status", "//", "100", "!=", "2", ":", "raise", "ReturnCode", "(", "'posting object %r: %s %s'", "%", "(", "path", ",", "status", ",", "reason", ")", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
CLIContext.copy
Returns a new CLIContext instance that is a shallow copy of the original, much like dict's copy method.
swiftly/cli/context.py
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(context, item, getattr(self, item)) return context
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(context, item, getattr(self, item)) return context
[ "Returns", "a", "new", "CLIContext", "instance", "that", "is", "a", "shallow", "copy", "of", "the", "original", "much", "like", "dict", "s", "copy", "method", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/context.py#L43-L52
[ "def", "copy", "(", "self", ")", ":", "context", "=", "CLIContext", "(", ")", "for", "item", "in", "dir", "(", "self", ")", ":", "if", "item", "[", "0", "]", "!=", "'_'", "and", "item", "not", "in", "(", "'copy'", ",", "'write_headers'", ")", ":", "setattr", "(", "context", ",", "item", ",", "getattr", "(", "self", ",", "item", ")", ")", "return", "context" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
CLIContext.write_headers
Convenience function to output headers in a formatted fashion to a file-like fp, optionally muting any headers in the mute list.
swiftly/cli/context.py
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 = '%%-%ds %%s\n' % (max(len(k) for k in headers) + 1) for key in sorted(headers): if key in mute: continue fp.write(fmt % (key.title() + ':', headers[key])) fp.flush()
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 = '%%-%ds %%s\n' % (max(len(k) for k in headers) + 1) for key in sorted(headers): if key in mute: continue fp.write(fmt % (key.title() + ':', headers[key])) fp.flush()
[ "Convenience", "function", "to", "output", "headers", "in", "a", "formatted", "fashion", "to", "a", "file", "-", "like", "fp", "optionally", "muting", "any", "headers", "in", "the", "mute", "list", "." ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/cli/context.py#L54-L68
[ "def", "write_headers", "(", "self", ",", "fp", ",", "headers", ",", "mute", "=", "None", ")", ":", "if", "headers", ":", "if", "not", "mute", ":", "mute", "=", "[", "]", "fmt", "=", "'%%-%ds %%s\\n'", "%", "(", "max", "(", "len", "(", "k", ")", "for", "k", "in", "headers", ")", "+", "1", ")", "for", "key", "in", "sorted", "(", "headers", ")", ":", "if", "key", "in", "mute", ":", "continue", "fp", ".", "write", "(", "fmt", "%", "(", "key", ".", "title", "(", ")", "+", "':'", ",", "headers", "[", "key", "]", ")", ")", "fp", ".", "flush", "(", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149
test
DirectClient.request
See :py:func:`swiftly.client.client.Client.request`
swiftly/client/directclient.py
def request(self, method, path, contents, headers, decode_json=False, stream=False, query=None, cdn=False): """ See :py:func:`swiftly.client.client.Client.request` """ if query: path += '?' + '&'.join( ('%s=%s' % (quote(k), quote(v)) if v else quote(k)) for k, v in sorted(six.iteritems(query))) reset_func = self._default_reset_func if isinstance(contents, six.string_types): contents = StringIO(contents) tell = getattr(contents, 'tell', None) seek = getattr(contents, 'seek', None) if tell and seek: try: orig_pos = tell() reset_func = lambda: seek(orig_pos) except Exception: tell = seek = None elif not contents: reset_func = lambda: None status = 0 reason = 'Unknown' attempt = 0 while attempt < self.attempts: attempt += 1 if cdn: conn_path = self.cdn_path else: conn_path = self.storage_path titled_headers = dict((k.title(), v) for k, v in six.iteritems({ 'User-Agent': self.user_agent})) if headers: titled_headers.update( (k.title(), v) for k, v in six.iteritems(headers)) resp = None if not hasattr(contents, 'read'): if method not in self.no_content_methods and contents and \ 'Content-Length' not in titled_headers and \ 'Transfer-Encoding' not in titled_headers: titled_headers['Content-Length'] = str( len(contents or '')) req = self.Request.blank( conn_path + path, environ={'REQUEST_METHOD': method, 'swift_owner': True}, headers=titled_headers, body=contents) verbose_headers = ' '.join( '%s: %s' % (k, v) for k, v in six.iteritems(titled_headers)) self.verbose( '> %s %s %s', method, conn_path + path, verbose_headers) resp = req.get_response(self.swift_proxy) else: req = self.Request.blank( conn_path + path, environ={'REQUEST_METHOD': method, 'swift_owner': True}, headers=titled_headers) content_length = None for h, v in six.iteritems(titled_headers): if h.lower() == 'content-length': content_length = int(v) req.headers[h] = v if method not in self.no_content_methods and \ content_length is None: titled_headers['Transfer-Encoding'] = 'chunked' req.headers['Transfer-Encoding'] = 'chunked' else: req.content_length = content_length req.body_file = contents verbose_headers = ' '.join( '%s: %s' % (k, v) for k, v in six.iteritems(titled_headers)) self.verbose( '> %s %s %s', method, conn_path + path, verbose_headers) resp = req.get_response(self.swift_proxy) status = resp.status_int reason = resp.status.split(' ', 1)[1] hdrs = headers_to_dict(resp.headers.items()) if stream: def iter_reader(size=-1): if size == -1: return ''.join(resp.app_iter) else: try: return next(resp.app_iter) except StopIteration: return '' iter_reader.read = iter_reader value = iter_reader else: value = resp.body self.verbose('< %s %s', status, reason) if status and status // 100 != 5: if not stream and decode_json and status // 100 == 2: if value: value = json.loads(value) else: value = None return (status, reason, hdrs, value) if reset_func: reset_func() self.sleep(2 ** attempt) raise Exception('%s %s failed: %s %s' % (method, path, status, reason))
def request(self, method, path, contents, headers, decode_json=False, stream=False, query=None, cdn=False): """ See :py:func:`swiftly.client.client.Client.request` """ if query: path += '?' + '&'.join( ('%s=%s' % (quote(k), quote(v)) if v else quote(k)) for k, v in sorted(six.iteritems(query))) reset_func = self._default_reset_func if isinstance(contents, six.string_types): contents = StringIO(contents) tell = getattr(contents, 'tell', None) seek = getattr(contents, 'seek', None) if tell and seek: try: orig_pos = tell() reset_func = lambda: seek(orig_pos) except Exception: tell = seek = None elif not contents: reset_func = lambda: None status = 0 reason = 'Unknown' attempt = 0 while attempt < self.attempts: attempt += 1 if cdn: conn_path = self.cdn_path else: conn_path = self.storage_path titled_headers = dict((k.title(), v) for k, v in six.iteritems({ 'User-Agent': self.user_agent})) if headers: titled_headers.update( (k.title(), v) for k, v in six.iteritems(headers)) resp = None if not hasattr(contents, 'read'): if method not in self.no_content_methods and contents and \ 'Content-Length' not in titled_headers and \ 'Transfer-Encoding' not in titled_headers: titled_headers['Content-Length'] = str( len(contents or '')) req = self.Request.blank( conn_path + path, environ={'REQUEST_METHOD': method, 'swift_owner': True}, headers=titled_headers, body=contents) verbose_headers = ' '.join( '%s: %s' % (k, v) for k, v in six.iteritems(titled_headers)) self.verbose( '> %s %s %s', method, conn_path + path, verbose_headers) resp = req.get_response(self.swift_proxy) else: req = self.Request.blank( conn_path + path, environ={'REQUEST_METHOD': method, 'swift_owner': True}, headers=titled_headers) content_length = None for h, v in six.iteritems(titled_headers): if h.lower() == 'content-length': content_length = int(v) req.headers[h] = v if method not in self.no_content_methods and \ content_length is None: titled_headers['Transfer-Encoding'] = 'chunked' req.headers['Transfer-Encoding'] = 'chunked' else: req.content_length = content_length req.body_file = contents verbose_headers = ' '.join( '%s: %s' % (k, v) for k, v in six.iteritems(titled_headers)) self.verbose( '> %s %s %s', method, conn_path + path, verbose_headers) resp = req.get_response(self.swift_proxy) status = resp.status_int reason = resp.status.split(' ', 1)[1] hdrs = headers_to_dict(resp.headers.items()) if stream: def iter_reader(size=-1): if size == -1: return ''.join(resp.app_iter) else: try: return next(resp.app_iter) except StopIteration: return '' iter_reader.read = iter_reader value = iter_reader else: value = resp.body self.verbose('< %s %s', status, reason) if status and status // 100 != 5: if not stream and decode_json and status // 100 == 2: if value: value = json.loads(value) else: value = None return (status, reason, hdrs, value) if reset_func: reset_func() self.sleep(2 ** attempt) raise Exception('%s %s failed: %s %s' % (method, path, status, reason))
[ "See", ":", "py", ":", "func", ":", "swiftly", ".", "client", ".", "client", ".", "Client", ".", "request" ]
gholt/swiftly
python
https://github.com/gholt/swiftly/blob/5bcc1c65323b1caf1f85adbefd9fc4988c072149/swiftly/client/directclient.py#L121-L222
[ "def", "request", "(", "self", ",", "method", ",", "path", ",", "contents", ",", "headers", ",", "decode_json", "=", "False", ",", "stream", "=", "False", ",", "query", "=", "None", ",", "cdn", "=", "False", ")", ":", "if", "query", ":", "path", "+=", "'?'", "+", "'&'", ".", "join", "(", "(", "'%s=%s'", "%", "(", "quote", "(", "k", ")", ",", "quote", "(", "v", ")", ")", "if", "v", "else", "quote", "(", "k", ")", ")", "for", "k", ",", "v", "in", "sorted", "(", "six", ".", "iteritems", "(", "query", ")", ")", ")", "reset_func", "=", "self", ".", "_default_reset_func", "if", "isinstance", "(", "contents", ",", "six", ".", "string_types", ")", ":", "contents", "=", "StringIO", "(", "contents", ")", "tell", "=", "getattr", "(", "contents", ",", "'tell'", ",", "None", ")", "seek", "=", "getattr", "(", "contents", ",", "'seek'", ",", "None", ")", "if", "tell", "and", "seek", ":", "try", ":", "orig_pos", "=", "tell", "(", ")", "reset_func", "=", "lambda", ":", "seek", "(", "orig_pos", ")", "except", "Exception", ":", "tell", "=", "seek", "=", "None", "elif", "not", "contents", ":", "reset_func", "=", "lambda", ":", "None", "status", "=", "0", "reason", "=", "'Unknown'", "attempt", "=", "0", "while", "attempt", "<", "self", ".", "attempts", ":", "attempt", "+=", "1", "if", "cdn", ":", "conn_path", "=", "self", ".", "cdn_path", "else", ":", "conn_path", "=", "self", ".", "storage_path", "titled_headers", "=", "dict", "(", "(", "k", ".", "title", "(", ")", ",", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "{", "'User-Agent'", ":", "self", ".", "user_agent", "}", ")", ")", "if", "headers", ":", "titled_headers", ".", "update", "(", "(", "k", ".", "title", "(", ")", ",", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "headers", ")", ")", "resp", "=", "None", "if", "not", "hasattr", "(", "contents", ",", "'read'", ")", ":", "if", "method", "not", "in", "self", ".", "no_content_methods", "and", "contents", "and", "'Content-Length'", "not", "in", "titled_headers", "and", "'Transfer-Encoding'", "not", "in", "titled_headers", ":", "titled_headers", "[", "'Content-Length'", "]", "=", "str", "(", "len", "(", "contents", "or", "''", ")", ")", "req", "=", "self", ".", "Request", ".", "blank", "(", "conn_path", "+", "path", ",", "environ", "=", "{", "'REQUEST_METHOD'", ":", "method", ",", "'swift_owner'", ":", "True", "}", ",", "headers", "=", "titled_headers", ",", "body", "=", "contents", ")", "verbose_headers", "=", "' '", ".", "join", "(", "'%s: %s'", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "titled_headers", ")", ")", "self", ".", "verbose", "(", "'> %s %s %s'", ",", "method", ",", "conn_path", "+", "path", ",", "verbose_headers", ")", "resp", "=", "req", ".", "get_response", "(", "self", ".", "swift_proxy", ")", "else", ":", "req", "=", "self", ".", "Request", ".", "blank", "(", "conn_path", "+", "path", ",", "environ", "=", "{", "'REQUEST_METHOD'", ":", "method", ",", "'swift_owner'", ":", "True", "}", ",", "headers", "=", "titled_headers", ")", "content_length", "=", "None", "for", "h", ",", "v", "in", "six", ".", "iteritems", "(", "titled_headers", ")", ":", "if", "h", ".", "lower", "(", ")", "==", "'content-length'", ":", "content_length", "=", "int", "(", "v", ")", "req", ".", "headers", "[", "h", "]", "=", "v", "if", "method", "not", "in", "self", ".", "no_content_methods", "and", "content_length", "is", "None", ":", "titled_headers", "[", "'Transfer-Encoding'", "]", "=", "'chunked'", "req", ".", "headers", "[", "'Transfer-Encoding'", "]", "=", "'chunked'", "else", ":", "req", ".", "content_length", "=", "content_length", "req", ".", "body_file", "=", "contents", "verbose_headers", "=", "' '", ".", "join", "(", "'%s: %s'", "%", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "titled_headers", ")", ")", "self", ".", "verbose", "(", "'> %s %s %s'", ",", "method", ",", "conn_path", "+", "path", ",", "verbose_headers", ")", "resp", "=", "req", ".", "get_response", "(", "self", ".", "swift_proxy", ")", "status", "=", "resp", ".", "status_int", "reason", "=", "resp", ".", "status", ".", "split", "(", "' '", ",", "1", ")", "[", "1", "]", "hdrs", "=", "headers_to_dict", "(", "resp", ".", "headers", ".", "items", "(", ")", ")", "if", "stream", ":", "def", "iter_reader", "(", "size", "=", "-", "1", ")", ":", "if", "size", "==", "-", "1", ":", "return", "''", ".", "join", "(", "resp", ".", "app_iter", ")", "else", ":", "try", ":", "return", "next", "(", "resp", ".", "app_iter", ")", "except", "StopIteration", ":", "return", "''", "iter_reader", ".", "read", "=", "iter_reader", "value", "=", "iter_reader", "else", ":", "value", "=", "resp", ".", "body", "self", ".", "verbose", "(", "'< %s %s'", ",", "status", ",", "reason", ")", "if", "status", "and", "status", "//", "100", "!=", "5", ":", "if", "not", "stream", "and", "decode_json", "and", "status", "//", "100", "==", "2", ":", "if", "value", ":", "value", "=", "json", ".", "loads", "(", "value", ")", "else", ":", "value", "=", "None", "return", "(", "status", ",", "reason", ",", "hdrs", ",", "value", ")", "if", "reset_func", ":", "reset_func", "(", ")", "self", ".", "sleep", "(", "2", "**", "attempt", ")", "raise", "Exception", "(", "'%s %s failed: %s %s'", "%", "(", "method", ",", "path", ",", "status", ",", "reason", ")", ")" ]
5bcc1c65323b1caf1f85adbefd9fc4988c072149