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
CLIManager._bash_comp_command
Build a list of all options for a given command. Args: cmd (str): command name, set to None or '' for bare command. add_help (bool): add an help option. Returns: list of str: list of CLI options strings.
loam/cli.py
def _bash_comp_command(self, cmd, add_help=True): """Build a list of all options for a given command. Args: cmd (str): command name, set to None or '' for bare command. add_help (bool): add an help option. Returns: list of str: list of CLI options strings. """ out = ['-h', '--help'] if add_help else [] cmd_dict = self._opt_cmds[cmd] if cmd else self._opt_bare for opt, sct in cmd_dict: out.extend(_names(self._conf[sct], opt)) return out
def _bash_comp_command(self, cmd, add_help=True): """Build a list of all options for a given command. Args: cmd (str): command name, set to None or '' for bare command. add_help (bool): add an help option. Returns: list of str: list of CLI options strings. """ out = ['-h', '--help'] if add_help else [] cmd_dict = self._opt_cmds[cmd] if cmd else self._opt_bare for opt, sct in cmd_dict: out.extend(_names(self._conf[sct], opt)) return out
[ "Build", "a", "list", "of", "all", "options", "for", "a", "given", "command", "." ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L294-L308
[ "def", "_bash_comp_command", "(", "self", ",", "cmd", ",", "add_help", "=", "True", ")", ":", "out", "=", "[", "'-h'", ",", "'--help'", "]", "if", "add_help", "else", "[", "]", "cmd_dict", "=", "self", ".", "_opt_cmds", "[", "cmd", "]", "if", "cmd", "else", "self", ".", "_opt_bare", "for", "opt", ",", "sct", "in", "cmd_dict", ":", "out", ".", "extend", "(", "_names", "(", "self", ".", "_conf", "[", "sct", "]", ",", "opt", ")", ")", "return", "out" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
CLIManager.bash_complete
Write bash complete script. Args: path (path-like): desired path of the complete script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed.
loam/cli.py
def bash_complete(self, path, cmd, *cmds): """Write bash complete script. Args: path (path-like): desired path of the complete script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. """ path = pathlib.Path(path) subcmds = list(self.subcmds.keys()) with path.open('w') as bcf: # main function print('_{}() {{'.format(cmd), file=bcf) print('COMPREPLY=()', file=bcf) print(r'local cur=${COMP_WORDS[COMP_CWORD]}', end='\n\n', file=bcf) optstr = ' '.join(self._bash_comp_command(None)) print(r'local options="{}"'.format(optstr), end='\n\n', file=bcf) if subcmds: print('local commands="{}"'.format(' '.join(subcmds)), file=bcf) print('declare -A suboptions', file=bcf) for sub in subcmds: optstr = ' '.join(self._bash_comp_command(sub)) print('suboptions[{}]="{}"'.format(sub, optstr), file=bcf) condstr = 'if' for sub in subcmds: print(condstr, r'[[ "${COMP_LINE}" == *"', sub, '"* ]] ; then', file=bcf) print(r'COMPREPLY=( `compgen -W "${suboptions[', sub, r']}" -- ${cur}` )', sep='', file=bcf) condstr = 'elif' print(condstr, r'[[ ${cur} == -* ]] ; then', file=bcf) print(r'COMPREPLY=( `compgen -W "${options}" -- ${cur}`)', file=bcf) if subcmds: print(r'else', file=bcf) print(r'COMPREPLY=( `compgen -W "${commands}" -- ${cur}`)', file=bcf) print('fi', file=bcf) print('}', end='\n\n', file=bcf) print('complete -F _{0} {0}'.format(cmd), *cmds, file=bcf)
def bash_complete(self, path, cmd, *cmds): """Write bash complete script. Args: path (path-like): desired path of the complete script. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. """ path = pathlib.Path(path) subcmds = list(self.subcmds.keys()) with path.open('w') as bcf: # main function print('_{}() {{'.format(cmd), file=bcf) print('COMPREPLY=()', file=bcf) print(r'local cur=${COMP_WORDS[COMP_CWORD]}', end='\n\n', file=bcf) optstr = ' '.join(self._bash_comp_command(None)) print(r'local options="{}"'.format(optstr), end='\n\n', file=bcf) if subcmds: print('local commands="{}"'.format(' '.join(subcmds)), file=bcf) print('declare -A suboptions', file=bcf) for sub in subcmds: optstr = ' '.join(self._bash_comp_command(sub)) print('suboptions[{}]="{}"'.format(sub, optstr), file=bcf) condstr = 'if' for sub in subcmds: print(condstr, r'[[ "${COMP_LINE}" == *"', sub, '"* ]] ; then', file=bcf) print(r'COMPREPLY=( `compgen -W "${suboptions[', sub, r']}" -- ${cur}` )', sep='', file=bcf) condstr = 'elif' print(condstr, r'[[ ${cur} == -* ]] ; then', file=bcf) print(r'COMPREPLY=( `compgen -W "${options}" -- ${cur}`)', file=bcf) if subcmds: print(r'else', file=bcf) print(r'COMPREPLY=( `compgen -W "${commands}" -- ${cur}`)', file=bcf) print('fi', file=bcf) print('}', end='\n\n', file=bcf) print('complete -F _{0} {0}'.format(cmd), *cmds, file=bcf)
[ "Write", "bash", "complete", "script", "." ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/cli.py#L310-L350
[ "def", "bash_complete", "(", "self", ",", "path", ",", "cmd", ",", "*", "cmds", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "path", ")", "subcmds", "=", "list", "(", "self", ".", "subcmds", ".", "keys", "(", ")", ")", "with", "path", ".", "open", "(", "'w'", ")", "as", "bcf", ":", "# main function", "print", "(", "'_{}() {{'", ".", "format", "(", "cmd", ")", ",", "file", "=", "bcf", ")", "print", "(", "'COMPREPLY=()'", ",", "file", "=", "bcf", ")", "print", "(", "r'local cur=${COMP_WORDS[COMP_CWORD]}'", ",", "end", "=", "'\\n\\n'", ",", "file", "=", "bcf", ")", "optstr", "=", "' '", ".", "join", "(", "self", ".", "_bash_comp_command", "(", "None", ")", ")", "print", "(", "r'local options=\"{}\"'", ".", "format", "(", "optstr", ")", ",", "end", "=", "'\\n\\n'", ",", "file", "=", "bcf", ")", "if", "subcmds", ":", "print", "(", "'local commands=\"{}\"'", ".", "format", "(", "' '", ".", "join", "(", "subcmds", ")", ")", ",", "file", "=", "bcf", ")", "print", "(", "'declare -A suboptions'", ",", "file", "=", "bcf", ")", "for", "sub", "in", "subcmds", ":", "optstr", "=", "' '", ".", "join", "(", "self", ".", "_bash_comp_command", "(", "sub", ")", ")", "print", "(", "'suboptions[{}]=\"{}\"'", ".", "format", "(", "sub", ",", "optstr", ")", ",", "file", "=", "bcf", ")", "condstr", "=", "'if'", "for", "sub", "in", "subcmds", ":", "print", "(", "condstr", ",", "r'[[ \"${COMP_LINE}\" == *\"'", ",", "sub", ",", "'\"* ]] ; then'", ",", "file", "=", "bcf", ")", "print", "(", "r'COMPREPLY=( `compgen -W \"${suboptions['", ",", "sub", ",", "r']}\" -- ${cur}` )'", ",", "sep", "=", "''", ",", "file", "=", "bcf", ")", "condstr", "=", "'elif'", "print", "(", "condstr", ",", "r'[[ ${cur} == -* ]] ; then'", ",", "file", "=", "bcf", ")", "print", "(", "r'COMPREPLY=( `compgen -W \"${options}\" -- ${cur}`)'", ",", "file", "=", "bcf", ")", "if", "subcmds", ":", "print", "(", "r'else'", ",", "file", "=", "bcf", ")", "print", "(", "r'COMPREPLY=( `compgen -W \"${commands}\" -- ${cur}`)'", ",", "file", "=", "bcf", ")", "print", "(", "'fi'", ",", "file", "=", "bcf", ")", "print", "(", "'}'", ",", "end", "=", "'\\n\\n'", ",", "file", "=", "bcf", ")", "print", "(", "'complete -F _{0} {0}'", ".", "format", "(", "cmd", ")", ",", "*", "cmds", ",", "file", "=", "bcf", ")" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
zsh_version
Try to guess zsh version, return (0, 0) on failure.
loam/internal.py
def zsh_version(): """Try to guess zsh version, return (0, 0) on failure.""" try: out = subprocess.check_output(shlex.split('zsh --version')) except (FileNotFoundError, subprocess.CalledProcessError): return (0, 0) match = re.search(br'[0-9]+\.[0-9]+', out) return tuple(map(int, match.group(0).split(b'.'))) if match else (0, 0)
def zsh_version(): """Try to guess zsh version, return (0, 0) on failure.""" try: out = subprocess.check_output(shlex.split('zsh --version')) except (FileNotFoundError, subprocess.CalledProcessError): return (0, 0) match = re.search(br'[0-9]+\.[0-9]+', out) return tuple(map(int, match.group(0).split(b'.'))) if match else (0, 0)
[ "Try", "to", "guess", "zsh", "version", "return", "(", "0", "0", ")", "on", "failure", "." ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/internal.py#L25-L32
[ "def", "zsh_version", "(", ")", ":", "try", ":", "out", "=", "subprocess", ".", "check_output", "(", "shlex", ".", "split", "(", "'zsh --version'", ")", ")", "except", "(", "FileNotFoundError", ",", "subprocess", ".", "CalledProcessError", ")", ":", "return", "(", "0", ",", "0", ")", "match", "=", "re", ".", "search", "(", "br'[0-9]+\\.[0-9]+'", ",", "out", ")", "return", "tuple", "(", "map", "(", "int", ",", "match", ".", "group", "(", "0", ")", ".", "split", "(", "b'.'", ")", ")", ")", "if", "match", "else", "(", "0", ",", "0", ")" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
start_master
Starts a new HighFive master at the given host and port, and returns it.
highfive/master.py
async def start_master(host="", port=48484, *, loop=None): """ Starts a new HighFive master at the given host and port, and returns it. """ loop = loop if loop is not None else asyncio.get_event_loop() manager = jobs.JobManager(loop=loop) workers = set() server = await loop.create_server( lambda: WorkerProtocol(manager, workers), host, port) return Master(server, manager, workers, loop=loop)
async def start_master(host="", port=48484, *, loop=None): """ Starts a new HighFive master at the given host and port, and returns it. """ loop = loop if loop is not None else asyncio.get_event_loop() manager = jobs.JobManager(loop=loop) workers = set() server = await loop.create_server( lambda: WorkerProtocol(manager, workers), host, port) return Master(server, manager, workers, loop=loop)
[ "Starts", "a", "new", "HighFive", "master", "at", "the", "given", "host", "and", "port", "and", "returns", "it", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L11-L22
[ "async", "def", "start_master", "(", "host", "=", "\"\"", ",", "port", "=", "48484", ",", "*", ",", "loop", "=", "None", ")", ":", "loop", "=", "loop", "if", "loop", "is", "not", "None", "else", "asyncio", ".", "get_event_loop", "(", ")", "manager", "=", "jobs", ".", "JobManager", "(", "loop", "=", "loop", ")", "workers", "=", "set", "(", ")", "server", "=", "await", "loop", ".", "create_server", "(", "lambda", ":", "WorkerProtocol", "(", "manager", ",", "workers", ")", ",", "host", ",", "port", ")", "return", "Master", "(", "server", ",", "manager", ",", "workers", ",", "loop", "=", "loop", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
WorkerProtocol.connection_made
Called when a remote worker connection has been found. Finishes setting up the protocol object.
highfive/master.py
def connection_made(self, transport): """ Called when a remote worker connection has been found. Finishes setting up the protocol object. """ if self._manager.is_closed(): logger.debug("worker tried to connect while manager was closed") return logger.debug("new worker connected") self._transport = transport self._buffer = bytearray() self._worker = Worker(self._transport, self._manager) self._workers.add(self._worker)
def connection_made(self, transport): """ Called when a remote worker connection has been found. Finishes setting up the protocol object. """ if self._manager.is_closed(): logger.debug("worker tried to connect while manager was closed") return logger.debug("new worker connected") self._transport = transport self._buffer = bytearray() self._worker = Worker(self._transport, self._manager) self._workers.add(self._worker)
[ "Called", "when", "a", "remote", "worker", "connection", "has", "been", "found", ".", "Finishes", "setting", "up", "the", "protocol", "object", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L36-L51
[ "def", "connection_made", "(", "self", ",", "transport", ")", ":", "if", "self", ".", "_manager", ".", "is_closed", "(", ")", ":", "logger", ".", "debug", "(", "\"worker tried to connect while manager was closed\"", ")", "return", "logger", ".", "debug", "(", "\"new worker connected\"", ")", "self", ".", "_transport", "=", "transport", "self", ".", "_buffer", "=", "bytearray", "(", ")", "self", ".", "_worker", "=", "Worker", "(", "self", ".", "_transport", ",", "self", ".", "_manager", ")", "self", ".", "_workers", ".", "add", "(", "self", ".", "_worker", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
WorkerProtocol.data_received
Called when a chunk of data is received from the remote worker. These chunks are stored in a buffer. When a complete line is found in the buffer, it removed and sent to line_received().
highfive/master.py
def data_received(self, data): """ Called when a chunk of data is received from the remote worker. These chunks are stored in a buffer. When a complete line is found in the buffer, it removed and sent to line_received(). """ self._buffer.extend(data) while True: i = self._buffer.find(b"\n") if i == -1: break line = self._buffer[:i+1] self._buffer = self._buffer[i+1:] self.line_received(line)
def data_received(self, data): """ Called when a chunk of data is received from the remote worker. These chunks are stored in a buffer. When a complete line is found in the buffer, it removed and sent to line_received(). """ self._buffer.extend(data) while True: i = self._buffer.find(b"\n") if i == -1: break line = self._buffer[:i+1] self._buffer = self._buffer[i+1:] self.line_received(line)
[ "Called", "when", "a", "chunk", "of", "data", "is", "received", "from", "the", "remote", "worker", ".", "These", "chunks", "are", "stored", "in", "a", "buffer", ".", "When", "a", "complete", "line", "is", "found", "in", "the", "buffer", "it", "removed", "and", "sent", "to", "line_received", "()", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L53-L67
[ "def", "data_received", "(", "self", ",", "data", ")", ":", "self", ".", "_buffer", ".", "extend", "(", "data", ")", "while", "True", ":", "i", "=", "self", ".", "_buffer", ".", "find", "(", "b\"\\n\"", ")", "if", "i", "==", "-", "1", ":", "break", "line", "=", "self", ".", "_buffer", "[", ":", "i", "+", "1", "]", "self", ".", "_buffer", "=", "self", ".", "_buffer", "[", "i", "+", "1", ":", "]", "self", ".", "line_received", "(", "line", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
WorkerProtocol.line_received
Called when a complete line is found from the remote worker. Decodes a response object from the line, then passes it to the worker object.
highfive/master.py
def line_received(self, line): """ Called when a complete line is found from the remote worker. Decodes a response object from the line, then passes it to the worker object. """ response = json.loads(line.decode("utf-8")) self._worker.response_received(response)
def line_received(self, line): """ Called when a complete line is found from the remote worker. Decodes a response object from the line, then passes it to the worker object. """ response = json.loads(line.decode("utf-8")) self._worker.response_received(response)
[ "Called", "when", "a", "complete", "line", "is", "found", "from", "the", "remote", "worker", ".", "Decodes", "a", "response", "object", "from", "the", "line", "then", "passes", "it", "to", "the", "worker", "object", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L69-L76
[ "def", "line_received", "(", "self", ",", "line", ")", ":", "response", "=", "json", ".", "loads", "(", "line", ".", "decode", "(", "\"utf-8\"", ")", ")", "self", ".", "_worker", ".", "response_received", "(", "response", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
WorkerProtocol.connection_lost
Called when the connection to the remote worker is broken. Closes the worker.
highfive/master.py
def connection_lost(self, exc): """ Called when the connection to the remote worker is broken. Closes the worker. """ logger.debug("worker connection lost") self._worker.close() self._workers.remove(self._worker)
def connection_lost(self, exc): """ Called when the connection to the remote worker is broken. Closes the worker. """ logger.debug("worker connection lost") self._worker.close() self._workers.remove(self._worker)
[ "Called", "when", "the", "connection", "to", "the", "remote", "worker", "is", "broken", ".", "Closes", "the", "worker", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L78-L87
[ "def", "connection_lost", "(", "self", ",", "exc", ")", ":", "logger", ".", "debug", "(", "\"worker connection lost\"", ")", "self", ".", "_worker", ".", "close", "(", ")", "self", ".", "_workers", ".", "remove", "(", "self", ".", "_worker", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Worker._job_loaded
Called when a job has been found for the worker to run. Sends the job's RPC to the remote worker.
highfive/master.py
def _job_loaded(self, job): """ Called when a job has been found for the worker to run. Sends the job's RPC to the remote worker. """ logger.debug("worker {} found a job".format(id(self))) if self._closed: self._manager.return_job(job) return self._job = job call_obj = self._job.get_call() call = (json.dumps(call_obj) + "\n").encode("utf-8") self._transport.write(call)
def _job_loaded(self, job): """ Called when a job has been found for the worker to run. Sends the job's RPC to the remote worker. """ logger.debug("worker {} found a job".format(id(self))) if self._closed: self._manager.return_job(job) return self._job = job call_obj = self._job.get_call() call = (json.dumps(call_obj) + "\n").encode("utf-8") self._transport.write(call)
[ "Called", "when", "a", "job", "has", "been", "found", "for", "the", "worker", "to", "run", ".", "Sends", "the", "job", "s", "RPC", "to", "the", "remote", "worker", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L112-L127
[ "def", "_job_loaded", "(", "self", ",", "job", ")", ":", "logger", ".", "debug", "(", "\"worker {} found a job\"", ".", "format", "(", "id", "(", "self", ")", ")", ")", "if", "self", ".", "_closed", ":", "self", ".", "_manager", ".", "return_job", "(", "job", ")", "return", "self", ".", "_job", "=", "job", "call_obj", "=", "self", ".", "_job", ".", "get_call", "(", ")", "call", "=", "(", "json", ".", "dumps", "(", "call_obj", ")", "+", "\"\\n\"", ")", ".", "encode", "(", "\"utf-8\"", ")", "self", ".", "_transport", ".", "write", "(", "call", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Worker.response_received
Called when a response to a job RPC has been received. Decodes the response and finalizes the result, then reports the result to the job manager.
highfive/master.py
def response_received(self, response): """ Called when a response to a job RPC has been received. Decodes the response and finalizes the result, then reports the result to the job manager. """ if self._closed: return assert self._job is not None logger.debug("worker {} got response".format(id(self))) result = self._job.get_result(response) self._manager.add_result(self._job, result) self._load_job()
def response_received(self, response): """ Called when a response to a job RPC has been received. Decodes the response and finalizes the result, then reports the result to the job manager. """ if self._closed: return assert self._job is not None logger.debug("worker {} got response".format(id(self))) result = self._job.get_result(response) self._manager.add_result(self._job, result) self._load_job()
[ "Called", "when", "a", "response", "to", "a", "job", "RPC", "has", "been", "received", ".", "Decodes", "the", "response", "and", "finalizes", "the", "result", "then", "reports", "the", "result", "to", "the", "job", "manager", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L129-L145
[ "def", "response_received", "(", "self", ",", "response", ")", ":", "if", "self", ".", "_closed", ":", "return", "assert", "self", ".", "_job", "is", "not", "None", "logger", ".", "debug", "(", "\"worker {} got response\"", ".", "format", "(", "id", "(", "self", ")", ")", ")", "result", "=", "self", ".", "_job", ".", "get_result", "(", "response", ")", "self", ".", "_manager", ".", "add_result", "(", "self", ".", "_job", ",", "result", ")", "self", ".", "_load_job", "(", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Worker.close
Closes the worker. No more jobs will be handled by the worker, and any running job is immediately returned to the job manager.
highfive/master.py
def close(self): """ Closes the worker. No more jobs will be handled by the worker, and any running job is immediately returned to the job manager. """ if self._closed: return self._closed = True if self._job is not None: self._manager.return_job(self._job) self._job = None
def close(self): """ Closes the worker. No more jobs will be handled by the worker, and any running job is immediately returned to the job manager. """ if self._closed: return self._closed = True if self._job is not None: self._manager.return_job(self._job) self._job = None
[ "Closes", "the", "worker", ".", "No", "more", "jobs", "will", "be", "handled", "by", "the", "worker", "and", "any", "running", "job", "is", "immediately", "returned", "to", "the", "job", "manager", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L147-L160
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "if", "self", ".", "_job", "is", "not", "None", ":", "self", ".", "_manager", ".", "return_job", "(", "self", ".", "_job", ")", "self", ".", "_job", "=", "None" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Master.run
Runs a job set which consists of the jobs in an iterable job list.
highfive/master.py
def run(self, job_list): """ Runs a job set which consists of the jobs in an iterable job list. """ if self._closed: raise RuntimeError("master is closed") return self._manager.add_job_set(job_list)
def run(self, job_list): """ Runs a job set which consists of the jobs in an iterable job list. """ if self._closed: raise RuntimeError("master is closed") return self._manager.add_job_set(job_list)
[ "Runs", "a", "job", "set", "which", "consists", "of", "the", "jobs", "in", "an", "iterable", "job", "list", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L183-L191
[ "def", "run", "(", "self", ",", "job_list", ")", ":", "if", "self", ".", "_closed", ":", "raise", "RuntimeError", "(", "\"master is closed\"", ")", "return", "self", ".", "_manager", ".", "add_job_set", "(", "job_list", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Master.close
Starts closing the HighFive master. The server will be closed and all queued job sets will be cancelled.
highfive/master.py
def close(self): """ Starts closing the HighFive master. The server will be closed and all queued job sets will be cancelled. """ if self._closed: return self._closed = True self._server.close() self._manager.close() for worker in self._workers: worker.close()
def close(self): """ Starts closing the HighFive master. The server will be closed and all queued job sets will be cancelled. """ if self._closed: return self._closed = True self._server.close() self._manager.close() for worker in self._workers: worker.close()
[ "Starts", "closing", "the", "HighFive", "master", ".", "The", "server", "will", "be", "closed", "and", "all", "queued", "job", "sets", "will", "be", "cancelled", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/master.py#L193-L207
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "self", ".", "_server", ".", "close", "(", ")", "self", ".", "_manager", ".", "close", "(", ")", "for", "worker", "in", "self", ".", "_workers", ":", "worker", ".", "close", "(", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Results._change
Called when a state change has occurred. Waiters are notified that a change has occurred.
highfive/jobs.py
def _change(self): """ Called when a state change has occurred. Waiters are notified that a change has occurred. """ for waiter in self._waiters: if not waiter.done(): waiter.set_result(None) self._waiters = []
def _change(self): """ Called when a state change has occurred. Waiters are notified that a change has occurred. """ for waiter in self._waiters: if not waiter.done(): waiter.set_result(None) self._waiters = []
[ "Called", "when", "a", "state", "change", "has", "occurred", ".", "Waiters", "are", "notified", "that", "a", "change", "has", "occurred", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L67-L76
[ "def", "_change", "(", "self", ")", ":", "for", "waiter", "in", "self", ".", "_waiters", ":", "if", "not", "waiter", ".", "done", "(", ")", ":", "waiter", ".", "set_result", "(", "None", ")", "self", ".", "_waiters", "=", "[", "]" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Results.add
Adds a new result.
highfive/jobs.py
def add(self, result): """ Adds a new result. """ assert not self._complete self._results.append(result) self._change()
def add(self, result): """ Adds a new result. """ assert not self._complete self._results.append(result) self._change()
[ "Adds", "a", "new", "result", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L85-L93
[ "def", "add", "(", "self", ",", "result", ")", ":", "assert", "not", "self", ".", "_complete", "self", ".", "_results", ".", "append", "(", "result", ")", "self", ".", "_change", "(", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
Results.wait_changed
Waits until the result set changes. Possible changes can be a result being added or the result set becoming complete. If the result set is already completed, this method returns immediately.
highfive/jobs.py
async def wait_changed(self): """ Waits until the result set changes. Possible changes can be a result being added or the result set becoming complete. If the result set is already completed, this method returns immediately. """ if not self.is_complete(): waiter = self._loop.create_future() self._waiters.append(waiter) await waiter
async def wait_changed(self): """ Waits until the result set changes. Possible changes can be a result being added or the result set becoming complete. If the result set is already completed, this method returns immediately. """ if not self.is_complete(): waiter = self._loop.create_future() self._waiters.append(waiter) await waiter
[ "Waits", "until", "the", "result", "set", "changes", ".", "Possible", "changes", "can", "be", "a", "result", "being", "added", "or", "the", "result", "set", "becoming", "complete", ".", "If", "the", "result", "set", "is", "already", "completed", "this", "method", "returns", "immediately", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L114-L124
[ "async", "def", "wait_changed", "(", "self", ")", ":", "if", "not", "self", ".", "is_complete", "(", ")", ":", "waiter", "=", "self", ".", "_loop", ".", "create_future", "(", ")", "self", ".", "_waiters", ".", "append", "(", "waiter", ")", "await", "waiter" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobSet._load_job
If there is still a job in the job iterator, loads it and increments the active job count.
highfive/jobs.py
def _load_job(self): """ If there is still a job in the job iterator, loads it and increments the active job count. """ try: next_job = next(self._jobs) except StopIteration: self._on_deck = None else: if not isinstance(next_job, Job): next_job = DefaultJob(next_job) self._on_deck = next_job self._active_jobs += 1
def _load_job(self): """ If there is still a job in the job iterator, loads it and increments the active job count. """ try: next_job = next(self._jobs) except StopIteration: self._on_deck = None else: if not isinstance(next_job, Job): next_job = DefaultJob(next_job) self._on_deck = next_job self._active_jobs += 1
[ "If", "there", "is", "still", "a", "job", "in", "the", "job", "iterator", "loads", "it", "and", "increments", "the", "active", "job", "count", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L235-L249
[ "def", "_load_job", "(", "self", ")", ":", "try", ":", "next_job", "=", "next", "(", "self", ".", "_jobs", ")", "except", "StopIteration", ":", "self", ".", "_on_deck", "=", "None", "else", ":", "if", "not", "isinstance", "(", "next_job", ",", "Job", ")", ":", "next_job", "=", "DefaultJob", "(", "next_job", ")", "self", ".", "_on_deck", "=", "next_job", "self", ".", "_active_jobs", "+=", "1" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobSet._done
Marks the job set as completed, and notifies all waiting tasks.
highfive/jobs.py
def _done(self): """ Marks the job set as completed, and notifies all waiting tasks. """ self._results.complete() waiters = self._waiters for waiter in waiters: waiter.set_result(None) self._manager.job_set_done(self)
def _done(self): """ Marks the job set as completed, and notifies all waiting tasks. """ self._results.complete() waiters = self._waiters for waiter in waiters: waiter.set_result(None) self._manager.job_set_done(self)
[ "Marks", "the", "job", "set", "as", "completed", "and", "notifies", "all", "waiting", "tasks", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L251-L260
[ "def", "_done", "(", "self", ")", ":", "self", ".", "_results", ".", "complete", "(", ")", "waiters", "=", "self", ".", "_waiters", "for", "waiter", "in", "waiters", ":", "waiter", ".", "set_result", "(", "None", ")", "self", ".", "_manager", ".", "job_set_done", "(", "self", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobSet.get_job
Gets a job from the job set if one is queued. The jobs_available() method should be consulted first to determine if a job can be obtained from a call to this method. If no jobs are available, an IndexError is raised.
highfive/jobs.py
def get_job(self): """ Gets a job from the job set if one is queued. The jobs_available() method should be consulted first to determine if a job can be obtained from a call to this method. If no jobs are available, an IndexError is raised. """ if len(self._return_queue) > 0: return self._return_queue.popleft() elif self._on_deck is not None: job = self._on_deck self._load_job() return job else: raise IndexError("no jobs available")
def get_job(self): """ Gets a job from the job set if one is queued. The jobs_available() method should be consulted first to determine if a job can be obtained from a call to this method. If no jobs are available, an IndexError is raised. """ if len(self._return_queue) > 0: return self._return_queue.popleft() elif self._on_deck is not None: job = self._on_deck self._load_job() return job else: raise IndexError("no jobs available")
[ "Gets", "a", "job", "from", "the", "job", "set", "if", "one", "is", "queued", ".", "The", "jobs_available", "()", "method", "should", "be", "consulted", "first", "to", "determine", "if", "a", "job", "can", "be", "obtained", "from", "a", "call", "to", "this", "method", ".", "If", "no", "jobs", "are", "available", "an", "IndexError", "is", "raised", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L277-L292
[ "def", "get_job", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_return_queue", ")", ">", "0", ":", "return", "self", ".", "_return_queue", ".", "popleft", "(", ")", "elif", "self", ".", "_on_deck", "is", "not", "None", ":", "job", "=", "self", ".", "_on_deck", "self", ".", "_load_job", "(", ")", "return", "job", "else", ":", "raise", "IndexError", "(", "\"no jobs available\"", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobSet.add_result
Adds the result of a completed job to the result list, then decrements the active job count. If the job set is already complete, the result is simply discarded instead.
highfive/jobs.py
def add_result(self, result): """ Adds the result of a completed job to the result list, then decrements the active job count. If the job set is already complete, the result is simply discarded instead. """ if self._active_jobs == 0: return self._results.add(result) self._active_jobs -= 1 if self._active_jobs == 0: self._done()
def add_result(self, result): """ Adds the result of a completed job to the result list, then decrements the active job count. If the job set is already complete, the result is simply discarded instead. """ if self._active_jobs == 0: return self._results.add(result) self._active_jobs -= 1 if self._active_jobs == 0: self._done()
[ "Adds", "the", "result", "of", "a", "completed", "job", "to", "the", "result", "list", "then", "decrements", "the", "active", "job", "count", ".", "If", "the", "job", "set", "is", "already", "complete", "the", "result", "is", "simply", "discarded", "instead", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L305-L318
[ "def", "add_result", "(", "self", ",", "result", ")", ":", "if", "self", ".", "_active_jobs", "==", "0", ":", "return", "self", ".", "_results", ".", "add", "(", "result", ")", "self", ".", "_active_jobs", "-=", "1", "if", "self", ".", "_active_jobs", "==", "0", ":", "self", ".", "_done", "(", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobSet.cancel
Cancels the job set. The job set is immediately finished, and all queued jobs are discarded.
highfive/jobs.py
def cancel(self): """ Cancels the job set. The job set is immediately finished, and all queued jobs are discarded. """ if self._active_jobs == 0: return self._jobs = iter(()) self._on_deck = None self._return_queue.clear() self._active_jobs = 0 self._done()
def cancel(self): """ Cancels the job set. The job set is immediately finished, and all queued jobs are discarded. """ if self._active_jobs == 0: return self._jobs = iter(()) self._on_deck = None self._return_queue.clear() self._active_jobs = 0 self._done()
[ "Cancels", "the", "job", "set", ".", "The", "job", "set", "is", "immediately", "finished", "and", "all", "queued", "jobs", "are", "discarded", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L320-L334
[ "def", "cancel", "(", "self", ")", ":", "if", "self", ".", "_active_jobs", "==", "0", ":", "return", "self", ".", "_jobs", "=", "iter", "(", "(", ")", ")", "self", ".", "_on_deck", "=", "None", "self", ".", "_return_queue", ".", "clear", "(", ")", "self", ".", "_active_jobs", "=", "0", "self", ".", "_done", "(", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobSet.wait_done
Waits until the job set is finished. Returns immediately if the job set is already finished.
highfive/jobs.py
async def wait_done(self): """ Waits until the job set is finished. Returns immediately if the job set is already finished. """ if self._active_jobs > 0: future = self._loop.create_future() self._waiters.append(future) await future
async def wait_done(self): """ Waits until the job set is finished. Returns immediately if the job set is already finished. """ if self._active_jobs > 0: future = self._loop.create_future() self._waiters.append(future) await future
[ "Waits", "until", "the", "job", "set", "is", "finished", ".", "Returns", "immediately", "if", "the", "job", "set", "is", "already", "finished", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L336-L345
[ "async", "def", "wait_done", "(", "self", ")", ":", "if", "self", ".", "_active_jobs", ">", "0", ":", "future", "=", "self", ".", "_loop", ".", "create_future", "(", ")", "self", ".", "_waiters", ".", "append", "(", "future", ")", "await", "future" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobManager._distribute_jobs
Distributes jobs from the active job set to any waiting get_job callbacks.
highfive/jobs.py
def _distribute_jobs(self): """ Distributes jobs from the active job set to any waiting get_job callbacks. """ while (self._active_js.job_available() and len(self._ready_callbacks) > 0): job = self._active_js.get_job() self._job_sources[job] = self._active_js callback = self._ready_callbacks.popleft() callback(job)
def _distribute_jobs(self): """ Distributes jobs from the active job set to any waiting get_job callbacks. """ while (self._active_js.job_available() and len(self._ready_callbacks) > 0): job = self._active_js.get_job() self._job_sources[job] = self._active_js callback = self._ready_callbacks.popleft() callback(job)
[ "Distributes", "jobs", "from", "the", "active", "job", "set", "to", "any", "waiting", "get_job", "callbacks", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L359-L370
[ "def", "_distribute_jobs", "(", "self", ")", ":", "while", "(", "self", ".", "_active_js", ".", "job_available", "(", ")", "and", "len", "(", "self", ".", "_ready_callbacks", ")", ">", "0", ")", ":", "job", "=", "self", ".", "_active_js", ".", "get_job", "(", ")", "self", ".", "_job_sources", "[", "job", "]", "=", "self", ".", "_active_js", "callback", "=", "self", ".", "_ready_callbacks", ".", "popleft", "(", ")", "callback", "(", "job", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobManager.add_job_set
Adds a job set to the manager's queue. If there is no job set running, it is activated immediately. A new job set handle is returned.
highfive/jobs.py
def add_job_set(self, job_list): """ Adds a job set to the manager's queue. If there is no job set running, it is activated immediately. A new job set handle is returned. """ assert not self._closed results = Results(loop=self._loop) js = JobSet(job_list, results, self, loop=self._loop) if not js.is_done(): if self._active_js is None: self._active_js = js logger.debug("activated job set") self._distribute_jobs() else: self._js_queue.append(js) else: logger.debug("new job set has no jobs") return JobSetHandle(js, results)
def add_job_set(self, job_list): """ Adds a job set to the manager's queue. If there is no job set running, it is activated immediately. A new job set handle is returned. """ assert not self._closed results = Results(loop=self._loop) js = JobSet(job_list, results, self, loop=self._loop) if not js.is_done(): if self._active_js is None: self._active_js = js logger.debug("activated job set") self._distribute_jobs() else: self._js_queue.append(js) else: logger.debug("new job set has no jobs") return JobSetHandle(js, results)
[ "Adds", "a", "job", "set", "to", "the", "manager", "s", "queue", ".", "If", "there", "is", "no", "job", "set", "running", "it", "is", "activated", "immediately", ".", "A", "new", "job", "set", "handle", "is", "returned", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L372-L391
[ "def", "add_job_set", "(", "self", ",", "job_list", ")", ":", "assert", "not", "self", ".", "_closed", "results", "=", "Results", "(", "loop", "=", "self", ".", "_loop", ")", "js", "=", "JobSet", "(", "job_list", ",", "results", ",", "self", ",", "loop", "=", "self", ".", "_loop", ")", "if", "not", "js", ".", "is_done", "(", ")", ":", "if", "self", ".", "_active_js", "is", "None", ":", "self", ".", "_active_js", "=", "js", "logger", ".", "debug", "(", "\"activated job set\"", ")", "self", ".", "_distribute_jobs", "(", ")", "else", ":", "self", ".", "_js_queue", ".", "append", "(", "js", ")", "else", ":", "logger", ".", "debug", "(", "\"new job set has no jobs\"", ")", "return", "JobSetHandle", "(", "js", ",", "results", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobManager.get_job
Calls the given callback function when a job becomes available.
highfive/jobs.py
def get_job(self, callback): """ Calls the given callback function when a job becomes available. """ assert not self._closed if self._active_js is None or not self._active_js.job_available(): self._ready_callbacks.append(callback) else: job = self._active_js.get_job() self._job_sources[job] = self._active_js callback(job)
def get_job(self, callback): """ Calls the given callback function when a job becomes available. """ assert not self._closed if self._active_js is None or not self._active_js.job_available(): self._ready_callbacks.append(callback) else: job = self._active_js.get_job() self._job_sources[job] = self._active_js callback(job)
[ "Calls", "the", "given", "callback", "function", "when", "a", "job", "becomes", "available", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L393-L405
[ "def", "get_job", "(", "self", ",", "callback", ")", ":", "assert", "not", "self", ".", "_closed", "if", "self", ".", "_active_js", "is", "None", "or", "not", "self", ".", "_active_js", ".", "job_available", "(", ")", ":", "self", ".", "_ready_callbacks", ".", "append", "(", "callback", ")", "else", ":", "job", "=", "self", ".", "_active_js", ".", "get_job", "(", ")", "self", ".", "_job_sources", "[", "job", "]", "=", "self", ".", "_active_js", "callback", "(", "job", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobManager.return_job
Returns a job to its source job set to be run again later.
highfive/jobs.py
def return_job(self, job): """ Returns a job to its source job set to be run again later. """ if self._closed: return js = self._job_sources[job] if len(self._ready_callbacks) > 0: callback = self._ready_callbacks.popleft() callback(job) else: del self._job_sources[job] js.return_job(job)
def return_job(self, job): """ Returns a job to its source job set to be run again later. """ if self._closed: return js = self._job_sources[job] if len(self._ready_callbacks) > 0: callback = self._ready_callbacks.popleft() callback(job) else: del self._job_sources[job] js.return_job(job)
[ "Returns", "a", "job", "to", "its", "source", "job", "set", "to", "be", "run", "again", "later", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L407-L421
[ "def", "return_job", "(", "self", ",", "job", ")", ":", "if", "self", ".", "_closed", ":", "return", "js", "=", "self", ".", "_job_sources", "[", "job", "]", "if", "len", "(", "self", ".", "_ready_callbacks", ")", ">", "0", ":", "callback", "=", "self", ".", "_ready_callbacks", ".", "popleft", "(", ")", "callback", "(", "job", ")", "else", ":", "del", "self", ".", "_job_sources", "[", "job", "]", "js", ".", "return_job", "(", "job", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobManager.add_result
Adds the result of a job to the results list of the job's source job set.
highfive/jobs.py
def add_result(self, job, result): """ Adds the result of a job to the results list of the job's source job set. """ if self._closed: return js = self._job_sources[job] del self._job_sources[job] js.add_result(result)
def add_result(self, job, result): """ Adds the result of a job to the results list of the job's source job set. """ if self._closed: return js = self._job_sources[job] del self._job_sources[job] js.add_result(result)
[ "Adds", "the", "result", "of", "a", "job", "to", "the", "results", "list", "of", "the", "job", "s", "source", "job", "set", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L423-L434
[ "def", "add_result", "(", "self", ",", "job", ",", "result", ")", ":", "if", "self", ".", "_closed", ":", "return", "js", "=", "self", ".", "_job_sources", "[", "job", "]", "del", "self", ".", "_job_sources", "[", "job", "]", "js", ".", "add_result", "(", "result", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobManager.job_set_done
Called when a job set has been completed or cancelled. If the job set was active, the next incomplete job set is loaded from the job set queue and is activated.
highfive/jobs.py
def job_set_done(self, js): """ Called when a job set has been completed or cancelled. If the job set was active, the next incomplete job set is loaded from the job set queue and is activated. """ if self._closed: return if self._active_js != js: return try: while self._active_js.is_done(): logger.debug("job set done") self._active_js = self._js_queue.popleft() logger.debug("activated job set") except IndexError: self._active_js = None else: self._distribute_jobs()
def job_set_done(self, js): """ Called when a job set has been completed or cancelled. If the job set was active, the next incomplete job set is loaded from the job set queue and is activated. """ if self._closed: return if self._active_js != js: return try: while self._active_js.is_done(): logger.debug("job set done") self._active_js = self._js_queue.popleft() logger.debug("activated job set") except IndexError: self._active_js = None else: self._distribute_jobs()
[ "Called", "when", "a", "job", "set", "has", "been", "completed", "or", "cancelled", ".", "If", "the", "job", "set", "was", "active", "the", "next", "incomplete", "job", "set", "is", "loaded", "from", "the", "job", "set", "queue", "and", "is", "activated", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L436-L457
[ "def", "job_set_done", "(", "self", ",", "js", ")", ":", "if", "self", ".", "_closed", ":", "return", "if", "self", ".", "_active_js", "!=", "js", ":", "return", "try", ":", "while", "self", ".", "_active_js", ".", "is_done", "(", ")", ":", "logger", ".", "debug", "(", "\"job set done\"", ")", "self", ".", "_active_js", "=", "self", ".", "_js_queue", ".", "popleft", "(", ")", "logger", ".", "debug", "(", "\"activated job set\"", ")", "except", "IndexError", ":", "self", ".", "_active_js", "=", "None", "else", ":", "self", ".", "_distribute_jobs", "(", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
JobManager.close
Closes the job manager. No more jobs will be assigned, no more job sets will be added, and any queued or active job sets will be cancelled.
highfive/jobs.py
def close(self): """ Closes the job manager. No more jobs will be assigned, no more job sets will be added, and any queued or active job sets will be cancelled. """ if self._closed: return self._closed = True if self._active_js is not None: self._active_js.cancel() for js in self._js_queue: js.cancel()
def close(self): """ Closes the job manager. No more jobs will be assigned, no more job sets will be added, and any queued or active job sets will be cancelled. """ if self._closed: return self._closed = True if self._active_js is not None: self._active_js.cancel() for js in self._js_queue: js.cancel()
[ "Closes", "the", "job", "manager", ".", "No", "more", "jobs", "will", "be", "assigned", "no", "more", "job", "sets", "will", "be", "added", "and", "any", "queued", "or", "active", "job", "sets", "will", "be", "cancelled", "." ]
abau171/highfive
python
https://github.com/abau171/highfive/blob/07b3829331072035ab100d1d66deca3e8f3f372a/highfive/jobs.py#L466-L479
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_closed", ":", "return", "self", ".", "_closed", "=", "True", "if", "self", ".", "_active_js", "is", "not", "None", ":", "self", ".", "_active_js", ".", "cancel", "(", ")", "for", "js", "in", "self", ".", "_js_queue", ":", "js", ".", "cancel", "(", ")" ]
07b3829331072035ab100d1d66deca3e8f3f372a
test
entry_point
External entry point which calls main() and if Stop is raised, calls sys.exit()
yaclifw/main.py
def entry_point(items=tuple()): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: if not items: from .example import ExampleCommand from .version import Version items = [(ExampleCommand.NAME, ExampleCommand), (Version.NAME, Version)] main("yaclifw", items=items) except Stop as stop: print(stop) sys.exit(stop.rc) except SystemExit: raise except KeyboardInterrupt: print("Cancelled") sys.exit(1) except Exception: traceback.print_exc() sys.exit(1)
def entry_point(items=tuple()): """ External entry point which calls main() and if Stop is raised, calls sys.exit() """ try: if not items: from .example import ExampleCommand from .version import Version items = [(ExampleCommand.NAME, ExampleCommand), (Version.NAME, Version)] main("yaclifw", items=items) except Stop as stop: print(stop) sys.exit(stop.rc) except SystemExit: raise except KeyboardInterrupt: print("Cancelled") sys.exit(1) except Exception: traceback.print_exc() sys.exit(1)
[ "External", "entry", "point", "which", "calls", "main", "()", "and", "if", "Stop", "is", "raised", "calls", "sys", ".", "exit", "()" ]
openmicroscopy/yaclifw
python
https://github.com/openmicroscopy/yaclifw/blob/a01179fefb2c2c4260c75e6d1dc6e19de9979d64/yaclifw/main.py#L37-L59
[ "def", "entry_point", "(", "items", "=", "tuple", "(", ")", ")", ":", "try", ":", "if", "not", "items", ":", "from", ".", "example", "import", "ExampleCommand", "from", ".", "version", "import", "Version", "items", "=", "[", "(", "ExampleCommand", ".", "NAME", ",", "ExampleCommand", ")", ",", "(", "Version", ".", "NAME", ",", "Version", ")", "]", "main", "(", "\"yaclifw\"", ",", "items", "=", "items", ")", "except", "Stop", "as", "stop", ":", "print", "(", "stop", ")", "sys", ".", "exit", "(", "stop", ".", "rc", ")", "except", "SystemExit", ":", "raise", "except", "KeyboardInterrupt", ":", "print", "(", "\"Cancelled\"", ")", "sys", ".", "exit", "(", "1", ")", "except", "Exception", ":", "traceback", ".", "print_exc", "(", ")", "sys", ".", "exit", "(", "1", ")" ]
a01179fefb2c2c4260c75e6d1dc6e19de9979d64
test
_uniquify
Remove duplicates in a list.
src/lsi/utils/hosts.py
def _uniquify(_list): """Remove duplicates in a list.""" seen = set() result = [] for x in _list: if x not in seen: result.append(x) seen.add(x) return result
def _uniquify(_list): """Remove duplicates in a list.""" seen = set() result = [] for x in _list: if x not in seen: result.append(x) seen.add(x) return result
[ "Remove", "duplicates", "in", "a", "list", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L397-L405
[ "def", "_uniquify", "(", "_list", ")", ":", "seen", "=", "set", "(", ")", "result", "=", "[", "]", "for", "x", "in", "_list", ":", "if", "x", "not", "in", "seen", ":", "result", ".", "append", "(", "x", ")", "seen", ".", "add", "(", "x", ")", "return", "result" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_match_regex
Returns true if the regex matches the object, or a string in the object if it is some sort of container. :param regex: A regex. :type regex: ``regex`` :param obj: An arbitrary object. :type object: ``object`` :rtype: ``bool``
src/lsi/utils/hosts.py
def _match_regex(regex, obj): """ Returns true if the regex matches the object, or a string in the object if it is some sort of container. :param regex: A regex. :type regex: ``regex`` :param obj: An arbitrary object. :type object: ``object`` :rtype: ``bool`` """ if isinstance(obj, six.string_types): return len(regex.findall(obj)) > 0 elif isinstance(obj, dict): return _match_regex(regex, obj.values()) elif hasattr(obj, '__iter__'): # Object is a list or some other iterable. return any(_match_regex(regex, s) for s in obj if isinstance(s, six.string_types)) else: return False
def _match_regex(regex, obj): """ Returns true if the regex matches the object, or a string in the object if it is some sort of container. :param regex: A regex. :type regex: ``regex`` :param obj: An arbitrary object. :type object: ``object`` :rtype: ``bool`` """ if isinstance(obj, six.string_types): return len(regex.findall(obj)) > 0 elif isinstance(obj, dict): return _match_regex(regex, obj.values()) elif hasattr(obj, '__iter__'): # Object is a list or some other iterable. return any(_match_regex(regex, s) for s in obj if isinstance(s, six.string_types)) else: return False
[ "Returns", "true", "if", "the", "regex", "matches", "the", "object", "or", "a", "string", "in", "the", "object", "if", "it", "is", "some", "sort", "of", "container", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L408-L429
[ "def", "_match_regex", "(", "regex", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "six", ".", "string_types", ")", ":", "return", "len", "(", "regex", ".", "findall", "(", "obj", ")", ")", ">", "0", "elif", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "_match_regex", "(", "regex", ",", "obj", ".", "values", "(", ")", ")", "elif", "hasattr", "(", "obj", ",", "'__iter__'", ")", ":", "# Object is a list or some other iterable.", "return", "any", "(", "_match_regex", "(", "regex", ",", "s", ")", "for", "s", "in", "obj", "if", "isinstance", "(", "s", ",", "six", ".", "string_types", ")", ")", "else", ":", "return", "False" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
get_entries
Lists all available instances. :param latest: If true, ignores the cache and grabs the latest list. :type latest: ``bool`` :param filters: Filters to apply to results. A result will only be shown if it includes all text in all filters. :type filters: [``str``] :param exclude: The opposite of filters. Results will be rejected if they include any of these strings. :type exclude: [``str``] :param limit: Maximum number of entries to show (default no maximum). :type limit: ``int`` or ``NoneType`` :return: A list of host entries. :rtype: ``list`` of :py:class:`HostEntry`
src/lsi/utils/hosts.py
def get_entries(latest, filters, exclude, limit=None): """ Lists all available instances. :param latest: If true, ignores the cache and grabs the latest list. :type latest: ``bool`` :param filters: Filters to apply to results. A result will only be shown if it includes all text in all filters. :type filters: [``str``] :param exclude: The opposite of filters. Results will be rejected if they include any of these strings. :type exclude: [``str``] :param limit: Maximum number of entries to show (default no maximum). :type limit: ``int`` or ``NoneType`` :return: A list of host entries. :rtype: ``list`` of :py:class:`HostEntry` """ entry_list = _list_all_latest() if latest is True or not _is_valid_cache()\ else _list_all_cached() filtered = filter_entries(entry_list, filters, exclude) if limit is not None: return filtered[:limit] else: return filtered
def get_entries(latest, filters, exclude, limit=None): """ Lists all available instances. :param latest: If true, ignores the cache and grabs the latest list. :type latest: ``bool`` :param filters: Filters to apply to results. A result will only be shown if it includes all text in all filters. :type filters: [``str``] :param exclude: The opposite of filters. Results will be rejected if they include any of these strings. :type exclude: [``str``] :param limit: Maximum number of entries to show (default no maximum). :type limit: ``int`` or ``NoneType`` :return: A list of host entries. :rtype: ``list`` of :py:class:`HostEntry` """ entry_list = _list_all_latest() if latest is True or not _is_valid_cache()\ else _list_all_cached() filtered = filter_entries(entry_list, filters, exclude) if limit is not None: return filtered[:limit] else: return filtered
[ "Lists", "all", "available", "instances", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L432-L456
[ "def", "get_entries", "(", "latest", ",", "filters", ",", "exclude", ",", "limit", "=", "None", ")", ":", "entry_list", "=", "_list_all_latest", "(", ")", "if", "latest", "is", "True", "or", "not", "_is_valid_cache", "(", ")", "else", "_list_all_cached", "(", ")", "filtered", "=", "filter_entries", "(", "entry_list", ",", "filters", ",", "exclude", ")", "if", "limit", "is", "not", "None", ":", "return", "filtered", "[", ":", "limit", "]", "else", ":", "return", "filtered" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
get_region
Use the environment to get the current region
src/lsi/utils/hosts.py
def get_region(): """Use the environment to get the current region""" global _REGION if _REGION is None: region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1" region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")} if region_name not in region_dict: raise ValueError("No such EC2 region: {}. Check AWS_DEFAULT_REGION " "environment variable".format(region_name)) _REGION = region_dict[region_name] return _REGION
def get_region(): """Use the environment to get the current region""" global _REGION if _REGION is None: region_name = os.getenv("AWS_DEFAULT_REGION") or "us-east-1" region_dict = {r.name: r for r in boto.regioninfo.get_regions("ec2")} if region_name not in region_dict: raise ValueError("No such EC2 region: {}. Check AWS_DEFAULT_REGION " "environment variable".format(region_name)) _REGION = region_dict[region_name] return _REGION
[ "Use", "the", "environment", "to", "get", "the", "current", "region" ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L462-L472
[ "def", "get_region", "(", ")", ":", "global", "_REGION", "if", "_REGION", "is", "None", ":", "region_name", "=", "os", ".", "getenv", "(", "\"AWS_DEFAULT_REGION\"", ")", "or", "\"us-east-1\"", "region_dict", "=", "{", "r", ".", "name", ":", "r", "for", "r", "in", "boto", ".", "regioninfo", ".", "get_regions", "(", "\"ec2\"", ")", "}", "if", "region_name", "not", "in", "region_dict", ":", "raise", "ValueError", "(", "\"No such EC2 region: {}. Check AWS_DEFAULT_REGION \"", "\"environment variable\"", ".", "format", "(", "region_name", ")", ")", "_REGION", "=", "region_dict", "[", "region_name", "]", "return", "_REGION" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_is_valid_cache
Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool``
src/lsi/utils/hosts.py
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False modified = os.path.getmtime(get_cache_location()) modified = time.ctime(modified) modified = datetime.strptime(modified, '%a %b %d %H:%M:%S %Y') return datetime.now() - modified <= CACHE_EXPIRATION_INTERVAL
def _is_valid_cache(): """ Returns if the cache is valid (exists and modified within the interval). :return: Whether the cache is valid. :rtype: ``bool`` """ if not os.path.exists(get_cache_location()): return False modified = os.path.getmtime(get_cache_location()) modified = time.ctime(modified) modified = datetime.strptime(modified, '%a %b %d %H:%M:%S %Y') return datetime.now() - modified <= CACHE_EXPIRATION_INTERVAL
[ "Returns", "if", "the", "cache", "is", "valid", "(", "exists", "and", "modified", "within", "the", "interval", ")", ".", ":", "return", ":", "Whether", "the", "cache", "is", "valid", ".", ":", "rtype", ":", "bool" ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L481-L492
[ "def", "_is_valid_cache", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "get_cache_location", "(", ")", ")", ":", "return", "False", "modified", "=", "os", ".", "path", ".", "getmtime", "(", "get_cache_location", "(", ")", ")", "modified", "=", "time", ".", "ctime", "(", "modified", ")", "modified", "=", "datetime", ".", "strptime", "(", "modified", ",", "'%a %b %d %H:%M:%S %Y'", ")", "return", "datetime", ".", "now", "(", ")", "-", "modified", "<=", "CACHE_EXPIRATION_INTERVAL" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_list_all_cached
Reads the description cache, returning each instance's information. :return: A list of host entries. :rtype: [:py:class:`HostEntry`]
src/lsi/utils/hosts.py
def _list_all_cached(): """ Reads the description cache, returning each instance's information. :return: A list of host entries. :rtype: [:py:class:`HostEntry`] """ with open(get_cache_location()) as f: contents = f.read() objects = json.loads(contents) return [HostEntry.from_dict(obj) for obj in objects]
def _list_all_cached(): """ Reads the description cache, returning each instance's information. :return: A list of host entries. :rtype: [:py:class:`HostEntry`] """ with open(get_cache_location()) as f: contents = f.read() objects = json.loads(contents) return [HostEntry.from_dict(obj) for obj in objects]
[ "Reads", "the", "description", "cache", "returning", "each", "instance", "s", "information", ".", ":", "return", ":", "A", "list", "of", "host", "entries", ".", ":", "rtype", ":", "[", ":", "py", ":", "class", ":", "HostEntry", "]" ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L515-L524
[ "def", "_list_all_cached", "(", ")", ":", "with", "open", "(", "get_cache_location", "(", ")", ")", "as", "f", ":", "contents", "=", "f", ".", "read", "(", ")", "objects", "=", "json", ".", "loads", "(", "contents", ")", "return", "[", "HostEntry", ".", "from_dict", "(", "obj", ")", "for", "obj", "in", "objects", "]" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
filter_entries
Filters a list of host entries according to the given filters. :param entries: A list of host entries. :type entries: [:py:class:`HostEntry`] :param filters: Regexes that must match a `HostEntry`. :type filters: [``str``] :param exclude: Regexes that must NOT match a `HostEntry`. :type exclude: [``str``] :return: The filtered list of host entries. :rtype: [:py:class:`HostEntry`]
src/lsi/utils/hosts.py
def filter_entries(entries, filters, exclude): """ Filters a list of host entries according to the given filters. :param entries: A list of host entries. :type entries: [:py:class:`HostEntry`] :param filters: Regexes that must match a `HostEntry`. :type filters: [``str``] :param exclude: Regexes that must NOT match a `HostEntry`. :type exclude: [``str``] :return: The filtered list of host entries. :rtype: [:py:class:`HostEntry`] """ filtered = [entry for entry in entries if all(entry.matches(f) for f in filters) and not any(entry.matches(e) for e in exclude)] return filtered
def filter_entries(entries, filters, exclude): """ Filters a list of host entries according to the given filters. :param entries: A list of host entries. :type entries: [:py:class:`HostEntry`] :param filters: Regexes that must match a `HostEntry`. :type filters: [``str``] :param exclude: Regexes that must NOT match a `HostEntry`. :type exclude: [``str``] :return: The filtered list of host entries. :rtype: [:py:class:`HostEntry`] """ filtered = [entry for entry in entries if all(entry.matches(f) for f in filters) and not any(entry.matches(e) for e in exclude)] return filtered
[ "Filters", "a", "list", "of", "host", "entries", "according", "to", "the", "given", "filters", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L527-L545
[ "def", "filter_entries", "(", "entries", ",", "filters", ",", "exclude", ")", ":", "filtered", "=", "[", "entry", "for", "entry", "in", "entries", "if", "all", "(", "entry", ".", "matches", "(", "f", ")", "for", "f", "in", "filters", ")", "and", "not", "any", "(", "entry", ".", "matches", "(", "e", ")", "for", "e", "in", "exclude", ")", "]", "return", "filtered" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
get_host
Prints the public dns name of `name`, if it exists. :param name: The instance name. :type name: ``str``
src/lsi/utils/hosts.py
def get_host(name): """ Prints the public dns name of `name`, if it exists. :param name: The instance name. :type name: ``str`` """ f = {'instance-state-name': 'running', 'tag:Name': name} ec2 = boto.connect_ec2(region=get_region()) rs = ec2.get_all_instances(filters=f) if len(rs) == 0: raise Exception('Host "%s" not found' % name) print(rs[0].instances[0].public_dns_name)
def get_host(name): """ Prints the public dns name of `name`, if it exists. :param name: The instance name. :type name: ``str`` """ f = {'instance-state-name': 'running', 'tag:Name': name} ec2 = boto.connect_ec2(region=get_region()) rs = ec2.get_all_instances(filters=f) if len(rs) == 0: raise Exception('Host "%s" not found' % name) print(rs[0].instances[0].public_dns_name)
[ "Prints", "the", "public", "dns", "name", "of", "name", "if", "it", "exists", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L548-L560
[ "def", "get_host", "(", "name", ")", ":", "f", "=", "{", "'instance-state-name'", ":", "'running'", ",", "'tag:Name'", ":", "name", "}", "ec2", "=", "boto", ".", "connect_ec2", "(", "region", "=", "get_region", "(", ")", ")", "rs", "=", "ec2", ".", "get_all_instances", "(", "filters", "=", "f", ")", "if", "len", "(", "rs", ")", "==", "0", ":", "raise", "Exception", "(", "'Host \"%s\" not found'", "%", "name", ")", "print", "(", "rs", "[", "0", "]", ".", "instances", "[", "0", "]", ".", "public_dns_name", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.from_dict
Deserialize a HostEntry from a dictionary. This is more or less the same as calling HostEntry(**entry_dict), but is clearer if something is missing. :param entry_dict: A dictionary in the format outputted by to_dict(). :type entry_dict: ``dict`` :return: A HostEntry object. :rtype: ``cls``
src/lsi/utils/hosts.py
def from_dict(cls, entry_dict): """Deserialize a HostEntry from a dictionary. This is more or less the same as calling HostEntry(**entry_dict), but is clearer if something is missing. :param entry_dict: A dictionary in the format outputted by to_dict(). :type entry_dict: ``dict`` :return: A HostEntry object. :rtype: ``cls`` """ return cls( name=entry_dict["name"], instance_type=entry_dict["instance_type"], hostname=entry_dict["hostname"], private_ip=entry_dict["private_ip"], public_ip=entry_dict["public_ip"], stack_name=entry_dict["stack_name"], stack_id=entry_dict["stack_id"], logical_id=entry_dict["logical_id"], security_groups=entry_dict["security_groups"], tags=entry_dict["tags"], ami_id=entry_dict["ami_id"], launch_time=entry_dict["launch_time"], instance_id=entry_dict["instance_id"] )
def from_dict(cls, entry_dict): """Deserialize a HostEntry from a dictionary. This is more or less the same as calling HostEntry(**entry_dict), but is clearer if something is missing. :param entry_dict: A dictionary in the format outputted by to_dict(). :type entry_dict: ``dict`` :return: A HostEntry object. :rtype: ``cls`` """ return cls( name=entry_dict["name"], instance_type=entry_dict["instance_type"], hostname=entry_dict["hostname"], private_ip=entry_dict["private_ip"], public_ip=entry_dict["public_ip"], stack_name=entry_dict["stack_name"], stack_id=entry_dict["stack_id"], logical_id=entry_dict["logical_id"], security_groups=entry_dict["security_groups"], tags=entry_dict["tags"], ami_id=entry_dict["ami_id"], launch_time=entry_dict["launch_time"], instance_id=entry_dict["instance_id"] )
[ "Deserialize", "a", "HostEntry", "from", "a", "dictionary", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L117-L144
[ "def", "from_dict", "(", "cls", ",", "entry_dict", ")", ":", "return", "cls", "(", "name", "=", "entry_dict", "[", "\"name\"", "]", ",", "instance_type", "=", "entry_dict", "[", "\"instance_type\"", "]", ",", "hostname", "=", "entry_dict", "[", "\"hostname\"", "]", ",", "private_ip", "=", "entry_dict", "[", "\"private_ip\"", "]", ",", "public_ip", "=", "entry_dict", "[", "\"public_ip\"", "]", ",", "stack_name", "=", "entry_dict", "[", "\"stack_name\"", "]", ",", "stack_id", "=", "entry_dict", "[", "\"stack_id\"", "]", ",", "logical_id", "=", "entry_dict", "[", "\"logical_id\"", "]", ",", "security_groups", "=", "entry_dict", "[", "\"security_groups\"", "]", ",", "tags", "=", "entry_dict", "[", "\"tags\"", "]", ",", "ami_id", "=", "entry_dict", "[", "\"ami_id\"", "]", ",", "launch_time", "=", "entry_dict", "[", "\"launch_time\"", "]", ",", "instance_id", "=", "entry_dict", "[", "\"instance_id\"", "]", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry._get_attrib
Given an attribute name, looks it up on the entry. Names that start with ``tags.`` are looked up in the ``tags`` dictionary. :param attr: Name of attribute to look up. :type attr: ``str`` :param convert_to_str: Convert result to a string. :type convert_to_str: ``bool`` :rtype: ``object``
src/lsi/utils/hosts.py
def _get_attrib(self, attr, convert_to_str=False): """ Given an attribute name, looks it up on the entry. Names that start with ``tags.`` are looked up in the ``tags`` dictionary. :param attr: Name of attribute to look up. :type attr: ``str`` :param convert_to_str: Convert result to a string. :type convert_to_str: ``bool`` :rtype: ``object`` """ if attr.startswith('tags.'): tag = attr[len('tags.'):] if tag in self.tags and self.tags[tag] != '': return self.tags[tag] elif convert_to_str is True: return '<not set>' else: return self.tags.get(tag) elif not hasattr(self, attr): raise AttributeError('Invalid attribute: {0}. Perhaps you meant ' '{1}?'.format(red(attr), green('tags.' + attr))) else: result = getattr(self, attr) if convert_to_str is True and not result: return '<none>' elif convert_to_str is True and isinstance(result, list): return ', '.join(result) elif convert_to_str is True: return str(result) else: return result
def _get_attrib(self, attr, convert_to_str=False): """ Given an attribute name, looks it up on the entry. Names that start with ``tags.`` are looked up in the ``tags`` dictionary. :param attr: Name of attribute to look up. :type attr: ``str`` :param convert_to_str: Convert result to a string. :type convert_to_str: ``bool`` :rtype: ``object`` """ if attr.startswith('tags.'): tag = attr[len('tags.'):] if tag in self.tags and self.tags[tag] != '': return self.tags[tag] elif convert_to_str is True: return '<not set>' else: return self.tags.get(tag) elif not hasattr(self, attr): raise AttributeError('Invalid attribute: {0}. Perhaps you meant ' '{1}?'.format(red(attr), green('tags.' + attr))) else: result = getattr(self, attr) if convert_to_str is True and not result: return '<none>' elif convert_to_str is True and isinstance(result, list): return ', '.join(result) elif convert_to_str is True: return str(result) else: return result
[ "Given", "an", "attribute", "name", "looks", "it", "up", "on", "the", "entry", ".", "Names", "that", "start", "with", "tags", ".", "are", "looked", "up", "in", "the", "tags", "dictionary", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L146-L179
[ "def", "_get_attrib", "(", "self", ",", "attr", ",", "convert_to_str", "=", "False", ")", ":", "if", "attr", ".", "startswith", "(", "'tags.'", ")", ":", "tag", "=", "attr", "[", "len", "(", "'tags.'", ")", ":", "]", "if", "tag", "in", "self", ".", "tags", "and", "self", ".", "tags", "[", "tag", "]", "!=", "''", ":", "return", "self", ".", "tags", "[", "tag", "]", "elif", "convert_to_str", "is", "True", ":", "return", "'<not set>'", "else", ":", "return", "self", ".", "tags", ".", "get", "(", "tag", ")", "elif", "not", "hasattr", "(", "self", ",", "attr", ")", ":", "raise", "AttributeError", "(", "'Invalid attribute: {0}. Perhaps you meant '", "'{1}?'", ".", "format", "(", "red", "(", "attr", ")", ",", "green", "(", "'tags.'", "+", "attr", ")", ")", ")", "else", ":", "result", "=", "getattr", "(", "self", ",", "attr", ")", "if", "convert_to_str", "is", "True", "and", "not", "result", ":", "return", "'<none>'", "elif", "convert_to_str", "is", "True", "and", "isinstance", "(", "result", ",", "list", ")", ":", "return", "', '", ".", "join", "(", "result", ")", "elif", "convert_to_str", "is", "True", ":", "return", "str", "(", "result", ")", "else", ":", "return", "result" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.list_attributes
Lists all of the attributes to be found on an instance of this class. It creates a "fake instance" by passing in `None` to all of the ``__init__`` arguments, then returns all of the attributes of that instance. :return: A list of instance attributes of this class. :rtype: ``list`` of ``str``
src/lsi/utils/hosts.py
def list_attributes(cls): """ Lists all of the attributes to be found on an instance of this class. It creates a "fake instance" by passing in `None` to all of the ``__init__`` arguments, then returns all of the attributes of that instance. :return: A list of instance attributes of this class. :rtype: ``list`` of ``str`` """ fake_args = [None for _ in inspect.getargspec(cls.__init__).args[1:]] fake_instance = cls(*fake_args) return vars(fake_instance).keys()
def list_attributes(cls): """ Lists all of the attributes to be found on an instance of this class. It creates a "fake instance" by passing in `None` to all of the ``__init__`` arguments, then returns all of the attributes of that instance. :return: A list of instance attributes of this class. :rtype: ``list`` of ``str`` """ fake_args = [None for _ in inspect.getargspec(cls.__init__).args[1:]] fake_instance = cls(*fake_args) return vars(fake_instance).keys()
[ "Lists", "all", "of", "the", "attributes", "to", "be", "found", "on", "an", "instance", "of", "this", "class", ".", "It", "creates", "a", "fake", "instance", "by", "passing", "in", "None", "to", "all", "of", "the", "__init__", "arguments", "then", "returns", "all", "of", "the", "attributes", "of", "that", "instance", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L192-L204
[ "def", "list_attributes", "(", "cls", ")", ":", "fake_args", "=", "[", "None", "for", "_", "in", "inspect", ".", "getargspec", "(", "cls", ".", "__init__", ")", ".", "args", "[", "1", ":", "]", "]", "fake_instance", "=", "cls", "(", "*", "fake_args", ")", "return", "vars", "(", "fake_instance", ")", ".", "keys", "(", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.sort_by
Sorts a list of entries by the given attribute.
src/lsi/utils/hosts.py
def sort_by(cls, entries, attribute): """ Sorts a list of entries by the given attribute. """ def key(entry): return entry._get_attrib(attribute, convert_to_str=True) return sorted(entries, key=key)
def sort_by(cls, entries, attribute): """ Sorts a list of entries by the given attribute. """ def key(entry): return entry._get_attrib(attribute, convert_to_str=True) return sorted(entries, key=key)
[ "Sorts", "a", "list", "of", "entries", "by", "the", "given", "attribute", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L207-L213
[ "def", "sort_by", "(", "cls", ",", "entries", ",", "attribute", ")", ":", "def", "key", "(", "entry", ")", ":", "return", "entry", ".", "_get_attrib", "(", "attribute", ",", "convert_to_str", "=", "True", ")", "return", "sorted", "(", "entries", ",", "key", "=", "key", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.repr_as_line
Returns a representation of the host as a single line, with columns joined by ``sep``. :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` :param only_show: A specific list of columns to show. :type only_show: ``NoneType`` or ``list`` of ``str`` :param sep: The column separator to use. :type sep: ``str`` :rtype: ``str``
src/lsi/utils/hosts.py
def repr_as_line(self, additional_columns=None, only_show=None, sep=','): """ Returns a representation of the host as a single line, with columns joined by ``sep``. :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` :param only_show: A specific list of columns to show. :type only_show: ``NoneType`` or ``list`` of ``str`` :param sep: The column separator to use. :type sep: ``str`` :rtype: ``str`` """ additional_columns = additional_columns or [] if only_show is not None: columns = _uniquify(only_show) else: columns = _uniquify(self.DEFAULT_COLUMNS + additional_columns) to_display = [self._get_attrib(c, convert_to_str=True) for c in columns] return sep.join(to_display)
def repr_as_line(self, additional_columns=None, only_show=None, sep=','): """ Returns a representation of the host as a single line, with columns joined by ``sep``. :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` :param only_show: A specific list of columns to show. :type only_show: ``NoneType`` or ``list`` of ``str`` :param sep: The column separator to use. :type sep: ``str`` :rtype: ``str`` """ additional_columns = additional_columns or [] if only_show is not None: columns = _uniquify(only_show) else: columns = _uniquify(self.DEFAULT_COLUMNS + additional_columns) to_display = [self._get_attrib(c, convert_to_str=True) for c in columns] return sep.join(to_display)
[ "Returns", "a", "representation", "of", "the", "host", "as", "a", "single", "line", "with", "columns", "joined", "by", "sep", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L216-L236
[ "def", "repr_as_line", "(", "self", ",", "additional_columns", "=", "None", ",", "only_show", "=", "None", ",", "sep", "=", "','", ")", ":", "additional_columns", "=", "additional_columns", "or", "[", "]", "if", "only_show", "is", "not", "None", ":", "columns", "=", "_uniquify", "(", "only_show", ")", "else", ":", "columns", "=", "_uniquify", "(", "self", ".", "DEFAULT_COLUMNS", "+", "additional_columns", ")", "to_display", "=", "[", "self", ".", "_get_attrib", "(", "c", ",", "convert_to_str", "=", "True", ")", "for", "c", "in", "columns", "]", "return", "sep", ".", "join", "(", "to_display", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.from_boto_instance
Loads a ``HostEntry`` from a boto instance. :param instance: A boto instance object. :type instance: :py:class:`boto.ec2.instanceInstance` :rtype: :py:class:`HostEntry`
src/lsi/utils/hosts.py
def from_boto_instance(cls, instance): """ Loads a ``HostEntry`` from a boto instance. :param instance: A boto instance object. :type instance: :py:class:`boto.ec2.instanceInstance` :rtype: :py:class:`HostEntry` """ return cls( name=instance.tags.get('Name'), private_ip=instance.private_ip_address, public_ip=instance.ip_address, instance_type=instance.instance_type, instance_id=instance.id, hostname=instance.dns_name, stack_id=instance.tags.get('aws:cloudformation:stack-id'), stack_name=instance.tags.get('aws:cloudformation:stack-name'), logical_id=instance.tags.get('aws:cloudformation:logical-id'), security_groups=[g.name for g in instance.groups], launch_time=instance.launch_time, ami_id=instance.image_id, tags={k.lower(): v for k, v in six.iteritems(instance.tags)} )
def from_boto_instance(cls, instance): """ Loads a ``HostEntry`` from a boto instance. :param instance: A boto instance object. :type instance: :py:class:`boto.ec2.instanceInstance` :rtype: :py:class:`HostEntry` """ return cls( name=instance.tags.get('Name'), private_ip=instance.private_ip_address, public_ip=instance.ip_address, instance_type=instance.instance_type, instance_id=instance.id, hostname=instance.dns_name, stack_id=instance.tags.get('aws:cloudformation:stack-id'), stack_name=instance.tags.get('aws:cloudformation:stack-name'), logical_id=instance.tags.get('aws:cloudformation:logical-id'), security_groups=[g.name for g in instance.groups], launch_time=instance.launch_time, ami_id=instance.image_id, tags={k.lower(): v for k, v in six.iteritems(instance.tags)} )
[ "Loads", "a", "HostEntry", "from", "a", "boto", "instance", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L239-L262
[ "def", "from_boto_instance", "(", "cls", ",", "instance", ")", ":", "return", "cls", "(", "name", "=", "instance", ".", "tags", ".", "get", "(", "'Name'", ")", ",", "private_ip", "=", "instance", ".", "private_ip_address", ",", "public_ip", "=", "instance", ".", "ip_address", ",", "instance_type", "=", "instance", ".", "instance_type", ",", "instance_id", "=", "instance", ".", "id", ",", "hostname", "=", "instance", ".", "dns_name", ",", "stack_id", "=", "instance", ".", "tags", ".", "get", "(", "'aws:cloudformation:stack-id'", ")", ",", "stack_name", "=", "instance", ".", "tags", ".", "get", "(", "'aws:cloudformation:stack-name'", ")", ",", "logical_id", "=", "instance", ".", "tags", ".", "get", "(", "'aws:cloudformation:logical-id'", ")", ",", "security_groups", "=", "[", "g", ".", "name", "for", "g", "in", "instance", ".", "groups", "]", ",", "launch_time", "=", "instance", ".", "launch_time", ",", "ami_id", "=", "instance", ".", "image_id", ",", "tags", "=", "{", "k", ".", "lower", "(", ")", ":", "v", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "instance", ".", "tags", ")", "}", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.matches
Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the part after will be applied to that attribute. :type _filter: ``basestring`` :return: True if the entry matches the filter. :rtype: ``bool``
src/lsi/utils/hosts.py
def matches(self, _filter): """ Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the part after will be applied to that attribute. :type _filter: ``basestring`` :return: True if the entry matches the filter. :rtype: ``bool`` """ within_attrib = re.match(r'^([a-z_.]+):(.*)', _filter) having_attrib = re.match(r'^([a-z_.]+)\?$', _filter) if within_attrib is not None: # Then we're matching against a specific attribute. val = self._get_attrib(within_attrib.group(1)) sub_regex = within_attrib.group(2) if len(sub_regex) > 0: sub_regex = re.compile(sub_regex, re.IGNORECASE) return _match_regex(sub_regex, val) else: # Then we are matching on the value being empty. return val == '' or val is None or val == [] elif having_attrib is not None: # Then we're searching for anything that has a specific attribute. val = self._get_attrib(having_attrib.group(1)) return val != '' and val is not None and val != [] else: regex = re.compile(_filter, re.IGNORECASE) return _match_regex(regex, vars(self))
def matches(self, _filter): """ Returns whether the instance matches the given filter text. :param _filter: A regex filter. If it starts with `<identifier>:`, then the part before the colon will be used as an attribute and the part after will be applied to that attribute. :type _filter: ``basestring`` :return: True if the entry matches the filter. :rtype: ``bool`` """ within_attrib = re.match(r'^([a-z_.]+):(.*)', _filter) having_attrib = re.match(r'^([a-z_.]+)\?$', _filter) if within_attrib is not None: # Then we're matching against a specific attribute. val = self._get_attrib(within_attrib.group(1)) sub_regex = within_attrib.group(2) if len(sub_regex) > 0: sub_regex = re.compile(sub_regex, re.IGNORECASE) return _match_regex(sub_regex, val) else: # Then we are matching on the value being empty. return val == '' or val is None or val == [] elif having_attrib is not None: # Then we're searching for anything that has a specific attribute. val = self._get_attrib(having_attrib.group(1)) return val != '' and val is not None and val != [] else: regex = re.compile(_filter, re.IGNORECASE) return _match_regex(regex, vars(self))
[ "Returns", "whether", "the", "instance", "matches", "the", "given", "filter", "text", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L264-L294
[ "def", "matches", "(", "self", ",", "_filter", ")", ":", "within_attrib", "=", "re", ".", "match", "(", "r'^([a-z_.]+):(.*)'", ",", "_filter", ")", "having_attrib", "=", "re", ".", "match", "(", "r'^([a-z_.]+)\\?$'", ",", "_filter", ")", "if", "within_attrib", "is", "not", "None", ":", "# Then we're matching against a specific attribute.", "val", "=", "self", ".", "_get_attrib", "(", "within_attrib", ".", "group", "(", "1", ")", ")", "sub_regex", "=", "within_attrib", ".", "group", "(", "2", ")", "if", "len", "(", "sub_regex", ")", ">", "0", ":", "sub_regex", "=", "re", ".", "compile", "(", "sub_regex", ",", "re", ".", "IGNORECASE", ")", "return", "_match_regex", "(", "sub_regex", ",", "val", ")", "else", ":", "# Then we are matching on the value being empty.", "return", "val", "==", "''", "or", "val", "is", "None", "or", "val", "==", "[", "]", "elif", "having_attrib", "is", "not", "None", ":", "# Then we're searching for anything that has a specific attribute.", "val", "=", "self", ".", "_get_attrib", "(", "having_attrib", ".", "group", "(", "1", ")", ")", "return", "val", "!=", "''", "and", "val", "is", "not", "None", "and", "val", "!=", "[", "]", "else", ":", "regex", "=", "re", ".", "compile", "(", "_filter", ",", "re", ".", "IGNORECASE", ")", "return", "_match_regex", "(", "regex", ",", "vars", "(", "self", ")", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.display
Returns the best name to display for this host. Uses the instance name if available; else just the public IP. :rtype: ``str``
src/lsi/utils/hosts.py
def display(self): """ Returns the best name to display for this host. Uses the instance name if available; else just the public IP. :rtype: ``str`` """ if isinstance(self.name, six.string_types) and len(self.name) > 0: return '{0} ({1})'.format(self.name, self.public_ip) else: return self.public_ip
def display(self): """ Returns the best name to display for this host. Uses the instance name if available; else just the public IP. :rtype: ``str`` """ if isinstance(self.name, six.string_types) and len(self.name) > 0: return '{0} ({1})'.format(self.name, self.public_ip) else: return self.public_ip
[ "Returns", "the", "best", "name", "to", "display", "for", "this", "host", ".", "Uses", "the", "instance", "name", "if", "available", ";", "else", "just", "the", "public", "IP", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L296-L306
[ "def", "display", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "name", ",", "six", ".", "string_types", ")", "and", "len", "(", "self", ".", "name", ")", ">", "0", ":", "return", "'{0} ({1})'", ".", "format", "(", "self", ".", "name", ",", "self", ".", "public_ip", ")", "else", ":", "return", "self", ".", "public_ip" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.prettyname
Returns the "pretty name" (capitalized, etc) of an attribute, by looking it up in ``cls.COLUMN_NAMES`` if it exists there. :param attrib_name: An attribute name. :type attrib_name: ``str`` :rtype: ``str``
src/lsi/utils/hosts.py
def prettyname(cls, attrib_name): """ Returns the "pretty name" (capitalized, etc) of an attribute, by looking it up in ``cls.COLUMN_NAMES`` if it exists there. :param attrib_name: An attribute name. :type attrib_name: ``str`` :rtype: ``str`` """ if attrib_name.startswith('tags.'): tagname = attrib_name[len('tags.'):] return '{} (tag)'.format(tagname) elif attrib_name in cls.COLUMN_NAMES: return cls.COLUMN_NAMES[attrib_name] else: return attrib_name
def prettyname(cls, attrib_name): """ Returns the "pretty name" (capitalized, etc) of an attribute, by looking it up in ``cls.COLUMN_NAMES`` if it exists there. :param attrib_name: An attribute name. :type attrib_name: ``str`` :rtype: ``str`` """ if attrib_name.startswith('tags.'): tagname = attrib_name[len('tags.'):] return '{} (tag)'.format(tagname) elif attrib_name in cls.COLUMN_NAMES: return cls.COLUMN_NAMES[attrib_name] else: return attrib_name
[ "Returns", "the", "pretty", "name", "(", "capitalized", "etc", ")", "of", "an", "attribute", "by", "looking", "it", "up", "in", "cls", ".", "COLUMN_NAMES", "if", "it", "exists", "there", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L309-L325
[ "def", "prettyname", "(", "cls", ",", "attrib_name", ")", ":", "if", "attrib_name", ".", "startswith", "(", "'tags.'", ")", ":", "tagname", "=", "attrib_name", "[", "len", "(", "'tags.'", ")", ":", "]", "return", "'{} (tag)'", ".", "format", "(", "tagname", ")", "elif", "attrib_name", "in", "cls", ".", "COLUMN_NAMES", ":", "return", "cls", ".", "COLUMN_NAMES", "[", "attrib_name", "]", "else", ":", "return", "attrib_name" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.format_string
Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to this instance. E.g. 'production-runtime-foo.txt' :rtype: ``str``
src/lsi/utils/hosts.py
def format_string(self, fmat_string): """ Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to this instance. E.g. 'production-runtime-foo.txt' :rtype: ``str`` """ try: return fmat_string.format(**vars(self)) except KeyError as e: raise ValueError('Invalid format string: {0}. Instance has no ' 'attribute {1}.'.format(repr(fmat_string), repr(e)))
def format_string(self, fmat_string): """ Takes a string containing 0 or more {variables} and formats it according to this instance's attributes. :param fmat_string: A string, e.g. '{name}-foo.txt' :type fmat_string: ``str`` :return: The string formatted according to this instance. E.g. 'production-runtime-foo.txt' :rtype: ``str`` """ try: return fmat_string.format(**vars(self)) except KeyError as e: raise ValueError('Invalid format string: {0}. Instance has no ' 'attribute {1}.'.format(repr(fmat_string), repr(e)))
[ "Takes", "a", "string", "containing", "0", "or", "more", "{", "variables", "}", "and", "formats", "it", "according", "to", "this", "instance", "s", "attributes", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L327-L344
[ "def", "format_string", "(", "self", ",", "fmat_string", ")", ":", "try", ":", "return", "fmat_string", ".", "format", "(", "*", "*", "vars", "(", "self", ")", ")", "except", "KeyError", "as", "e", ":", "raise", "ValueError", "(", "'Invalid format string: {0}. Instance has no '", "'attribute {1}.'", ".", "format", "(", "repr", "(", "fmat_string", ")", ",", "repr", "(", "e", ")", ")", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
HostEntry.render_entries
Pretty-prints a list of entries. If the window is wide enough to support printing as a table, runs the `print_table.render_table` function on the table. Otherwise, constructs a line-by-line representation.. :param entries: A list of entries. :type entries: [:py:class:`HostEntry`] :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` :param only_show: A specific list of columns to show. :type only_show: ``NoneType`` or ``list`` of ``str`` :param numbers: Whether to include a number column. :type numbers: ``bool`` :return: A pretty-printed string. :rtype: ``str``
src/lsi/utils/hosts.py
def render_entries(cls, entries, additional_columns=None, only_show=None, numbers=False): """ Pretty-prints a list of entries. If the window is wide enough to support printing as a table, runs the `print_table.render_table` function on the table. Otherwise, constructs a line-by-line representation.. :param entries: A list of entries. :type entries: [:py:class:`HostEntry`] :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` :param only_show: A specific list of columns to show. :type only_show: ``NoneType`` or ``list`` of ``str`` :param numbers: Whether to include a number column. :type numbers: ``bool`` :return: A pretty-printed string. :rtype: ``str`` """ additional_columns = additional_columns or [] if only_show is not None: columns = _uniquify(only_show) else: columns = _uniquify(cls.DEFAULT_COLUMNS + additional_columns) top_row = [cls.prettyname(col) for col in columns] table = [top_row] if numbers is False else [[''] + top_row] for i, entry in enumerate(entries): row = [entry._get_attrib(c, convert_to_str=True) for c in columns] table.append(row if numbers is False else [i] + row) cur_width = get_current_terminal_width() colors = [get_color_hash(c, MIN_COLOR_BRIGHT, MAX_COLOR_BRIGHT) for c in columns] if cur_width >= get_table_width(table): return render_table(table, column_colors=colors if numbers is False else [green] + colors) else: result = [] first_index = 1 if numbers is True else 0 for row in table[1:]: rep = [green('%s:' % row[0] if numbers is True else '-----')] for i, val in enumerate(row[first_index:]): color = colors[i-1 if numbers is True else i] name = columns[i] rep.append(' %s: %s' % (name, color(val))) result.append('\n'.join(rep)) return '\n'.join(result)
def render_entries(cls, entries, additional_columns=None, only_show=None, numbers=False): """ Pretty-prints a list of entries. If the window is wide enough to support printing as a table, runs the `print_table.render_table` function on the table. Otherwise, constructs a line-by-line representation.. :param entries: A list of entries. :type entries: [:py:class:`HostEntry`] :param additional_columns: Columns to show in addition to defaults. :type additional_columns: ``list`` of ``str`` :param only_show: A specific list of columns to show. :type only_show: ``NoneType`` or ``list`` of ``str`` :param numbers: Whether to include a number column. :type numbers: ``bool`` :return: A pretty-printed string. :rtype: ``str`` """ additional_columns = additional_columns or [] if only_show is not None: columns = _uniquify(only_show) else: columns = _uniquify(cls.DEFAULT_COLUMNS + additional_columns) top_row = [cls.prettyname(col) for col in columns] table = [top_row] if numbers is False else [[''] + top_row] for i, entry in enumerate(entries): row = [entry._get_attrib(c, convert_to_str=True) for c in columns] table.append(row if numbers is False else [i] + row) cur_width = get_current_terminal_width() colors = [get_color_hash(c, MIN_COLOR_BRIGHT, MAX_COLOR_BRIGHT) for c in columns] if cur_width >= get_table_width(table): return render_table(table, column_colors=colors if numbers is False else [green] + colors) else: result = [] first_index = 1 if numbers is True else 0 for row in table[1:]: rep = [green('%s:' % row[0] if numbers is True else '-----')] for i, val in enumerate(row[first_index:]): color = colors[i-1 if numbers is True else i] name = columns[i] rep.append(' %s: %s' % (name, color(val))) result.append('\n'.join(rep)) return '\n'.join(result)
[ "Pretty", "-", "prints", "a", "list", "of", "entries", ".", "If", "the", "window", "is", "wide", "enough", "to", "support", "printing", "as", "a", "table", "runs", "the", "print_table", ".", "render_table", "function", "on", "the", "table", ".", "Otherwise", "constructs", "a", "line", "-", "by", "-", "line", "representation", ".." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/hosts.py#L347-L394
[ "def", "render_entries", "(", "cls", ",", "entries", ",", "additional_columns", "=", "None", ",", "only_show", "=", "None", ",", "numbers", "=", "False", ")", ":", "additional_columns", "=", "additional_columns", "or", "[", "]", "if", "only_show", "is", "not", "None", ":", "columns", "=", "_uniquify", "(", "only_show", ")", "else", ":", "columns", "=", "_uniquify", "(", "cls", ".", "DEFAULT_COLUMNS", "+", "additional_columns", ")", "top_row", "=", "[", "cls", ".", "prettyname", "(", "col", ")", "for", "col", "in", "columns", "]", "table", "=", "[", "top_row", "]", "if", "numbers", "is", "False", "else", "[", "[", "''", "]", "+", "top_row", "]", "for", "i", ",", "entry", "in", "enumerate", "(", "entries", ")", ":", "row", "=", "[", "entry", ".", "_get_attrib", "(", "c", ",", "convert_to_str", "=", "True", ")", "for", "c", "in", "columns", "]", "table", ".", "append", "(", "row", "if", "numbers", "is", "False", "else", "[", "i", "]", "+", "row", ")", "cur_width", "=", "get_current_terminal_width", "(", ")", "colors", "=", "[", "get_color_hash", "(", "c", ",", "MIN_COLOR_BRIGHT", ",", "MAX_COLOR_BRIGHT", ")", "for", "c", "in", "columns", "]", "if", "cur_width", ">=", "get_table_width", "(", "table", ")", ":", "return", "render_table", "(", "table", ",", "column_colors", "=", "colors", "if", "numbers", "is", "False", "else", "[", "green", "]", "+", "colors", ")", "else", ":", "result", "=", "[", "]", "first_index", "=", "1", "if", "numbers", "is", "True", "else", "0", "for", "row", "in", "table", "[", "1", ":", "]", ":", "rep", "=", "[", "green", "(", "'%s:'", "%", "row", "[", "0", "]", "if", "numbers", "is", "True", "else", "'-----'", ")", "]", "for", "i", ",", "val", "in", "enumerate", "(", "row", "[", "first_index", ":", "]", ")", ":", "color", "=", "colors", "[", "i", "-", "1", "if", "numbers", "is", "True", "else", "i", "]", "name", "=", "columns", "[", "i", "]", "rep", ".", "append", "(", "' %s: %s'", "%", "(", "name", ",", "color", "(", "val", ")", ")", ")", "result", ".", "append", "(", "'\\n'", ".", "join", "(", "rep", ")", ")", "return", "'\\n'", ".", "join", "(", "result", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
add_timestamp
Attach the event time, as unix epoch
python/dna/logging.py
def add_timestamp(logger_class, log_method, event_dict): ''' Attach the event time, as unix epoch ''' event_dict['timestamp'] = calendar.timegm(time.gmtime()) return event_dict
def add_timestamp(logger_class, log_method, event_dict): ''' Attach the event time, as unix epoch ''' event_dict['timestamp'] = calendar.timegm(time.gmtime()) return event_dict
[ "Attach", "the", "event", "time", "as", "unix", "epoch" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/logging.py#L25-L28
[ "def", "add_timestamp", "(", "logger_class", ",", "log_method", ",", "event_dict", ")", ":", "event_dict", "[", "'timestamp'", "]", "=", "calendar", ".", "timegm", "(", "time", ".", "gmtime", "(", ")", ")", "return", "event_dict" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
setup
Hivy formated logger
python/dna/logging.py
def setup(level='debug', output=None): ''' Hivy formated logger ''' output = output or settings.LOG['file'] level = level.upper() handlers = [ logbook.NullHandler() ] if output == 'stdout': handlers.append( logbook.StreamHandler(sys.stdout, format_string=settings.LOG['format'], level=level)) else: handlers.append( logbook.FileHandler(output, format_string=settings.LOG['format'], level=level)) sentry_dns = settings.LOG['sentry_dns'] if sentry_dns: handlers.append(SentryHandler(sentry_dns, level='ERROR')) return logbook.NestedSetup(handlers)
def setup(level='debug', output=None): ''' Hivy formated logger ''' output = output or settings.LOG['file'] level = level.upper() handlers = [ logbook.NullHandler() ] if output == 'stdout': handlers.append( logbook.StreamHandler(sys.stdout, format_string=settings.LOG['format'], level=level)) else: handlers.append( logbook.FileHandler(output, format_string=settings.LOG['format'], level=level)) sentry_dns = settings.LOG['sentry_dns'] if sentry_dns: handlers.append(SentryHandler(sentry_dns, level='ERROR')) return logbook.NestedSetup(handlers)
[ "Hivy", "formated", "logger" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/logging.py#L31-L54
[ "def", "setup", "(", "level", "=", "'debug'", ",", "output", "=", "None", ")", ":", "output", "=", "output", "or", "settings", ".", "LOG", "[", "'file'", "]", "level", "=", "level", ".", "upper", "(", ")", "handlers", "=", "[", "logbook", ".", "NullHandler", "(", ")", "]", "if", "output", "==", "'stdout'", ":", "handlers", ".", "append", "(", "logbook", ".", "StreamHandler", "(", "sys", ".", "stdout", ",", "format_string", "=", "settings", ".", "LOG", "[", "'format'", "]", ",", "level", "=", "level", ")", ")", "else", ":", "handlers", ".", "append", "(", "logbook", ".", "FileHandler", "(", "output", ",", "format_string", "=", "settings", ".", "LOG", "[", "'format'", "]", ",", "level", "=", "level", ")", ")", "sentry_dns", "=", "settings", ".", "LOG", "[", "'sentry_dns'", "]", "if", "sentry_dns", ":", "handlers", ".", "append", "(", "SentryHandler", "(", "sentry_dns", ",", "level", "=", "'ERROR'", ")", ")", "return", "logbook", ".", "NestedSetup", "(", "handlers", ")" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
logger
Configure and return a new logger for hivy modules
python/dna/logging.py
def logger(name=__name__, output=None, uuid=False, timestamp=False): ''' Configure and return a new logger for hivy modules ''' processors = [] if output == 'json': processors.append(structlog.processors.JSONRenderer()) if uuid: processors.append(add_unique_id) if uuid: processors.append(add_timestamp) return structlog.wrap_logger( logbook.Logger(name), processors=processors )
def logger(name=__name__, output=None, uuid=False, timestamp=False): ''' Configure and return a new logger for hivy modules ''' processors = [] if output == 'json': processors.append(structlog.processors.JSONRenderer()) if uuid: processors.append(add_unique_id) if uuid: processors.append(add_timestamp) return structlog.wrap_logger( logbook.Logger(name), processors=processors )
[ "Configure", "and", "return", "a", "new", "logger", "for", "hivy", "modules" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/logging.py#L57-L70
[ "def", "logger", "(", "name", "=", "__name__", ",", "output", "=", "None", ",", "uuid", "=", "False", ",", "timestamp", "=", "False", ")", ":", "processors", "=", "[", "]", "if", "output", "==", "'json'", ":", "processors", ".", "append", "(", "structlog", ".", "processors", ".", "JSONRenderer", "(", ")", ")", "if", "uuid", ":", "processors", ".", "append", "(", "add_unique_id", ")", "if", "uuid", ":", "processors", ".", "append", "(", "add_timestamp", ")", "return", "structlog", ".", "wrap_logger", "(", "logbook", ".", "Logger", "(", "name", ")", ",", "processors", "=", "processors", ")" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
setup
Implement celery workers using json and redis
python/dna/apy/worker.py
def setup(title, output='json', timezone=None): ''' Implement celery workers using json and redis ''' timezone = timezone or dna.time_utils._detect_timezone() broker_url = 'redis://{}:{}/{}'.format( os.environ.get('BROKER_HOST', 'localhost'), os.environ.get('BROKER_PORT', 6379), 0 ) app = Celery(title, broker=broker_url) app.conf.update( CELERY_TASK_SERIALIZER=output, CELERY_ACCEPT_CONTENT=[output], # Ignore other content CELERY_RESULT_SERIALIZER=output, CELERY_RESULT_BACKEND=broker_url, CELERY_TIMEZONE=timezone, CELERYD_FORCE_EXECV=True, CELERY_ENABLE_UTC=True, CELERY_IGNORE_RESULT=False ) return app
def setup(title, output='json', timezone=None): ''' Implement celery workers using json and redis ''' timezone = timezone or dna.time_utils._detect_timezone() broker_url = 'redis://{}:{}/{}'.format( os.environ.get('BROKER_HOST', 'localhost'), os.environ.get('BROKER_PORT', 6379), 0 ) app = Celery(title, broker=broker_url) app.conf.update( CELERY_TASK_SERIALIZER=output, CELERY_ACCEPT_CONTENT=[output], # Ignore other content CELERY_RESULT_SERIALIZER=output, CELERY_RESULT_BACKEND=broker_url, CELERY_TIMEZONE=timezone, CELERYD_FORCE_EXECV=True, CELERY_ENABLE_UTC=True, CELERY_IGNORE_RESULT=False ) return app
[ "Implement", "celery", "workers", "using", "json", "and", "redis" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/worker.py#L22-L45
[ "def", "setup", "(", "title", ",", "output", "=", "'json'", ",", "timezone", "=", "None", ")", ":", "timezone", "=", "timezone", "or", "dna", ".", "time_utils", ".", "_detect_timezone", "(", ")", "broker_url", "=", "'redis://{}:{}/{}'", ".", "format", "(", "os", ".", "environ", ".", "get", "(", "'BROKER_HOST'", ",", "'localhost'", ")", ",", "os", ".", "environ", ".", "get", "(", "'BROKER_PORT'", ",", "6379", ")", ",", "0", ")", "app", "=", "Celery", "(", "title", ",", "broker", "=", "broker_url", ")", "app", ".", "conf", ".", "update", "(", "CELERY_TASK_SERIALIZER", "=", "output", ",", "CELERY_ACCEPT_CONTENT", "=", "[", "output", "]", ",", "# Ignore other content", "CELERY_RESULT_SERIALIZER", "=", "output", ",", "CELERY_RESULT_BACKEND", "=", "broker_url", ",", "CELERY_TIMEZONE", "=", "timezone", ",", "CELERYD_FORCE_EXECV", "=", "True", ",", "CELERY_ENABLE_UTC", "=", "True", ",", "CELERY_IGNORE_RESULT", "=", "False", ")", "return", "app" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
RestfulWorker.get
Return status report
python/dna/apy/worker.py
def get(self, worker_id): ''' Return status report ''' code = 200 if worker_id == 'all': report = {'workers': [{ 'id': job, 'report': self._inspect_worker(job)} for job in self.jobs] } elif worker_id in self.jobs: report = { 'id': worker_id, 'report': self._inspect_worker(worker_id) } else: report = {'error': 'job {} unknown'.format(worker_id)} code = 404 return flask.jsonify(report), code
def get(self, worker_id): ''' Return status report ''' code = 200 if worker_id == 'all': report = {'workers': [{ 'id': job, 'report': self._inspect_worker(job)} for job in self.jobs] } elif worker_id in self.jobs: report = { 'id': worker_id, 'report': self._inspect_worker(worker_id) } else: report = {'error': 'job {} unknown'.format(worker_id)} code = 404 return flask.jsonify(report), code
[ "Return", "status", "report" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/worker.py#L93-L114
[ "def", "get", "(", "self", ",", "worker_id", ")", ":", "code", "=", "200", "if", "worker_id", "==", "'all'", ":", "report", "=", "{", "'workers'", ":", "[", "{", "'id'", ":", "job", ",", "'report'", ":", "self", ".", "_inspect_worker", "(", "job", ")", "}", "for", "job", "in", "self", ".", "jobs", "]", "}", "elif", "worker_id", "in", "self", ".", "jobs", ":", "report", "=", "{", "'id'", ":", "worker_id", ",", "'report'", ":", "self", ".", "_inspect_worker", "(", "worker_id", ")", "}", "else", ":", "report", "=", "{", "'error'", ":", "'job {} unknown'", ".", "format", "(", "worker_id", ")", "}", "code", "=", "404", "return", "flask", ".", "jsonify", "(", "report", ")", ",", "code" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
RestfulWorker.delete
Stop and remove a worker
python/dna/apy/worker.py
def delete(self, worker_id): ''' Stop and remove a worker ''' code = 200 if worker_id in self.jobs: # NOTE pop it if done ? self.jobs[worker_id]['worker'].revoke(terminate=True) report = { 'id': worker_id, 'revoked': True # FIXME Unable to serialize self.jobs[worker_id] # 'session': self.jobs.pop(worker_id) } self.jobs.pop(worker_id) else: report = {'error': 'job {} unknown'.format(worker_id)} code = 404 return flask.jsonify(report), code
def delete(self, worker_id): ''' Stop and remove a worker ''' code = 200 if worker_id in self.jobs: # NOTE pop it if done ? self.jobs[worker_id]['worker'].revoke(terminate=True) report = { 'id': worker_id, 'revoked': True # FIXME Unable to serialize self.jobs[worker_id] # 'session': self.jobs.pop(worker_id) } self.jobs.pop(worker_id) else: report = {'error': 'job {} unknown'.format(worker_id)} code = 404 return flask.jsonify(report), code
[ "Stop", "and", "remove", "a", "worker" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/worker.py#L117-L135
[ "def", "delete", "(", "self", ",", "worker_id", ")", ":", "code", "=", "200", "if", "worker_id", "in", "self", ".", "jobs", ":", "# NOTE pop it if done ?", "self", ".", "jobs", "[", "worker_id", "]", "[", "'worker'", "]", ".", "revoke", "(", "terminate", "=", "True", ")", "report", "=", "{", "'id'", ":", "worker_id", ",", "'revoked'", ":", "True", "# FIXME Unable to serialize self.jobs[worker_id]", "# 'session': self.jobs.pop(worker_id)", "}", "self", ".", "jobs", ".", "pop", "(", "worker_id", ")", "else", ":", "report", "=", "{", "'error'", ":", "'job {} unknown'", ".", "format", "(", "worker_id", ")", "}", "code", "=", "404", "return", "flask", ".", "jsonify", "(", "report", ")", ",", "code" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
main
Reusable entry point. Arguments are parsed via the argparse-subcommands configured via each Command class found in globals(). Stop exceptions are propagated to callers. The name of the framework will be used in logging and similar.
yaclifw/framework.py
def main(fw_name, args=None, items=None): """ Reusable entry point. Arguments are parsed via the argparse-subcommands configured via each Command class found in globals(). Stop exceptions are propagated to callers. The name of the framework will be used in logging and similar. """ global DEBUG_LEVEL global FRAMEWORK_NAME debug_name = "%s_DEBUG_LEVEL" % fw_name.upper() if debug_name in os.environ: try: DEBUG_LEVEL = int(os.environ.get(debug_name)) except ValueError: DEBUG_LEVEL = 10 # Assume poorly formatted means "debug" FRAMEWORK_NAME = fw_name if args is None: args = sys.argv[1:] if items is None: items = list(globals().items()) yaclifw_parser, sub_parsers = parsers() for name, MyCommand in sorted(items): if not isinstance(MyCommand, type): continue if not issubclass(MyCommand, Command): continue if MyCommand.NAME == "abstract": continue MyCommand(sub_parsers) ns = yaclifw_parser.parse_args(args) ns.func(ns) if hasattr(ns, 'callback'): if callable(ns.callback): ns.callback() else: raise Stop(3, "Callback not callable")
def main(fw_name, args=None, items=None): """ Reusable entry point. Arguments are parsed via the argparse-subcommands configured via each Command class found in globals(). Stop exceptions are propagated to callers. The name of the framework will be used in logging and similar. """ global DEBUG_LEVEL global FRAMEWORK_NAME debug_name = "%s_DEBUG_LEVEL" % fw_name.upper() if debug_name in os.environ: try: DEBUG_LEVEL = int(os.environ.get(debug_name)) except ValueError: DEBUG_LEVEL = 10 # Assume poorly formatted means "debug" FRAMEWORK_NAME = fw_name if args is None: args = sys.argv[1:] if items is None: items = list(globals().items()) yaclifw_parser, sub_parsers = parsers() for name, MyCommand in sorted(items): if not isinstance(MyCommand, type): continue if not issubclass(MyCommand, Command): continue if MyCommand.NAME == "abstract": continue MyCommand(sub_parsers) ns = yaclifw_parser.parse_args(args) ns.func(ns) if hasattr(ns, 'callback'): if callable(ns.callback): ns.callback() else: raise Stop(3, "Callback not callable")
[ "Reusable", "entry", "point", ".", "Arguments", "are", "parsed", "via", "the", "argparse", "-", "subcommands", "configured", "via", "each", "Command", "class", "found", "in", "globals", "()", ".", "Stop", "exceptions", "are", "propagated", "to", "callers", "." ]
openmicroscopy/yaclifw
python
https://github.com/openmicroscopy/yaclifw/blob/a01179fefb2c2c4260c75e6d1dc6e19de9979d64/yaclifw/framework.py#L148-L193
[ "def", "main", "(", "fw_name", ",", "args", "=", "None", ",", "items", "=", "None", ")", ":", "global", "DEBUG_LEVEL", "global", "FRAMEWORK_NAME", "debug_name", "=", "\"%s_DEBUG_LEVEL\"", "%", "fw_name", ".", "upper", "(", ")", "if", "debug_name", "in", "os", ".", "environ", ":", "try", ":", "DEBUG_LEVEL", "=", "int", "(", "os", ".", "environ", ".", "get", "(", "debug_name", ")", ")", "except", "ValueError", ":", "DEBUG_LEVEL", "=", "10", "# Assume poorly formatted means \"debug\"", "FRAMEWORK_NAME", "=", "fw_name", "if", "args", "is", "None", ":", "args", "=", "sys", ".", "argv", "[", "1", ":", "]", "if", "items", "is", "None", ":", "items", "=", "list", "(", "globals", "(", ")", ".", "items", "(", ")", ")", "yaclifw_parser", ",", "sub_parsers", "=", "parsers", "(", ")", "for", "name", ",", "MyCommand", "in", "sorted", "(", "items", ")", ":", "if", "not", "isinstance", "(", "MyCommand", ",", "type", ")", ":", "continue", "if", "not", "issubclass", "(", "MyCommand", ",", "Command", ")", ":", "continue", "if", "MyCommand", ".", "NAME", "==", "\"abstract\"", ":", "continue", "MyCommand", "(", "sub_parsers", ")", "ns", "=", "yaclifw_parser", ".", "parse_args", "(", "args", ")", "ns", ".", "func", "(", "ns", ")", "if", "hasattr", "(", "ns", ",", "'callback'", ")", ":", "if", "callable", "(", "ns", ".", "callback", ")", ":", "ns", ".", "callback", "(", ")", "else", ":", "raise", "Stop", "(", "3", ",", "\"Callback not callable\"", ")" ]
a01179fefb2c2c4260c75e6d1dc6e19de9979d64
test
switch_opt
Define a switchable ConfOpt. This creates a boolean option. If you use it in your CLI, it can be switched on and off by prepending + or - to its name: +opt / -opt. Args: default (bool): the default value of the swith option. shortname (str): short name of the option, no shortname will be used if it is set to None. help_msg (str): short description of the option. Returns: :class:`~loam.manager.ConfOpt`: a configuration option with the given properties.
loam/tools.py
def switch_opt(default, shortname, help_msg): """Define a switchable ConfOpt. This creates a boolean option. If you use it in your CLI, it can be switched on and off by prepending + or - to its name: +opt / -opt. Args: default (bool): the default value of the swith option. shortname (str): short name of the option, no shortname will be used if it is set to None. help_msg (str): short description of the option. Returns: :class:`~loam.manager.ConfOpt`: a configuration option with the given properties. """ return ConfOpt(bool(default), True, shortname, dict(action=internal.Switch), True, help_msg, None)
def switch_opt(default, shortname, help_msg): """Define a switchable ConfOpt. This creates a boolean option. If you use it in your CLI, it can be switched on and off by prepending + or - to its name: +opt / -opt. Args: default (bool): the default value of the swith option. shortname (str): short name of the option, no shortname will be used if it is set to None. help_msg (str): short description of the option. Returns: :class:`~loam.manager.ConfOpt`: a configuration option with the given properties. """ return ConfOpt(bool(default), True, shortname, dict(action=internal.Switch), True, help_msg, None)
[ "Define", "a", "switchable", "ConfOpt", "." ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/tools.py#L15-L32
[ "def", "switch_opt", "(", "default", ",", "shortname", ",", "help_msg", ")", ":", "return", "ConfOpt", "(", "bool", "(", "default", ")", ",", "True", ",", "shortname", ",", "dict", "(", "action", "=", "internal", ".", "Switch", ")", ",", "True", ",", "help_msg", ",", "None", ")" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
config_conf_section
Define a configuration section handling config file. Returns: dict of ConfOpt: it defines the 'create', 'update', 'edit' and 'editor' configuration options.
loam/tools.py
def config_conf_section(): """Define a configuration section handling config file. Returns: dict of ConfOpt: it defines the 'create', 'update', 'edit' and 'editor' configuration options. """ config_dict = OrderedDict(( ('create', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'create most global config file')), ('create_local', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'create most local config file')), ('update', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'add missing entries to config file')), ('edit', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'open config file in a text editor')), ('editor', ConfOpt('vim', False, None, {}, True, 'text editor')), )) return config_dict
def config_conf_section(): """Define a configuration section handling config file. Returns: dict of ConfOpt: it defines the 'create', 'update', 'edit' and 'editor' configuration options. """ config_dict = OrderedDict(( ('create', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'create most global config file')), ('create_local', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'create most local config file')), ('update', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'add missing entries to config file')), ('edit', ConfOpt(None, True, None, {'action': 'store_true'}, False, 'open config file in a text editor')), ('editor', ConfOpt('vim', False, None, {}, True, 'text editor')), )) return config_dict
[ "Define", "a", "configuration", "section", "handling", "config", "file", "." ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/tools.py#L35-L58
[ "def", "config_conf_section", "(", ")", ":", "config_dict", "=", "OrderedDict", "(", "(", "(", "'create'", ",", "ConfOpt", "(", "None", ",", "True", ",", "None", ",", "{", "'action'", ":", "'store_true'", "}", ",", "False", ",", "'create most global config file'", ")", ")", ",", "(", "'create_local'", ",", "ConfOpt", "(", "None", ",", "True", ",", "None", ",", "{", "'action'", ":", "'store_true'", "}", ",", "False", ",", "'create most local config file'", ")", ")", ",", "(", "'update'", ",", "ConfOpt", "(", "None", ",", "True", ",", "None", ",", "{", "'action'", ":", "'store_true'", "}", ",", "False", ",", "'add missing entries to config file'", ")", ")", ",", "(", "'edit'", ",", "ConfOpt", "(", "None", ",", "True", ",", "None", ",", "{", "'action'", ":", "'store_true'", "}", ",", "False", ",", "'open config file in a text editor'", ")", ")", ",", "(", "'editor'", ",", "ConfOpt", "(", "'vim'", ",", "False", ",", "None", ",", "{", "}", ",", "True", ",", "'text editor'", ")", ")", ",", ")", ")", "return", "config_dict" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
set_conf_str
Set options from a list of section.option=value string. Args: conf (:class:`~loam.manager.ConfigurationManager`): the conf to update. optstrs (list of str): the list of 'section.option=value' formatted string.
loam/tools.py
def set_conf_str(conf, optstrs): """Set options from a list of section.option=value string. Args: conf (:class:`~loam.manager.ConfigurationManager`): the conf to update. optstrs (list of str): the list of 'section.option=value' formatted string. """ falsy = ['0', 'no', 'n', 'off', 'false', 'f'] bool_actions = ['store_true', 'store_false', internal.Switch] for optstr in optstrs: opt, val = optstr.split('=', 1) sec, opt = opt.split('.', 1) if sec not in conf: raise error.SectionError(sec) if opt not in conf[sec]: raise error.OptionError(opt) meta = conf[sec].def_[opt] if meta.default is None: if 'type' in meta.cmd_kwargs: cast = meta.cmd_kwargs['type'] else: act = meta.cmd_kwargs.get('action') cast = bool if act in bool_actions else str else: cast = type(meta.default) if cast is bool and val.lower() in falsy: val = '' conf[sec][opt] = cast(val)
def set_conf_str(conf, optstrs): """Set options from a list of section.option=value string. Args: conf (:class:`~loam.manager.ConfigurationManager`): the conf to update. optstrs (list of str): the list of 'section.option=value' formatted string. """ falsy = ['0', 'no', 'n', 'off', 'false', 'f'] bool_actions = ['store_true', 'store_false', internal.Switch] for optstr in optstrs: opt, val = optstr.split('=', 1) sec, opt = opt.split('.', 1) if sec not in conf: raise error.SectionError(sec) if opt not in conf[sec]: raise error.OptionError(opt) meta = conf[sec].def_[opt] if meta.default is None: if 'type' in meta.cmd_kwargs: cast = meta.cmd_kwargs['type'] else: act = meta.cmd_kwargs.get('action') cast = bool if act in bool_actions else str else: cast = type(meta.default) if cast is bool and val.lower() in falsy: val = '' conf[sec][opt] = cast(val)
[ "Set", "options", "from", "a", "list", "of", "section", ".", "option", "=", "value", "string", "." ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/tools.py#L77-L105
[ "def", "set_conf_str", "(", "conf", ",", "optstrs", ")", ":", "falsy", "=", "[", "'0'", ",", "'no'", ",", "'n'", ",", "'off'", ",", "'false'", ",", "'f'", "]", "bool_actions", "=", "[", "'store_true'", ",", "'store_false'", ",", "internal", ".", "Switch", "]", "for", "optstr", "in", "optstrs", ":", "opt", ",", "val", "=", "optstr", ".", "split", "(", "'='", ",", "1", ")", "sec", ",", "opt", "=", "opt", ".", "split", "(", "'.'", ",", "1", ")", "if", "sec", "not", "in", "conf", ":", "raise", "error", ".", "SectionError", "(", "sec", ")", "if", "opt", "not", "in", "conf", "[", "sec", "]", ":", "raise", "error", ".", "OptionError", "(", "opt", ")", "meta", "=", "conf", "[", "sec", "]", ".", "def_", "[", "opt", "]", "if", "meta", ".", "default", "is", "None", ":", "if", "'type'", "in", "meta", ".", "cmd_kwargs", ":", "cast", "=", "meta", ".", "cmd_kwargs", "[", "'type'", "]", "else", ":", "act", "=", "meta", ".", "cmd_kwargs", ".", "get", "(", "'action'", ")", "cast", "=", "bool", "if", "act", "in", "bool_actions", "else", "str", "else", ":", "cast", "=", "type", "(", "meta", ".", "default", ")", "if", "cast", "is", "bool", "and", "val", ".", "lower", "(", ")", "in", "falsy", ":", "val", "=", "''", "conf", "[", "sec", "]", "[", "opt", "]", "=", "cast", "(", "val", ")" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
config_cmd_handler
Implement the behavior of a subcmd using config_conf_section Args: conf (:class:`~loam.manager.ConfigurationManager`): it should contain a section created with :func:`config_conf_section` function. config (str): name of the configuration section created with :func:`config_conf_section` function.
loam/tools.py
def config_cmd_handler(conf, config='config'): """Implement the behavior of a subcmd using config_conf_section Args: conf (:class:`~loam.manager.ConfigurationManager`): it should contain a section created with :func:`config_conf_section` function. config (str): name of the configuration section created with :func:`config_conf_section` function. """ if conf[config].create or conf[config].update: conf.create_config_(update=conf[config].update) if conf[config].create_local: conf.create_config_(index=-1, update=conf[config].update) if conf[config].edit: if not conf.config_files_[0].is_file(): conf.create_config_(update=conf[config].update) subprocess.call(shlex.split('{} {}'.format(conf[config].editor, conf.config_files_[0])))
def config_cmd_handler(conf, config='config'): """Implement the behavior of a subcmd using config_conf_section Args: conf (:class:`~loam.manager.ConfigurationManager`): it should contain a section created with :func:`config_conf_section` function. config (str): name of the configuration section created with :func:`config_conf_section` function. """ if conf[config].create or conf[config].update: conf.create_config_(update=conf[config].update) if conf[config].create_local: conf.create_config_(index=-1, update=conf[config].update) if conf[config].edit: if not conf.config_files_[0].is_file(): conf.create_config_(update=conf[config].update) subprocess.call(shlex.split('{} {}'.format(conf[config].editor, conf.config_files_[0])))
[ "Implement", "the", "behavior", "of", "a", "subcmd", "using", "config_conf_section" ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/tools.py#L108-L125
[ "def", "config_cmd_handler", "(", "conf", ",", "config", "=", "'config'", ")", ":", "if", "conf", "[", "config", "]", ".", "create", "or", "conf", "[", "config", "]", ".", "update", ":", "conf", ".", "create_config_", "(", "update", "=", "conf", "[", "config", "]", ".", "update", ")", "if", "conf", "[", "config", "]", ".", "create_local", ":", "conf", ".", "create_config_", "(", "index", "=", "-", "1", ",", "update", "=", "conf", "[", "config", "]", ".", "update", ")", "if", "conf", "[", "config", "]", ".", "edit", ":", "if", "not", "conf", ".", "config_files_", "[", "0", "]", ".", "is_file", "(", ")", ":", "conf", ".", "create_config_", "(", "update", "=", "conf", "[", "config", "]", ".", "update", ")", "subprocess", ".", "call", "(", "shlex", ".", "split", "(", "'{} {}'", ".", "format", "(", "conf", "[", "config", "]", ".", "editor", ",", "conf", ".", "config_files_", "[", "0", "]", ")", ")", ")" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
create_complete_files
Create completion files for bash and zsh. Args: climan (:class:`~loam.cli.CLIManager`): CLI manager. path (path-like): directory in which the config files should be created. It is created if it doesn't exist. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. zsh_sourceable (bool): if True, the generated file will contain an explicit call to ``compdef``, which means it can be sourced to activate CLI completion.
loam/tools.py
def create_complete_files(climan, path, cmd, *cmds, zsh_sourceable=False): """Create completion files for bash and zsh. Args: climan (:class:`~loam.cli.CLIManager`): CLI manager. path (path-like): directory in which the config files should be created. It is created if it doesn't exist. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. zsh_sourceable (bool): if True, the generated file will contain an explicit call to ``compdef``, which means it can be sourced to activate CLI completion. """ path = pathlib.Path(path) zsh_dir = path / 'zsh' if not zsh_dir.exists(): zsh_dir.mkdir(parents=True) zsh_file = zsh_dir / '_{}.sh'.format(cmd) bash_dir = path / 'bash' if not bash_dir.exists(): bash_dir.mkdir(parents=True) bash_file = bash_dir / '{}.sh'.format(cmd) climan.zsh_complete(zsh_file, cmd, *cmds, sourceable=zsh_sourceable) climan.bash_complete(bash_file, cmd, *cmds)
def create_complete_files(climan, path, cmd, *cmds, zsh_sourceable=False): """Create completion files for bash and zsh. Args: climan (:class:`~loam.cli.CLIManager`): CLI manager. path (path-like): directory in which the config files should be created. It is created if it doesn't exist. cmd (str): command name that should be completed. cmds (str): extra command names that should be completed. zsh_sourceable (bool): if True, the generated file will contain an explicit call to ``compdef``, which means it can be sourced to activate CLI completion. """ path = pathlib.Path(path) zsh_dir = path / 'zsh' if not zsh_dir.exists(): zsh_dir.mkdir(parents=True) zsh_file = zsh_dir / '_{}.sh'.format(cmd) bash_dir = path / 'bash' if not bash_dir.exists(): bash_dir.mkdir(parents=True) bash_file = bash_dir / '{}.sh'.format(cmd) climan.zsh_complete(zsh_file, cmd, *cmds, sourceable=zsh_sourceable) climan.bash_complete(bash_file, cmd, *cmds)
[ "Create", "completion", "files", "for", "bash", "and", "zsh", "." ]
amorison/loam
python
https://github.com/amorison/loam/blob/a566c943a75e068a4510099331a1ddfe5bbbdd94/loam/tools.py#L128-L151
[ "def", "create_complete_files", "(", "climan", ",", "path", ",", "cmd", ",", "*", "cmds", ",", "zsh_sourceable", "=", "False", ")", ":", "path", "=", "pathlib", ".", "Path", "(", "path", ")", "zsh_dir", "=", "path", "/", "'zsh'", "if", "not", "zsh_dir", ".", "exists", "(", ")", ":", "zsh_dir", ".", "mkdir", "(", "parents", "=", "True", ")", "zsh_file", "=", "zsh_dir", "/", "'_{}.sh'", ".", "format", "(", "cmd", ")", "bash_dir", "=", "path", "/", "'bash'", "if", "not", "bash_dir", ".", "exists", "(", ")", ":", "bash_dir", ".", "mkdir", "(", "parents", "=", "True", ")", "bash_file", "=", "bash_dir", "/", "'{}.sh'", ".", "format", "(", "cmd", ")", "climan", ".", "zsh_complete", "(", "zsh_file", ",", "cmd", ",", "*", "cmds", ",", "sourceable", "=", "zsh_sourceable", ")", "climan", ".", "bash_complete", "(", "bash_file", ",", "cmd", ",", "*", "cmds", ")" ]
a566c943a75e068a4510099331a1ddfe5bbbdd94
test
render_columns
Renders a list of columns. :param columns: A list of columns, where each column is a list of strings. :type columns: [[``str``]] :param write_borders: Whether to write the top and bottom borders. :type write_borders: ``bool`` :param column_colors: A list of coloring functions, one for each column. Optional. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered columns. :rtype: ``str``
src/lsi/utils/table.py
def render_columns(columns, write_borders=True, column_colors=None): """ Renders a list of columns. :param columns: A list of columns, where each column is a list of strings. :type columns: [[``str``]] :param write_borders: Whether to write the top and bottom borders. :type write_borders: ``bool`` :param column_colors: A list of coloring functions, one for each column. Optional. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered columns. :rtype: ``str`` """ if column_colors is not None and len(column_colors) != len(columns): raise ValueError('Wrong number of column colors') widths = [max(len(cell) for cell in column) for column in columns] max_column_length = max(len(column) for column in columns) result = '\n'.join(render_row(i, columns, widths, column_colors) for i in range(max_column_length)) if write_borders: border = '+%s+' % '|'.join('-' * (w + 2) for w in widths) return '%s\n%s\n%s' % (border, result, border) else: return result
def render_columns(columns, write_borders=True, column_colors=None): """ Renders a list of columns. :param columns: A list of columns, where each column is a list of strings. :type columns: [[``str``]] :param write_borders: Whether to write the top and bottom borders. :type write_borders: ``bool`` :param column_colors: A list of coloring functions, one for each column. Optional. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered columns. :rtype: ``str`` """ if column_colors is not None and len(column_colors) != len(columns): raise ValueError('Wrong number of column colors') widths = [max(len(cell) for cell in column) for column in columns] max_column_length = max(len(column) for column in columns) result = '\n'.join(render_row(i, columns, widths, column_colors) for i in range(max_column_length)) if write_borders: border = '+%s+' % '|'.join('-' * (w + 2) for w in widths) return '%s\n%s\n%s' % (border, result, border) else: return result
[ "Renders", "a", "list", "of", "columns", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/table.py#L28-L53
[ "def", "render_columns", "(", "columns", ",", "write_borders", "=", "True", ",", "column_colors", "=", "None", ")", ":", "if", "column_colors", "is", "not", "None", "and", "len", "(", "column_colors", ")", "!=", "len", "(", "columns", ")", ":", "raise", "ValueError", "(", "'Wrong number of column colors'", ")", "widths", "=", "[", "max", "(", "len", "(", "cell", ")", "for", "cell", "in", "column", ")", "for", "column", "in", "columns", "]", "max_column_length", "=", "max", "(", "len", "(", "column", ")", "for", "column", "in", "columns", ")", "result", "=", "'\\n'", ".", "join", "(", "render_row", "(", "i", ",", "columns", ",", "widths", ",", "column_colors", ")", "for", "i", "in", "range", "(", "max_column_length", ")", ")", "if", "write_borders", ":", "border", "=", "'+%s+'", "%", "'|'", ".", "join", "(", "'-'", "*", "(", "w", "+", "2", ")", "for", "w", "in", "widths", ")", "return", "'%s\\n%s\\n%s'", "%", "(", "border", ",", "result", ",", "border", ")", "else", ":", "return", "result" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
render_row
Render the `num`th row of each column in `columns`. :param num: Which row to render. :type num: ``int`` :param columns: The list of columns. :type columns: [[``str``]] :param widths: The widths of each column. :type widths: [``int``] :param column_colors: An optional list of coloring functions. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered row. :rtype: ``str``
src/lsi/utils/table.py
def render_row(num, columns, widths, column_colors=None): """ Render the `num`th row of each column in `columns`. :param num: Which row to render. :type num: ``int`` :param columns: The list of columns. :type columns: [[``str``]] :param widths: The widths of each column. :type widths: [``int``] :param column_colors: An optional list of coloring functions. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered row. :rtype: ``str`` """ row_str = '|' cell_strs = [] for i, column in enumerate(columns): try: cell = column[num] # We choose the number of spaces before we color the string, so # that the coloring codes don't affect the length. spaces = ' ' * (widths[i] - len(cell)) if column_colors is not None and column_colors[i] is not None: cell = column_colors[i](cell) cell_strs.append(' %s%s ' % (cell, spaces)) except IndexError: # If the index is out of range, just print an empty cell. cell_strs.append(' ' * (widths[i] + 2)) return '|%s|' % '|'.join(cell_strs)
def render_row(num, columns, widths, column_colors=None): """ Render the `num`th row of each column in `columns`. :param num: Which row to render. :type num: ``int`` :param columns: The list of columns. :type columns: [[``str``]] :param widths: The widths of each column. :type widths: [``int``] :param column_colors: An optional list of coloring functions. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered row. :rtype: ``str`` """ row_str = '|' cell_strs = [] for i, column in enumerate(columns): try: cell = column[num] # We choose the number of spaces before we color the string, so # that the coloring codes don't affect the length. spaces = ' ' * (widths[i] - len(cell)) if column_colors is not None and column_colors[i] is not None: cell = column_colors[i](cell) cell_strs.append(' %s%s ' % (cell, spaces)) except IndexError: # If the index is out of range, just print an empty cell. cell_strs.append(' ' * (widths[i] + 2)) return '|%s|' % '|'.join(cell_strs)
[ "Render", "the", "num", "th", "row", "of", "each", "column", "in", "columns", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/table.py#L55-L85
[ "def", "render_row", "(", "num", ",", "columns", ",", "widths", ",", "column_colors", "=", "None", ")", ":", "row_str", "=", "'|'", "cell_strs", "=", "[", "]", "for", "i", ",", "column", "in", "enumerate", "(", "columns", ")", ":", "try", ":", "cell", "=", "column", "[", "num", "]", "# We choose the number of spaces before we color the string, so", "# that the coloring codes don't affect the length.", "spaces", "=", "' '", "*", "(", "widths", "[", "i", "]", "-", "len", "(", "cell", ")", ")", "if", "column_colors", "is", "not", "None", "and", "column_colors", "[", "i", "]", "is", "not", "None", ":", "cell", "=", "column_colors", "[", "i", "]", "(", "cell", ")", "cell_strs", ".", "append", "(", "' %s%s '", "%", "(", "cell", ",", "spaces", ")", ")", "except", "IndexError", ":", "# If the index is out of range, just print an empty cell.", "cell_strs", ".", "append", "(", "' '", "*", "(", "widths", "[", "i", "]", "+", "2", ")", ")", "return", "'|%s|'", "%", "'|'", ".", "join", "(", "cell_strs", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
render_table
Renders a table. A table is a list of rows, each of which is a list of arbitrary objects. The `.str` method will be called on each element of the row. Jagged tables are ok; in this case, each row will be expanded to the maximum row length. :param table: A list of rows, as described above. :type table: [[``object``]] :param write_borders: Whether there should be a border on the top and bottom. Defaults to ``True``. :type write_borders: ``bool`` :param column_colors: An optional list of coloring *functions* to be applied to each cell in each column. If provided, the list's length must be equal to the maximum number of columns. ``None`` can be mixed in to this list so that a selection of columns can be colored. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered table. :rtype: ``str``
src/lsi/utils/table.py
def render_table(table, write_borders=True, column_colors=None): """ Renders a table. A table is a list of rows, each of which is a list of arbitrary objects. The `.str` method will be called on each element of the row. Jagged tables are ok; in this case, each row will be expanded to the maximum row length. :param table: A list of rows, as described above. :type table: [[``object``]] :param write_borders: Whether there should be a border on the top and bottom. Defaults to ``True``. :type write_borders: ``bool`` :param column_colors: An optional list of coloring *functions* to be applied to each cell in each column. If provided, the list's length must be equal to the maximum number of columns. ``None`` can be mixed in to this list so that a selection of columns can be colored. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered table. :rtype: ``str`` """ prepare_rows(table) columns = transpose_table(table) return render_columns(columns, write_borders, column_colors)
def render_table(table, write_borders=True, column_colors=None): """ Renders a table. A table is a list of rows, each of which is a list of arbitrary objects. The `.str` method will be called on each element of the row. Jagged tables are ok; in this case, each row will be expanded to the maximum row length. :param table: A list of rows, as described above. :type table: [[``object``]] :param write_borders: Whether there should be a border on the top and bottom. Defaults to ``True``. :type write_borders: ``bool`` :param column_colors: An optional list of coloring *functions* to be applied to each cell in each column. If provided, the list's length must be equal to the maximum number of columns. ``None`` can be mixed in to this list so that a selection of columns can be colored. :type column_colors: [``str`` -> ``str``] or ``NoneType`` :return: The rendered table. :rtype: ``str`` """ prepare_rows(table) columns = transpose_table(table) return render_columns(columns, write_borders, column_colors)
[ "Renders", "a", "table", ".", "A", "table", "is", "a", "list", "of", "rows", "each", "of", "which", "is", "a", "list", "of", "arbitrary", "objects", ".", "The", ".", "str", "method", "will", "be", "called", "on", "each", "element", "of", "the", "row", ".", "Jagged", "tables", "are", "ok", ";", "in", "this", "case", "each", "row", "will", "be", "expanded", "to", "the", "maximum", "row", "length", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/table.py#L87-L111
[ "def", "render_table", "(", "table", ",", "write_borders", "=", "True", ",", "column_colors", "=", "None", ")", ":", "prepare_rows", "(", "table", ")", "columns", "=", "transpose_table", "(", "table", ")", "return", "render_columns", "(", "columns", ",", "write_borders", ",", "column_colors", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
transpose_table
Transposes a table, turning rows into columns. :param table: A 2D string grid. :type table: [[``str``]] :return: The same table, with rows and columns flipped. :rtype: [[``str``]]
src/lsi/utils/table.py
def transpose_table(table): """ Transposes a table, turning rows into columns. :param table: A 2D string grid. :type table: [[``str``]] :return: The same table, with rows and columns flipped. :rtype: [[``str``]] """ if len(table) == 0: return table else: num_columns = len(table[0]) return [[row[i] for row in table] for i in range(num_columns)]
def transpose_table(table): """ Transposes a table, turning rows into columns. :param table: A 2D string grid. :type table: [[``str``]] :return: The same table, with rows and columns flipped. :rtype: [[``str``]] """ if len(table) == 0: return table else: num_columns = len(table[0]) return [[row[i] for row in table] for i in range(num_columns)]
[ "Transposes", "a", "table", "turning", "rows", "into", "columns", ".", ":", "param", "table", ":", "A", "2D", "string", "grid", ".", ":", "type", "table", ":", "[[", "str", "]]" ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/table.py#L113-L126
[ "def", "transpose_table", "(", "table", ")", ":", "if", "len", "(", "table", ")", "==", "0", ":", "return", "table", "else", ":", "num_columns", "=", "len", "(", "table", "[", "0", "]", ")", "return", "[", "[", "row", "[", "i", "]", "for", "row", "in", "table", "]", "for", "i", "in", "range", "(", "num_columns", ")", "]" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
prepare_rows
Prepare the rows so they're all strings, and all the same length. :param table: A 2D grid of anything. :type table: [[``object``]] :return: A table of strings, where every row is the same length. :rtype: [[``str``]]
src/lsi/utils/table.py
def prepare_rows(table): """ Prepare the rows so they're all strings, and all the same length. :param table: A 2D grid of anything. :type table: [[``object``]] :return: A table of strings, where every row is the same length. :rtype: [[``str``]] """ num_columns = max(len(row) for row in table) for row in table: while len(row) < num_columns: row.append('') for i in range(num_columns): row[i] = str(row[i]) if row[i] is not None else '' return table
def prepare_rows(table): """ Prepare the rows so they're all strings, and all the same length. :param table: A 2D grid of anything. :type table: [[``object``]] :return: A table of strings, where every row is the same length. :rtype: [[``str``]] """ num_columns = max(len(row) for row in table) for row in table: while len(row) < num_columns: row.append('') for i in range(num_columns): row[i] = str(row[i]) if row[i] is not None else '' return table
[ "Prepare", "the", "rows", "so", "they", "re", "all", "strings", "and", "all", "the", "same", "length", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/table.py#L128-L144
[ "def", "prepare_rows", "(", "table", ")", ":", "num_columns", "=", "max", "(", "len", "(", "row", ")", "for", "row", "in", "table", ")", "for", "row", "in", "table", ":", "while", "len", "(", "row", ")", "<", "num_columns", ":", "row", ".", "append", "(", "''", ")", "for", "i", "in", "range", "(", "num_columns", ")", ":", "row", "[", "i", "]", "=", "str", "(", "row", "[", "i", "]", ")", "if", "row", "[", "i", "]", "is", "not", "None", "else", "''", "return", "table" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
get_table_width
Gets the width of the table that would be printed. :rtype: ``int``
src/lsi/utils/table.py
def get_table_width(table): """ Gets the width of the table that would be printed. :rtype: ``int`` """ columns = transpose_table(prepare_rows(table)) widths = [max(len(cell) for cell in column) for column in columns] return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
def get_table_width(table): """ Gets the width of the table that would be printed. :rtype: ``int`` """ columns = transpose_table(prepare_rows(table)) widths = [max(len(cell) for cell in column) for column in columns] return len('+' + '|'.join('-' * (w + 2) for w in widths) + '+')
[ "Gets", "the", "width", "of", "the", "table", "that", "would", "be", "printed", ".", ":", "rtype", ":", "int" ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/table.py#L146-L153
[ "def", "get_table_width", "(", "table", ")", ":", "columns", "=", "transpose_table", "(", "prepare_rows", "(", "table", ")", ")", "widths", "=", "[", "max", "(", "len", "(", "cell", ")", "for", "cell", "in", "column", ")", "for", "column", "in", "columns", "]", "return", "len", "(", "'+'", "+", "'|'", ".", "join", "(", "'-'", "*", "(", "w", "+", "2", ")", "for", "w", "in", "widths", ")", "+", "'+'", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
color
Returns a function that colors a string with a number from 0 to 255.
src/lsi/utils/term.py
def color(number): """ Returns a function that colors a string with a number from 0 to 255. """ if supports_256(): template = "\033[38;5;{number}m{text}\033[0m" else: template = "\033[{number}m{text}\033[0m" def _color(text): if not all([sys.stdout.isatty(), sys.stderr.isatty()]): return text else: return template.format(number=number, text=text) return _color
def color(number): """ Returns a function that colors a string with a number from 0 to 255. """ if supports_256(): template = "\033[38;5;{number}m{text}\033[0m" else: template = "\033[{number}m{text}\033[0m" def _color(text): if not all([sys.stdout.isatty(), sys.stderr.isatty()]): return text else: return template.format(number=number, text=text) return _color
[ "Returns", "a", "function", "that", "colors", "a", "string", "with", "a", "number", "from", "0", "to", "255", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/term.py#L42-L55
[ "def", "color", "(", "number", ")", ":", "if", "supports_256", "(", ")", ":", "template", "=", "\"\\033[38;5;{number}m{text}\\033[0m\"", "else", ":", "template", "=", "\"\\033[{number}m{text}\\033[0m\"", "def", "_color", "(", "text", ")", ":", "if", "not", "all", "(", "[", "sys", ".", "stdout", ".", "isatty", "(", ")", ",", "sys", ".", "stderr", ".", "isatty", "(", ")", "]", ")", ":", "return", "text", "else", ":", "return", "template", ".", "format", "(", "number", "=", "number", ",", "text", "=", "text", ")", "return", "_color" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
get_color_hash
Hashes a string and returns a number between ``min`` and ``max``.
src/lsi/utils/term.py
def get_color_hash(string, _min=MIN_COLOR_BRIGHT, _max=MAX_COLOR_BRIGHT): """ Hashes a string and returns a number between ``min`` and ``max``. """ hash_num = int(hashlib.sha1(string.encode('utf-8')).hexdigest()[:6], 16) _range = _max - _min num_in_range = hash_num % _range return color(_min + num_in_range)
def get_color_hash(string, _min=MIN_COLOR_BRIGHT, _max=MAX_COLOR_BRIGHT): """ Hashes a string and returns a number between ``min`` and ``max``. """ hash_num = int(hashlib.sha1(string.encode('utf-8')).hexdigest()[:6], 16) _range = _max - _min num_in_range = hash_num % _range return color(_min + num_in_range)
[ "Hashes", "a", "string", "and", "returns", "a", "number", "between", "min", "and", "max", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/term.py#L76-L83
[ "def", "get_color_hash", "(", "string", ",", "_min", "=", "MIN_COLOR_BRIGHT", ",", "_max", "=", "MAX_COLOR_BRIGHT", ")", ":", "hash_num", "=", "int", "(", "hashlib", ".", "sha1", "(", "string", ".", "encode", "(", "'utf-8'", ")", ")", ".", "hexdigest", "(", ")", "[", ":", "6", "]", ",", "16", ")", "_range", "=", "_max", "-", "_min", "num_in_range", "=", "hash_num", "%", "_range", "return", "color", "(", "_min", "+", "num_in_range", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
random_color
Returns a random color between min and max.
src/lsi/utils/term.py
def random_color(_min=MIN_COLOR, _max=MAX_COLOR): """Returns a random color between min and max.""" return color(random.randint(_min, _max))
def random_color(_min=MIN_COLOR, _max=MAX_COLOR): """Returns a random color between min and max.""" return color(random.randint(_min, _max))
[ "Returns", "a", "random", "color", "between", "min", "and", "max", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/term.py#L86-L88
[ "def", "random_color", "(", "_min", "=", "MIN_COLOR", ",", "_max", "=", "MAX_COLOR", ")", ":", "return", "color", "(", "random", ".", "randint", "(", "_min", ",", "_max", ")", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
get_input
Reads stdin, exits with a message if interrupted, EOF, or a quit message. :return: The entered input. Converts to an integer if possible. :rtype: ``str`` or ``int``
src/lsi/utils/term.py
def get_input(prompt, default=None, exit_msg='bye!'): """ Reads stdin, exits with a message if interrupted, EOF, or a quit message. :return: The entered input. Converts to an integer if possible. :rtype: ``str`` or ``int`` """ try: response = six.moves.input(prompt) except (KeyboardInterrupt, EOFError): print() print(exit_msg) exit() try: return int(response) except ValueError: if response.strip() == "" and default is not None: return default else: return response
def get_input(prompt, default=None, exit_msg='bye!'): """ Reads stdin, exits with a message if interrupted, EOF, or a quit message. :return: The entered input. Converts to an integer if possible. :rtype: ``str`` or ``int`` """ try: response = six.moves.input(prompt) except (KeyboardInterrupt, EOFError): print() print(exit_msg) exit() try: return int(response) except ValueError: if response.strip() == "" and default is not None: return default else: return response
[ "Reads", "stdin", "exits", "with", "a", "message", "if", "interrupted", "EOF", "or", "a", "quit", "message", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/term.py#L102-L121
[ "def", "get_input", "(", "prompt", ",", "default", "=", "None", ",", "exit_msg", "=", "'bye!'", ")", ":", "try", ":", "response", "=", "six", ".", "moves", ".", "input", "(", "prompt", ")", "except", "(", "KeyboardInterrupt", ",", "EOFError", ")", ":", "print", "(", ")", "print", "(", "exit_msg", ")", "exit", "(", ")", "try", ":", "return", "int", "(", "response", ")", "except", "ValueError", ":", "if", "response", ".", "strip", "(", ")", "==", "\"\"", "and", "default", "is", "not", "None", ":", "return", "default", "else", ":", "return", "response" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
check_credentials
Verify basic http authentification
python/dna/apy/auth.py
def check_credentials(username, password): ''' Verify basic http authentification ''' user = models.User.objects( username=username, password=password ).first() return user or None
def check_credentials(username, password): ''' Verify basic http authentification ''' user = models.User.objects( username=username, password=password ).first() return user or None
[ "Verify", "basic", "http", "authentification" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/auth.py#L21-L27
[ "def", "check_credentials", "(", "username", ",", "password", ")", ":", "user", "=", "models", ".", "User", ".", "objects", "(", "username", "=", "username", ",", "password", "=", "password", ")", ".", "first", "(", ")", "return", "user", "or", "None" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
check_token
Verify http header token authentification
python/dna/apy/auth.py
def check_token(token): ''' Verify http header token authentification ''' user = models.User.objects(api_key=token).first() return user or None
def check_token(token): ''' Verify http header token authentification ''' user = models.User.objects(api_key=token).first() return user or None
[ "Verify", "http", "header", "token", "authentification" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/auth.py#L30-L33
[ "def", "check_token", "(", "token", ")", ":", "user", "=", "models", ".", "User", ".", "objects", "(", "api_key", "=", "token", ")", ".", "first", "(", ")", "return", "user", "or", "None" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
requires_basic_auth
Flask decorator protecting ressources using username/password scheme
python/dna/apy/auth.py
def requires_basic_auth(resource): ''' Flask decorator protecting ressources using username/password scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided username/password ''' auth = flask.request.authorization user = check_credentials(auth.username, auth.password) if not auth or user is None: log.warn('authentification failed', credentials=auth) return auth_failed() log.info('authentification succeeded', credentials=auth) flask.g.user = user return resource(*args, **kwargs) return decorated
def requires_basic_auth(resource): ''' Flask decorator protecting ressources using username/password scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided username/password ''' auth = flask.request.authorization user = check_credentials(auth.username, auth.password) if not auth or user is None: log.warn('authentification failed', credentials=auth) return auth_failed() log.info('authentification succeeded', credentials=auth) flask.g.user = user return resource(*args, **kwargs) return decorated
[ "Flask", "decorator", "protecting", "ressources", "using", "username", "/", "password", "scheme" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/auth.py#L44-L61
[ "def", "requires_basic_auth", "(", "resource", ")", ":", "@", "functools", ".", "wraps", "(", "resource", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "''' Check provided username/password '''", "auth", "=", "flask", ".", "request", ".", "authorization", "user", "=", "check_credentials", "(", "auth", ".", "username", ",", "auth", ".", "password", ")", "if", "not", "auth", "or", "user", "is", "None", ":", "log", ".", "warn", "(", "'authentification failed'", ",", "credentials", "=", "auth", ")", "return", "auth_failed", "(", ")", "log", ".", "info", "(", "'authentification succeeded'", ",", "credentials", "=", "auth", ")", "flask", ".", "g", ".", "user", "=", "user", "return", "resource", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decorated" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
requires_token_auth
Flask decorator protecting ressources using token scheme
python/dna/apy/auth.py
def requires_token_auth(resource): ''' Flask decorator protecting ressources using token scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided token ''' token = flask.request.headers.get('Authorization') user = check_token(token) if not token or user is None: log.warn('authentification failed', token=token) return auth_failed() flask.g.user = user log.info('authentification succeeded', token=token, user=flask.g.user) return resource(*args, **kwargs) return decorated
def requires_token_auth(resource): ''' Flask decorator protecting ressources using token scheme ''' @functools.wraps(resource) def decorated(*args, **kwargs): ''' Check provided token ''' token = flask.request.headers.get('Authorization') user = check_token(token) if not token or user is None: log.warn('authentification failed', token=token) return auth_failed() flask.g.user = user log.info('authentification succeeded', token=token, user=flask.g.user) return resource(*args, **kwargs) return decorated
[ "Flask", "decorator", "protecting", "ressources", "using", "token", "scheme" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/auth.py#L64-L81
[ "def", "requires_token_auth", "(", "resource", ")", ":", "@", "functools", ".", "wraps", "(", "resource", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "''' Check provided token '''", "token", "=", "flask", ".", "request", ".", "headers", ".", "get", "(", "'Authorization'", ")", "user", "=", "check_token", "(", "token", ")", "if", "not", "token", "or", "user", "is", "None", ":", "log", ".", "warn", "(", "'authentification failed'", ",", "token", "=", "token", ")", "return", "auth_failed", "(", ")", "flask", ".", "g", ".", "user", "=", "user", "log", ".", "info", "(", "'authentification succeeded'", ",", "token", "=", "token", ",", "user", "=", "flask", ".", "g", ".", "user", ")", "return", "resource", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "decorated" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
is_running
`pgrep` returns an error code if no process was found
python/dna/utils.py
def is_running(process): ''' `pgrep` returns an error code if no process was found ''' try: pgrep = sh.Command('/usr/bin/pgrep') pgrep(process) flag = True except sh.ErrorReturnCode_1: flag = False return flag
def is_running(process): ''' `pgrep` returns an error code if no process was found ''' try: pgrep = sh.Command('/usr/bin/pgrep') pgrep(process) flag = True except sh.ErrorReturnCode_1: flag = False return flag
[ "pgrep", "returns", "an", "error", "code", "if", "no", "process", "was", "found" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/utils.py#L35-L43
[ "def", "is_running", "(", "process", ")", ":", "try", ":", "pgrep", "=", "sh", ".", "Command", "(", "'/usr/bin/pgrep'", ")", "pgrep", "(", "process", ")", "flag", "=", "True", "except", "sh", ".", "ErrorReturnCode_1", ":", "flag", "=", "False", "return", "flag" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
dynamic_import
Take a string and return the corresponding module
python/dna/utils.py
def dynamic_import(mod_path, obj_name=None): ''' Take a string and return the corresponding module ''' try: module = __import__(mod_path, fromlist=['whatever']) except ImportError, error: raise errors.DynamicImportFailed( module='.'.join([mod_path, obj_name]), reason=error) # Make sure we're up-to-date reload(module) if obj_name is None: obj = module elif hasattr(module, obj_name): obj = getattr(module, obj_name) else: raise errors.DynamicImportFailed( module='.'.join([mod_path, obj_name]), reason='module {} has no attribute {}'. format(module.__name__, obj_name)) return None return obj
def dynamic_import(mod_path, obj_name=None): ''' Take a string and return the corresponding module ''' try: module = __import__(mod_path, fromlist=['whatever']) except ImportError, error: raise errors.DynamicImportFailed( module='.'.join([mod_path, obj_name]), reason=error) # Make sure we're up-to-date reload(module) if obj_name is None: obj = module elif hasattr(module, obj_name): obj = getattr(module, obj_name) else: raise errors.DynamicImportFailed( module='.'.join([mod_path, obj_name]), reason='module {} has no attribute {}'. format(module.__name__, obj_name)) return None return obj
[ "Take", "a", "string", "and", "return", "the", "corresponding", "module" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/utils.py#L72-L93
[ "def", "dynamic_import", "(", "mod_path", ",", "obj_name", "=", "None", ")", ":", "try", ":", "module", "=", "__import__", "(", "mod_path", ",", "fromlist", "=", "[", "'whatever'", "]", ")", "except", "ImportError", ",", "error", ":", "raise", "errors", ".", "DynamicImportFailed", "(", "module", "=", "'.'", ".", "join", "(", "[", "mod_path", ",", "obj_name", "]", ")", ",", "reason", "=", "error", ")", "# Make sure we're up-to-date", "reload", "(", "module", ")", "if", "obj_name", "is", "None", ":", "obj", "=", "module", "elif", "hasattr", "(", "module", ",", "obj_name", ")", ":", "obj", "=", "getattr", "(", "module", ",", "obj_name", ")", "else", ":", "raise", "errors", ".", "DynamicImportFailed", "(", "module", "=", "'.'", ".", "join", "(", "[", "mod_path", ",", "obj_name", "]", ")", ",", "reason", "=", "'module {} has no attribute {}'", ".", "format", "(", "module", ".", "__name__", ",", "obj_name", ")", ")", "return", "None", "return", "obj" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
self_ip
Utility for logbook information injection
python/dna/utils.py
def self_ip(public=False): ''' Utility for logbook information injection ''' try: if public: data = str(urlopen('http://checkip.dyndns.com/').read()) ip_addr = re.compile( r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) else: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(('google.com', 0)) ip_addr = sock.getsockname()[0] except Exception, error: print('Online test failed : {}'.format(error)) raise return ip_addr
def self_ip(public=False): ''' Utility for logbook information injection ''' try: if public: data = str(urlopen('http://checkip.dyndns.com/').read()) ip_addr = re.compile( r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) else: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.connect(('google.com', 0)) ip_addr = sock.getsockname()[0] except Exception, error: print('Online test failed : {}'.format(error)) raise return ip_addr
[ "Utility", "for", "logbook", "information", "injection" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/utils.py#L101-L115
[ "def", "self_ip", "(", "public", "=", "False", ")", ":", "try", ":", "if", "public", ":", "data", "=", "str", "(", "urlopen", "(", "'http://checkip.dyndns.com/'", ")", ".", "read", "(", ")", ")", "ip_addr", "=", "re", ".", "compile", "(", "r'Address: (\\d+\\.\\d+\\.\\d+\\.\\d+)'", ")", ".", "search", "(", "data", ")", ".", "group", "(", "1", ")", "else", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "sock", ".", "connect", "(", "(", "'google.com'", ",", "0", ")", ")", "ip_addr", "=", "sock", ".", "getsockname", "(", ")", "[", "0", "]", "except", "Exception", ",", "error", ":", "print", "(", "'Online test failed : {}'", ".", "format", "(", "error", ")", ")", "raise", "return", "ip_addr" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
ApiClient.request
Makes the HTTP request using RESTClient.
probe/api_client.py
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_params, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PUT": return self.rest_client.PUT(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers) else: raise ValueError( "http method must be `GET`, `HEAD`," " `POST`, `PATCH`, `PUT` or `DELETE`." )
def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): """ Makes the HTTP request using RESTClient. """ if method == "GET": return self.rest_client.GET(url, query_params=query_params, headers=headers) elif method == "HEAD": return self.rest_client.HEAD(url, query_params=query_params, headers=headers) elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PUT": return self.rest_client.PUT(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "PATCH": return self.rest_client.PATCH(url, query_params=query_params, headers=headers, post_params=post_params, body=body) elif method == "DELETE": return self.rest_client.DELETE(url, query_params=query_params, headers=headers) else: raise ValueError( "http method must be `GET`, `HEAD`," " `POST`, `PATCH`, `PUT` or `DELETE`." )
[ "Makes", "the", "HTTP", "request", "using", "RESTClient", "." ]
loanzen/probe-py
python
https://github.com/loanzen/probe-py/blob/b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5/probe/api_client.py#L334-L379
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "query_params", "=", "None", ",", "headers", "=", "None", ",", "post_params", "=", "None", ",", "body", "=", "None", ")", ":", "if", "method", "==", "\"GET\"", ":", "return", "self", ".", "rest_client", ".", "GET", "(", "url", ",", "query_params", "=", "query_params", ",", "headers", "=", "headers", ")", "elif", "method", "==", "\"HEAD\"", ":", "return", "self", ".", "rest_client", ".", "HEAD", "(", "url", ",", "query_params", "=", "query_params", ",", "headers", "=", "headers", ")", "elif", "method", "==", "\"OPTIONS\"", ":", "return", "self", ".", "rest_client", ".", "OPTIONS", "(", "url", ",", "query_params", "=", "query_params", ",", "headers", "=", "headers", ",", "post_params", "=", "post_params", ",", "body", "=", "body", ")", "elif", "method", "==", "\"POST\"", ":", "return", "self", ".", "rest_client", ".", "POST", "(", "url", ",", "query_params", "=", "query_params", ",", "headers", "=", "headers", ",", "post_params", "=", "post_params", ",", "body", "=", "body", ")", "elif", "method", "==", "\"PUT\"", ":", "return", "self", ".", "rest_client", ".", "PUT", "(", "url", ",", "query_params", "=", "query_params", ",", "headers", "=", "headers", ",", "post_params", "=", "post_params", ",", "body", "=", "body", ")", "elif", "method", "==", "\"PATCH\"", ":", "return", "self", ".", "rest_client", ".", "PATCH", "(", "url", ",", "query_params", "=", "query_params", ",", "headers", "=", "headers", ",", "post_params", "=", "post_params", ",", "body", "=", "body", ")", "elif", "method", "==", "\"DELETE\"", ":", "return", "self", ".", "rest_client", ".", "DELETE", "(", "url", ",", "query_params", "=", "query_params", ",", "headers", "=", "headers", ")", "else", ":", "raise", "ValueError", "(", "\"http method must be `GET`, `HEAD`,\"", "\" `POST`, `PATCH`, `PUT` or `DELETE`.\"", ")" ]
b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5
test
ApiClient.prepare_post_parameters
Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files.
probe/api_client.py
def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = {} if post_params: params.update(post_params) if files: for k, v in iteritems(files): if not v: continue with open(v, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() mimetype = mimetypes.\ guess_type(filename)[0] or 'application/octet-stream' params[k] = tuple([filename, filedata, mimetype]) return params
def prepare_post_parameters(self, post_params=None, files=None): """ Builds form parameters. :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = {} if post_params: params.update(post_params) if files: for k, v in iteritems(files): if not v: continue with open(v, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() mimetype = mimetypes.\ guess_type(filename)[0] or 'application/octet-stream' params[k] = tuple([filename, filedata, mimetype]) return params
[ "Builds", "form", "parameters", "." ]
loanzen/probe-py
python
https://github.com/loanzen/probe-py/blob/b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5/probe/api_client.py#L381-L406
[ "def", "prepare_post_parameters", "(", "self", ",", "post_params", "=", "None", ",", "files", "=", "None", ")", ":", "params", "=", "{", "}", "if", "post_params", ":", "params", ".", "update", "(", "post_params", ")", "if", "files", ":", "for", "k", ",", "v", "in", "iteritems", "(", "files", ")", ":", "if", "not", "v", ":", "continue", "with", "open", "(", "v", ",", "'rb'", ")", "as", "f", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "f", ".", "name", ")", "filedata", "=", "f", ".", "read", "(", ")", "mimetype", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "0", "]", "or", "'application/octet-stream'", "params", "[", "k", "]", "=", "tuple", "(", "[", "filename", ",", "filedata", ",", "mimetype", "]", ")", "return", "params" ]
b5dbb0dba26c9b451e9bf1dec9e1aaa7f42d75a5
test
App.serve
Configure from cli and run the server
python/dna/apy/core.py
def serve(self, app_docopt=DEFAULT_DOC, description=''): ''' Configure from cli and run the server ''' exit_status = 0 if isinstance(app_docopt, str): args = docopt(app_docopt, version=description) elif isinstance(app_docopt, dict): args = app_docopt else: raise ValueError('unknown configuration object ({})' .format(type(app_docopt))) log_level = args.get('--log', 'debug') is_debug = args.get('--debug', False) # TODO More serious default log_output = 'stdout' if is_debug else 'apy.log' safe_bind = args.get('--bind', '127.0.0.1') safe_port = int(args.get('--port', 5000)) log_setup = dna.logging.setup(level=log_level, output=log_output) with log_setup.applicationbound(): try: log.info('server ready', version=description, log=log_level, debug=is_debug, bind='{}:{}'.format(safe_bind, safe_port)) self.app.run(host=safe_bind, port=safe_port, debug=is_debug) except Exception as error: if is_debug: raise log.error('{}: {}'.format(type(error).__name__, str(error))) exit_status = 1 finally: log.info('session ended with status {}'.format(exit_status)) return exit_status
def serve(self, app_docopt=DEFAULT_DOC, description=''): ''' Configure from cli and run the server ''' exit_status = 0 if isinstance(app_docopt, str): args = docopt(app_docopt, version=description) elif isinstance(app_docopt, dict): args = app_docopt else: raise ValueError('unknown configuration object ({})' .format(type(app_docopt))) log_level = args.get('--log', 'debug') is_debug = args.get('--debug', False) # TODO More serious default log_output = 'stdout' if is_debug else 'apy.log' safe_bind = args.get('--bind', '127.0.0.1') safe_port = int(args.get('--port', 5000)) log_setup = dna.logging.setup(level=log_level, output=log_output) with log_setup.applicationbound(): try: log.info('server ready', version=description, log=log_level, debug=is_debug, bind='{}:{}'.format(safe_bind, safe_port)) self.app.run(host=safe_bind, port=safe_port, debug=is_debug) except Exception as error: if is_debug: raise log.error('{}: {}'.format(type(error).__name__, str(error))) exit_status = 1 finally: log.info('session ended with status {}'.format(exit_status)) return exit_status
[ "Configure", "from", "cli", "and", "run", "the", "server" ]
hivetech/dna
python
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/apy/core.py#L78-L118
[ "def", "serve", "(", "self", ",", "app_docopt", "=", "DEFAULT_DOC", ",", "description", "=", "''", ")", ":", "exit_status", "=", "0", "if", "isinstance", "(", "app_docopt", ",", "str", ")", ":", "args", "=", "docopt", "(", "app_docopt", ",", "version", "=", "description", ")", "elif", "isinstance", "(", "app_docopt", ",", "dict", ")", ":", "args", "=", "app_docopt", "else", ":", "raise", "ValueError", "(", "'unknown configuration object ({})'", ".", "format", "(", "type", "(", "app_docopt", ")", ")", ")", "log_level", "=", "args", ".", "get", "(", "'--log'", ",", "'debug'", ")", "is_debug", "=", "args", ".", "get", "(", "'--debug'", ",", "False", ")", "# TODO More serious default", "log_output", "=", "'stdout'", "if", "is_debug", "else", "'apy.log'", "safe_bind", "=", "args", ".", "get", "(", "'--bind'", ",", "'127.0.0.1'", ")", "safe_port", "=", "int", "(", "args", ".", "get", "(", "'--port'", ",", "5000", ")", ")", "log_setup", "=", "dna", ".", "logging", ".", "setup", "(", "level", "=", "log_level", ",", "output", "=", "log_output", ")", "with", "log_setup", ".", "applicationbound", "(", ")", ":", "try", ":", "log", ".", "info", "(", "'server ready'", ",", "version", "=", "description", ",", "log", "=", "log_level", ",", "debug", "=", "is_debug", ",", "bind", "=", "'{}:{}'", ".", "format", "(", "safe_bind", ",", "safe_port", ")", ")", "self", ".", "app", ".", "run", "(", "host", "=", "safe_bind", ",", "port", "=", "safe_port", ",", "debug", "=", "is_debug", ")", "except", "Exception", "as", "error", ":", "if", "is_debug", ":", "raise", "log", ".", "error", "(", "'{}: {}'", ".", "format", "(", "type", "(", "error", ")", ".", "__name__", ",", "str", "(", "error", ")", ")", ")", "exit_status", "=", "1", "finally", ":", "log", ".", "info", "(", "'session ended with status {}'", ".", "format", "(", "exit_status", ")", ")", "return", "exit_status" ]
50ad00031be29765b2576fa407d35a36e0608de9
test
WYSIWYGWidget.render
Include a hidden input to stored the serialized upload value.
secure_input/widgets.py
def render(self, name, value, attrs=None): """Include a hidden input to stored the serialized upload value.""" context = attrs or {} context.update({'name': name, 'value': value, }) return render_to_string(self.template_name, context)
def render(self, name, value, attrs=None): """Include a hidden input to stored the serialized upload value.""" context = attrs or {} context.update({'name': name, 'value': value, }) return render_to_string(self.template_name, context)
[ "Include", "a", "hidden", "input", "to", "stored", "the", "serialized", "upload", "value", "." ]
rochapps/django-secure-input
python
https://github.com/rochapps/django-secure-input/blob/6da714475613870f2891b2ccf3317f55b3e81107/secure_input/widgets.py#L11-L15
[ "def", "render", "(", "self", ",", "name", ",", "value", ",", "attrs", "=", "None", ")", ":", "context", "=", "attrs", "or", "{", "}", "context", ".", "update", "(", "{", "'name'", ":", "name", ",", "'value'", ":", "value", ",", "}", ")", "return", "render_to_string", "(", "self", ".", "template_name", ",", "context", ")" ]
6da714475613870f2891b2ccf3317f55b3e81107
test
stream_command
Starts `command` in a subprocess. Prints every line the command prints, prefaced with `description`. :param command: The bash command to run. Must use fully-qualified paths. :type command: ``str`` :param formatter: An optional formatting function to apply to each line. :type formatter: ``function`` or ``NoneType`` :param write_stdin: An optional string to write to the process' stdin. :type write_stdin: ``str`` or ``NoneType`` :param ignore_empty: If true, empty or whitespace-only lines will be skipped. :type ignore_empty: ``bool``
src/lsi/utils/stream.py
def stream_command(command, formatter=None, write_stdin=None, ignore_empty=False): """ Starts `command` in a subprocess. Prints every line the command prints, prefaced with `description`. :param command: The bash command to run. Must use fully-qualified paths. :type command: ``str`` :param formatter: An optional formatting function to apply to each line. :type formatter: ``function`` or ``NoneType`` :param write_stdin: An optional string to write to the process' stdin. :type write_stdin: ``str`` or ``NoneType`` :param ignore_empty: If true, empty or whitespace-only lines will be skipped. :type ignore_empty: ``bool`` """ command_list = shlex.split(command) try: proc = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) except Exception as e: raise IOError('Encountered error: {0} when running command {1}' .format(e.message, ' '.join(command_list))) if write_stdin is not None: proc.stdin.write(write_stdin) proc.stdin.flush() while proc.poll() is None: try: line = proc.stdout.readline() except KeyboardInterrupt: sys.exit('Keyboard interrupt while running {}'.format(command)) if len(line.strip()) == 0 and ignore_empty is True: continue elif 'killed by signal 1' in decode(line).lower(): continue elif 'to the list of known hosts' in decode(line).lower(): continue if formatter is not None: line = formatter(line) sys.stdout.write(line) result = proc.poll() return result
def stream_command(command, formatter=None, write_stdin=None, ignore_empty=False): """ Starts `command` in a subprocess. Prints every line the command prints, prefaced with `description`. :param command: The bash command to run. Must use fully-qualified paths. :type command: ``str`` :param formatter: An optional formatting function to apply to each line. :type formatter: ``function`` or ``NoneType`` :param write_stdin: An optional string to write to the process' stdin. :type write_stdin: ``str`` or ``NoneType`` :param ignore_empty: If true, empty or whitespace-only lines will be skipped. :type ignore_empty: ``bool`` """ command_list = shlex.split(command) try: proc = subprocess.Popen(command_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE) except Exception as e: raise IOError('Encountered error: {0} when running command {1}' .format(e.message, ' '.join(command_list))) if write_stdin is not None: proc.stdin.write(write_stdin) proc.stdin.flush() while proc.poll() is None: try: line = proc.stdout.readline() except KeyboardInterrupt: sys.exit('Keyboard interrupt while running {}'.format(command)) if len(line.strip()) == 0 and ignore_empty is True: continue elif 'killed by signal 1' in decode(line).lower(): continue elif 'to the list of known hosts' in decode(line).lower(): continue if formatter is not None: line = formatter(line) sys.stdout.write(line) result = proc.poll() return result
[ "Starts", "command", "in", "a", "subprocess", ".", "Prints", "every", "line", "the", "command", "prints", "prefaced", "with", "description", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/stream.py#L43-L83
[ "def", "stream_command", "(", "command", ",", "formatter", "=", "None", ",", "write_stdin", "=", "None", ",", "ignore_empty", "=", "False", ")", ":", "command_list", "=", "shlex", ".", "split", "(", "command", ")", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "command_list", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "stdin", "=", "subprocess", ".", "PIPE", ")", "except", "Exception", "as", "e", ":", "raise", "IOError", "(", "'Encountered error: {0} when running command {1}'", ".", "format", "(", "e", ".", "message", ",", "' '", ".", "join", "(", "command_list", ")", ")", ")", "if", "write_stdin", "is", "not", "None", ":", "proc", ".", "stdin", ".", "write", "(", "write_stdin", ")", "proc", ".", "stdin", ".", "flush", "(", ")", "while", "proc", ".", "poll", "(", ")", "is", "None", ":", "try", ":", "line", "=", "proc", ".", "stdout", ".", "readline", "(", ")", "except", "KeyboardInterrupt", ":", "sys", ".", "exit", "(", "'Keyboard interrupt while running {}'", ".", "format", "(", "command", ")", ")", "if", "len", "(", "line", ".", "strip", "(", ")", ")", "==", "0", "and", "ignore_empty", "is", "True", ":", "continue", "elif", "'killed by signal 1'", "in", "decode", "(", "line", ")", ".", "lower", "(", ")", ":", "continue", "elif", "'to the list of known hosts'", "in", "decode", "(", "line", ")", ".", "lower", "(", ")", ":", "continue", "if", "formatter", "is", "not", "None", ":", "line", "=", "formatter", "(", "line", ")", "sys", ".", "stdout", ".", "write", "(", "line", ")", "result", "=", "proc", ".", "poll", "(", ")", "return", "result" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
stream_command_dicts
Takes a list of dictionaries with keys corresponding to ``stream_command`` arguments, and runs all concurrently. :param commands: A list of dictionaries, the keys of which should line up with the arguments to ``stream_command`` function. :type commands: ``list`` of ``dict`` :param parallel: If true, commands will be run in parallel. :type parallel: ``bool``
src/lsi/utils/stream.py
def stream_command_dicts(commands, parallel=False): """ Takes a list of dictionaries with keys corresponding to ``stream_command`` arguments, and runs all concurrently. :param commands: A list of dictionaries, the keys of which should line up with the arguments to ``stream_command`` function. :type commands: ``list`` of ``dict`` :param parallel: If true, commands will be run in parallel. :type parallel: ``bool`` """ if parallel is True: threads = [] for command in commands: target = lambda: stream_command(**command) thread = Thread(target=target) thread.start() threads.append(thread) for t in threads: t.join() else: for command in commands: stream_command(**command)
def stream_command_dicts(commands, parallel=False): """ Takes a list of dictionaries with keys corresponding to ``stream_command`` arguments, and runs all concurrently. :param commands: A list of dictionaries, the keys of which should line up with the arguments to ``stream_command`` function. :type commands: ``list`` of ``dict`` :param parallel: If true, commands will be run in parallel. :type parallel: ``bool`` """ if parallel is True: threads = [] for command in commands: target = lambda: stream_command(**command) thread = Thread(target=target) thread.start() threads.append(thread) for t in threads: t.join() else: for command in commands: stream_command(**command)
[ "Takes", "a", "list", "of", "dictionaries", "with", "keys", "corresponding", "to", "stream_command", "arguments", "and", "runs", "all", "concurrently", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/stream.py#L86-L108
[ "def", "stream_command_dicts", "(", "commands", ",", "parallel", "=", "False", ")", ":", "if", "parallel", "is", "True", ":", "threads", "=", "[", "]", "for", "command", "in", "commands", ":", "target", "=", "lambda", ":", "stream_command", "(", "*", "*", "command", ")", "thread", "=", "Thread", "(", "target", "=", "target", ")", "thread", ".", "start", "(", ")", "threads", ".", "append", "(", "thread", ")", "for", "t", "in", "threads", ":", "t", ".", "join", "(", ")", "else", ":", "for", "command", "in", "commands", ":", "stream_command", "(", "*", "*", "command", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
stream_commands
Runs multiple commands, optionally in parallel. Each command should be a dictionary with a 'command' key and optionally 'description' and 'write_stdin' keys.
src/lsi/utils/stream.py
def stream_commands(commands, hash_colors=True, parallel=False): """ Runs multiple commands, optionally in parallel. Each command should be a dictionary with a 'command' key and optionally 'description' and 'write_stdin' keys. """ def _get_color(string): if hash_colors is True: return get_color_hash(string) else: return DEFAULT_COLOR fixed_commands = [] for command in commands: cmd_text = command['command'] description = command.get('description') color = _get_color(description or '') write_stdin = command.get('write_stdin') description = color(description) if color is not None else description formatter = _format_with_description(description) fixed_commands.append({ 'command': cmd_text, 'formatter': formatter, 'write_stdin': write_stdin, 'ignore_empty': True }) stream_command_dicts(fixed_commands, parallel=parallel)
def stream_commands(commands, hash_colors=True, parallel=False): """ Runs multiple commands, optionally in parallel. Each command should be a dictionary with a 'command' key and optionally 'description' and 'write_stdin' keys. """ def _get_color(string): if hash_colors is True: return get_color_hash(string) else: return DEFAULT_COLOR fixed_commands = [] for command in commands: cmd_text = command['command'] description = command.get('description') color = _get_color(description or '') write_stdin = command.get('write_stdin') description = color(description) if color is not None else description formatter = _format_with_description(description) fixed_commands.append({ 'command': cmd_text, 'formatter': formatter, 'write_stdin': write_stdin, 'ignore_empty': True }) stream_command_dicts(fixed_commands, parallel=parallel)
[ "Runs", "multiple", "commands", "optionally", "in", "parallel", ".", "Each", "command", "should", "be", "a", "dictionary", "with", "a", "command", "key", "and", "optionally", "description", "and", "write_stdin", "keys", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/utils/stream.py#L117-L142
[ "def", "stream_commands", "(", "commands", ",", "hash_colors", "=", "True", ",", "parallel", "=", "False", ")", ":", "def", "_get_color", "(", "string", ")", ":", "if", "hash_colors", "is", "True", ":", "return", "get_color_hash", "(", "string", ")", "else", ":", "return", "DEFAULT_COLOR", "fixed_commands", "=", "[", "]", "for", "command", "in", "commands", ":", "cmd_text", "=", "command", "[", "'command'", "]", "description", "=", "command", ".", "get", "(", "'description'", ")", "color", "=", "_get_color", "(", "description", "or", "''", ")", "write_stdin", "=", "command", ".", "get", "(", "'write_stdin'", ")", "description", "=", "color", "(", "description", ")", "if", "color", "is", "not", "None", "else", "description", "formatter", "=", "_format_with_description", "(", "description", ")", "fixed_commands", ".", "append", "(", "{", "'command'", ":", "cmd_text", ",", "'formatter'", ":", "formatter", ",", "'write_stdin'", ":", "write_stdin", ",", "'ignore_empty'", ":", "True", "}", ")", "stream_command_dicts", "(", "fixed_commands", ",", "parallel", "=", "parallel", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
networkdays
Return the net work days according to RH's calendar.
rhcalendar/__init__.py
def networkdays(from_date, to_date, locale='en-US'): """ Return the net work days according to RH's calendar. """ holidays = locales[locale] return workdays.networkdays(from_date, to_date, holidays)
def networkdays(from_date, to_date, locale='en-US'): """ Return the net work days according to RH's calendar. """ holidays = locales[locale] return workdays.networkdays(from_date, to_date, holidays)
[ "Return", "the", "net", "work", "days", "according", "to", "RH", "s", "calendar", "." ]
ktdreyer/rhcalendar
python
https://github.com/ktdreyer/rhcalendar/blob/fee4bd4b0a4fe42bea8b876e2e871e42c362c40b/rhcalendar/__init__.py#L7-L10
[ "def", "networkdays", "(", "from_date", ",", "to_date", ",", "locale", "=", "'en-US'", ")", ":", "holidays", "=", "locales", "[", "locale", "]", "return", "workdays", ".", "networkdays", "(", "from_date", ",", "to_date", ",", "holidays", ")" ]
fee4bd4b0a4fe42bea8b876e2e871e42c362c40b
test
merge
Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``other`` is merged into ``dicto``. :param dicto: dict onto which the merge is executed :param other: dict that is going to merged into dicto :return: None
dicto/api.py
def merge(dicto, other): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``other`` is merged into ``dicto``. :param dicto: dict onto which the merge is executed :param other: dict that is going to merged into dicto :return: None """ if not isinstance(dicto, Dicto): dicto = Dicto(dicto) if not isinstance(other, Dicto): other = Dicto(other) for k, v in other.__dict__.items(): if k in dicto and isinstance(dicto[k], Dicto) and isinstance(other[k], Dicto): dicto[k] = merge(dicto[k], other[k]) else: dicto[k] = other[k] return dicto
def merge(dicto, other): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``other`` is merged into ``dicto``. :param dicto: dict onto which the merge is executed :param other: dict that is going to merged into dicto :return: None """ if not isinstance(dicto, Dicto): dicto = Dicto(dicto) if not isinstance(other, Dicto): other = Dicto(other) for k, v in other.__dict__.items(): if k in dicto and isinstance(dicto[k], Dicto) and isinstance(other[k], Dicto): dicto[k] = merge(dicto[k], other[k]) else: dicto[k] = other[k] return dicto
[ "Recursive", "dict", "merge", ".", "Inspired", "by", ":", "meth", ":", "dict", ".", "update", "()", "instead", "of", "updating", "only", "top", "-", "level", "keys", "dict_merge", "recurses", "down", "into", "dicts", "nested", "to", "an", "arbitrary", "depth", "updating", "keys", ".", "The", "other", "is", "merged", "into", "dicto", ".", ":", "param", "dicto", ":", "dict", "onto", "which", "the", "merge", "is", "executed", ":", "param", "other", ":", "dict", "that", "is", "going", "to", "merged", "into", "dicto", ":", "return", ":", "None" ]
cgarciae/dicto
python
https://github.com/cgarciae/dicto/blob/fee67e1abcf2538455fee62414c34eb2354bdafa/dicto/api.py#L114-L135
[ "def", "merge", "(", "dicto", ",", "other", ")", ":", "if", "not", "isinstance", "(", "dicto", ",", "Dicto", ")", ":", "dicto", "=", "Dicto", "(", "dicto", ")", "if", "not", "isinstance", "(", "other", ",", "Dicto", ")", ":", "other", "=", "Dicto", "(", "other", ")", "for", "k", ",", "v", "in", "other", ".", "__dict__", ".", "items", "(", ")", ":", "if", "k", "in", "dicto", "and", "isinstance", "(", "dicto", "[", "k", "]", ",", "Dicto", ")", "and", "isinstance", "(", "other", "[", "k", "]", ",", "Dicto", ")", ":", "dicto", "[", "k", "]", "=", "merge", "(", "dicto", "[", "k", "]", ",", "other", "[", "k", "]", ")", "else", ":", "dicto", "[", "k", "]", "=", "other", "[", "k", "]", "return", "dicto" ]
fee67e1abcf2538455fee62414c34eb2354bdafa
test
_run_ssh
Lets the user choose which instance to SSH into. :param entries: The list of host entries. :type entries: [:py:class:`HostEntry`] :param username: The SSH username to use. Defaults to current user. :type username: ``str`` or ``NoneType`` :param idfile: The identity file to use. Optional. :type idfile: ``str`` or ``NoneType`` :param no_prompt: Whether to disable confirmation for SSH command. :type no_prompt: ``bool`` :param command: SSH command to run on matching instances. :type command: ``str`` or ``NoneType`` :param show: Instance attributes to show in addition to defaults. :type show: ``NoneType`` or ``list`` of ``str`` :param only: If not ``None``, will *only* show these attributes. :type only: ``NoneType`` or ``list`` of ``str`` :param sort_by: What to sort columns by. By default, sort by 'name'. :type sort_by: ``str`` :param limit: At most how many results to show. :type limit: ``int`` or ``NoneType`` :param num: If not None, choose the given entry from within filters. :type num: ``int`` or ``NoneType`` :param random: If true, choose a random entry from within filters. :type random: ``bool``
src/lsi/lsi.py
def _run_ssh(entries, username, idfile, no_prompt=False, command=None, show=None, only=None, sort_by=None, limit=None, tunnel=None, num=None, random=False): """ Lets the user choose which instance to SSH into. :param entries: The list of host entries. :type entries: [:py:class:`HostEntry`] :param username: The SSH username to use. Defaults to current user. :type username: ``str`` or ``NoneType`` :param idfile: The identity file to use. Optional. :type idfile: ``str`` or ``NoneType`` :param no_prompt: Whether to disable confirmation for SSH command. :type no_prompt: ``bool`` :param command: SSH command to run on matching instances. :type command: ``str`` or ``NoneType`` :param show: Instance attributes to show in addition to defaults. :type show: ``NoneType`` or ``list`` of ``str`` :param only: If not ``None``, will *only* show these attributes. :type only: ``NoneType`` or ``list`` of ``str`` :param sort_by: What to sort columns by. By default, sort by 'name'. :type sort_by: ``str`` :param limit: At most how many results to show. :type limit: ``int`` or ``NoneType`` :param num: If not None, choose the given entry from within filters. :type num: ``int`` or ``NoneType`` :param random: If true, choose a random entry from within filters. :type random: ``bool`` """ _print_entries = num is None _print_help = False if len(entries) == 0: exit('No entries matched the filters.') if no_prompt is True and command is not None: return _run_ssh_command(entries, username, idfile, command, tunnel) elif len(entries) == 1 or random is True: entry = py_random.choice(entries) if command is None: return _connect_ssh(entry, username, idfile, tunnel) else: return _run_ssh_command([entry], username, idfile, command, tunnel) elif command is not None: print(HostEntry.render_entries(entries, additional_columns=show, only_show=only, numbers=True)) if no_prompt is False: get_input("Press enter to run command {} on the {} " "above machines (Ctrl-C to cancel)" .format(cyan(command), len(entries))) return _run_ssh_command(entries, username, idfile, command, tunnel) else: while True: if sort_by is not None: entries = HostEntry.sort_by(entries, sort_by) if limit is not None: entries = entries[:limit] if _print_entries is True: print(HostEntry.render_entries(entries, additional_columns=show, only_show=only, numbers=True)) print('%s matching entries.' % len(entries)) _print_entries = False if _print_help is True: cmd_str = green(command) if command is not None else 'none set' msg = COMMANDS_STRING.format(username=username or 'none set', idfile=idfile or 'none set', cur_cmd=cmd_str) print(msg) _print_help = False elif command is not None: print('Set to run ssh command: %s' % cyan(command)) msg = 'Enter command (%s for help, %s to quit): ' % (cyan('h'), cyan('q')) if num is not None: choice = num else: choice = get_input(msg) if isinstance(choice, int): if 0 <= choice <= len(entries): break else: if num is not None: exit("Invalid number {}: must be between 0 and {}" .format(num, len(entries) - 1)) else: msg = "Invalid number: must be between 0 and %s" print(msg % (len(entries) - 1)) elif choice == 'x': if command is None: print('No command has been set. Set command with `c`') else: return _run_ssh_command(entries, username, idfile, command, tunnel) elif choice == 'h': _print_help = True elif choice in ['q', 'quit', 'exit']: print('bye!') return else: # All of these commands take one or more arguments, so the # split length must be at least 2. commands = choice.split() if len(commands) < 2: print(yellow('Unknown command "%s".' % choice)) else: cmd = commands[0] if cmd in ['u', 'i', 'p']: if cmd == 'u': username = commands[1] elif cmd == 'i': _idfile = commands[1] if not os.path.exists(_idfile): print(yellow('No such file: %s' % _idfile)) continue idfile = _idfile elif cmd == 'p': p = commands[1] try: profile = LsiProfile.load(p) _username = profile.username _idfile = expanduser(profile.identity_file) except LsiProfile.LoadError: print(yellow('No such profile: %s' % repr(p))) continue username = _username idfile = _idfile print('username: %s' % green(repr(username))) print('identity file: %s' % green(repr(idfile))) elif cmd == 'f': entries = filter_entries(entries, commands[1:], []) _print_entries = True elif cmd == 'e': entries = filter_entries(entries, [], commands[1:]) _print_entries = True elif cmd == 'c': command = ' '.join(commands[1:]) elif cmd == 'limit': try: limit = int(commands[1]) _print_entries = True except ValueError: print(yellow('Invalid limit (must be an integer)')) elif cmd == 'sort': sort_by = commands[1] if sort_by not in show: show.append(sort_by) _print_entries = True elif cmd == 'show': if show is None: show = commands[1:] else: show.extend(commands[1:]) _print_entries = True else: print(yellow('Unknown command "%s".' % cmd)) return _connect_ssh(entries[choice], username, idfile, tunnel)
def _run_ssh(entries, username, idfile, no_prompt=False, command=None, show=None, only=None, sort_by=None, limit=None, tunnel=None, num=None, random=False): """ Lets the user choose which instance to SSH into. :param entries: The list of host entries. :type entries: [:py:class:`HostEntry`] :param username: The SSH username to use. Defaults to current user. :type username: ``str`` or ``NoneType`` :param idfile: The identity file to use. Optional. :type idfile: ``str`` or ``NoneType`` :param no_prompt: Whether to disable confirmation for SSH command. :type no_prompt: ``bool`` :param command: SSH command to run on matching instances. :type command: ``str`` or ``NoneType`` :param show: Instance attributes to show in addition to defaults. :type show: ``NoneType`` or ``list`` of ``str`` :param only: If not ``None``, will *only* show these attributes. :type only: ``NoneType`` or ``list`` of ``str`` :param sort_by: What to sort columns by. By default, sort by 'name'. :type sort_by: ``str`` :param limit: At most how many results to show. :type limit: ``int`` or ``NoneType`` :param num: If not None, choose the given entry from within filters. :type num: ``int`` or ``NoneType`` :param random: If true, choose a random entry from within filters. :type random: ``bool`` """ _print_entries = num is None _print_help = False if len(entries) == 0: exit('No entries matched the filters.') if no_prompt is True and command is not None: return _run_ssh_command(entries, username, idfile, command, tunnel) elif len(entries) == 1 or random is True: entry = py_random.choice(entries) if command is None: return _connect_ssh(entry, username, idfile, tunnel) else: return _run_ssh_command([entry], username, idfile, command, tunnel) elif command is not None: print(HostEntry.render_entries(entries, additional_columns=show, only_show=only, numbers=True)) if no_prompt is False: get_input("Press enter to run command {} on the {} " "above machines (Ctrl-C to cancel)" .format(cyan(command), len(entries))) return _run_ssh_command(entries, username, idfile, command, tunnel) else: while True: if sort_by is not None: entries = HostEntry.sort_by(entries, sort_by) if limit is not None: entries = entries[:limit] if _print_entries is True: print(HostEntry.render_entries(entries, additional_columns=show, only_show=only, numbers=True)) print('%s matching entries.' % len(entries)) _print_entries = False if _print_help is True: cmd_str = green(command) if command is not None else 'none set' msg = COMMANDS_STRING.format(username=username or 'none set', idfile=idfile or 'none set', cur_cmd=cmd_str) print(msg) _print_help = False elif command is not None: print('Set to run ssh command: %s' % cyan(command)) msg = 'Enter command (%s for help, %s to quit): ' % (cyan('h'), cyan('q')) if num is not None: choice = num else: choice = get_input(msg) if isinstance(choice, int): if 0 <= choice <= len(entries): break else: if num is not None: exit("Invalid number {}: must be between 0 and {}" .format(num, len(entries) - 1)) else: msg = "Invalid number: must be between 0 and %s" print(msg % (len(entries) - 1)) elif choice == 'x': if command is None: print('No command has been set. Set command with `c`') else: return _run_ssh_command(entries, username, idfile, command, tunnel) elif choice == 'h': _print_help = True elif choice in ['q', 'quit', 'exit']: print('bye!') return else: # All of these commands take one or more arguments, so the # split length must be at least 2. commands = choice.split() if len(commands) < 2: print(yellow('Unknown command "%s".' % choice)) else: cmd = commands[0] if cmd in ['u', 'i', 'p']: if cmd == 'u': username = commands[1] elif cmd == 'i': _idfile = commands[1] if not os.path.exists(_idfile): print(yellow('No such file: %s' % _idfile)) continue idfile = _idfile elif cmd == 'p': p = commands[1] try: profile = LsiProfile.load(p) _username = profile.username _idfile = expanduser(profile.identity_file) except LsiProfile.LoadError: print(yellow('No such profile: %s' % repr(p))) continue username = _username idfile = _idfile print('username: %s' % green(repr(username))) print('identity file: %s' % green(repr(idfile))) elif cmd == 'f': entries = filter_entries(entries, commands[1:], []) _print_entries = True elif cmd == 'e': entries = filter_entries(entries, [], commands[1:]) _print_entries = True elif cmd == 'c': command = ' '.join(commands[1:]) elif cmd == 'limit': try: limit = int(commands[1]) _print_entries = True except ValueError: print(yellow('Invalid limit (must be an integer)')) elif cmd == 'sort': sort_by = commands[1] if sort_by not in show: show.append(sort_by) _print_entries = True elif cmd == 'show': if show is None: show = commands[1:] else: show.extend(commands[1:]) _print_entries = True else: print(yellow('Unknown command "%s".' % cmd)) return _connect_ssh(entries[choice], username, idfile, tunnel)
[ "Lets", "the", "user", "choose", "which", "instance", "to", "SSH", "into", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L195-L350
[ "def", "_run_ssh", "(", "entries", ",", "username", ",", "idfile", ",", "no_prompt", "=", "False", ",", "command", "=", "None", ",", "show", "=", "None", ",", "only", "=", "None", ",", "sort_by", "=", "None", ",", "limit", "=", "None", ",", "tunnel", "=", "None", ",", "num", "=", "None", ",", "random", "=", "False", ")", ":", "_print_entries", "=", "num", "is", "None", "_print_help", "=", "False", "if", "len", "(", "entries", ")", "==", "0", ":", "exit", "(", "'No entries matched the filters.'", ")", "if", "no_prompt", "is", "True", "and", "command", "is", "not", "None", ":", "return", "_run_ssh_command", "(", "entries", ",", "username", ",", "idfile", ",", "command", ",", "tunnel", ")", "elif", "len", "(", "entries", ")", "==", "1", "or", "random", "is", "True", ":", "entry", "=", "py_random", ".", "choice", "(", "entries", ")", "if", "command", "is", "None", ":", "return", "_connect_ssh", "(", "entry", ",", "username", ",", "idfile", ",", "tunnel", ")", "else", ":", "return", "_run_ssh_command", "(", "[", "entry", "]", ",", "username", ",", "idfile", ",", "command", ",", "tunnel", ")", "elif", "command", "is", "not", "None", ":", "print", "(", "HostEntry", ".", "render_entries", "(", "entries", ",", "additional_columns", "=", "show", ",", "only_show", "=", "only", ",", "numbers", "=", "True", ")", ")", "if", "no_prompt", "is", "False", ":", "get_input", "(", "\"Press enter to run command {} on the {} \"", "\"above machines (Ctrl-C to cancel)\"", ".", "format", "(", "cyan", "(", "command", ")", ",", "len", "(", "entries", ")", ")", ")", "return", "_run_ssh_command", "(", "entries", ",", "username", ",", "idfile", ",", "command", ",", "tunnel", ")", "else", ":", "while", "True", ":", "if", "sort_by", "is", "not", "None", ":", "entries", "=", "HostEntry", ".", "sort_by", "(", "entries", ",", "sort_by", ")", "if", "limit", "is", "not", "None", ":", "entries", "=", "entries", "[", ":", "limit", "]", "if", "_print_entries", "is", "True", ":", "print", "(", "HostEntry", ".", "render_entries", "(", "entries", ",", "additional_columns", "=", "show", ",", "only_show", "=", "only", ",", "numbers", "=", "True", ")", ")", "print", "(", "'%s matching entries.'", "%", "len", "(", "entries", ")", ")", "_print_entries", "=", "False", "if", "_print_help", "is", "True", ":", "cmd_str", "=", "green", "(", "command", ")", "if", "command", "is", "not", "None", "else", "'none set'", "msg", "=", "COMMANDS_STRING", ".", "format", "(", "username", "=", "username", "or", "'none set'", ",", "idfile", "=", "idfile", "or", "'none set'", ",", "cur_cmd", "=", "cmd_str", ")", "print", "(", "msg", ")", "_print_help", "=", "False", "elif", "command", "is", "not", "None", ":", "print", "(", "'Set to run ssh command: %s'", "%", "cyan", "(", "command", ")", ")", "msg", "=", "'Enter command (%s for help, %s to quit): '", "%", "(", "cyan", "(", "'h'", ")", ",", "cyan", "(", "'q'", ")", ")", "if", "num", "is", "not", "None", ":", "choice", "=", "num", "else", ":", "choice", "=", "get_input", "(", "msg", ")", "if", "isinstance", "(", "choice", ",", "int", ")", ":", "if", "0", "<=", "choice", "<=", "len", "(", "entries", ")", ":", "break", "else", ":", "if", "num", "is", "not", "None", ":", "exit", "(", "\"Invalid number {}: must be between 0 and {}\"", ".", "format", "(", "num", ",", "len", "(", "entries", ")", "-", "1", ")", ")", "else", ":", "msg", "=", "\"Invalid number: must be between 0 and %s\"", "print", "(", "msg", "%", "(", "len", "(", "entries", ")", "-", "1", ")", ")", "elif", "choice", "==", "'x'", ":", "if", "command", "is", "None", ":", "print", "(", "'No command has been set. Set command with `c`'", ")", "else", ":", "return", "_run_ssh_command", "(", "entries", ",", "username", ",", "idfile", ",", "command", ",", "tunnel", ")", "elif", "choice", "==", "'h'", ":", "_print_help", "=", "True", "elif", "choice", "in", "[", "'q'", ",", "'quit'", ",", "'exit'", "]", ":", "print", "(", "'bye!'", ")", "return", "else", ":", "# All of these commands take one or more arguments, so the", "# split length must be at least 2.", "commands", "=", "choice", ".", "split", "(", ")", "if", "len", "(", "commands", ")", "<", "2", ":", "print", "(", "yellow", "(", "'Unknown command \"%s\".'", "%", "choice", ")", ")", "else", ":", "cmd", "=", "commands", "[", "0", "]", "if", "cmd", "in", "[", "'u'", ",", "'i'", ",", "'p'", "]", ":", "if", "cmd", "==", "'u'", ":", "username", "=", "commands", "[", "1", "]", "elif", "cmd", "==", "'i'", ":", "_idfile", "=", "commands", "[", "1", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "_idfile", ")", ":", "print", "(", "yellow", "(", "'No such file: %s'", "%", "_idfile", ")", ")", "continue", "idfile", "=", "_idfile", "elif", "cmd", "==", "'p'", ":", "p", "=", "commands", "[", "1", "]", "try", ":", "profile", "=", "LsiProfile", ".", "load", "(", "p", ")", "_username", "=", "profile", ".", "username", "_idfile", "=", "expanduser", "(", "profile", ".", "identity_file", ")", "except", "LsiProfile", ".", "LoadError", ":", "print", "(", "yellow", "(", "'No such profile: %s'", "%", "repr", "(", "p", ")", ")", ")", "continue", "username", "=", "_username", "idfile", "=", "_idfile", "print", "(", "'username: %s'", "%", "green", "(", "repr", "(", "username", ")", ")", ")", "print", "(", "'identity file: %s'", "%", "green", "(", "repr", "(", "idfile", ")", ")", ")", "elif", "cmd", "==", "'f'", ":", "entries", "=", "filter_entries", "(", "entries", ",", "commands", "[", "1", ":", "]", ",", "[", "]", ")", "_print_entries", "=", "True", "elif", "cmd", "==", "'e'", ":", "entries", "=", "filter_entries", "(", "entries", ",", "[", "]", ",", "commands", "[", "1", ":", "]", ")", "_print_entries", "=", "True", "elif", "cmd", "==", "'c'", ":", "command", "=", "' '", ".", "join", "(", "commands", "[", "1", ":", "]", ")", "elif", "cmd", "==", "'limit'", ":", "try", ":", "limit", "=", "int", "(", "commands", "[", "1", "]", ")", "_print_entries", "=", "True", "except", "ValueError", ":", "print", "(", "yellow", "(", "'Invalid limit (must be an integer)'", ")", ")", "elif", "cmd", "==", "'sort'", ":", "sort_by", "=", "commands", "[", "1", "]", "if", "sort_by", "not", "in", "show", ":", "show", ".", "append", "(", "sort_by", ")", "_print_entries", "=", "True", "elif", "cmd", "==", "'show'", ":", "if", "show", "is", "None", ":", "show", "=", "commands", "[", "1", ":", "]", "else", ":", "show", ".", "extend", "(", "commands", "[", "1", ":", "]", ")", "_print_entries", "=", "True", "else", ":", "print", "(", "yellow", "(", "'Unknown command \"%s\".'", "%", "cmd", ")", ")", "return", "_connect_ssh", "(", "entries", "[", "choice", "]", ",", "username", ",", "idfile", ",", "tunnel", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_get_path
Queries bash to find the path to a commmand on the system.
src/lsi/lsi.py
def _get_path(cmd): """Queries bash to find the path to a commmand on the system.""" if cmd in _PATHS: return _PATHS[cmd] out = subprocess.check_output('which {}'.format(cmd), shell=True) _PATHS[cmd] = out.decode("utf-8").strip() return _PATHS[cmd]
def _get_path(cmd): """Queries bash to find the path to a commmand on the system.""" if cmd in _PATHS: return _PATHS[cmd] out = subprocess.check_output('which {}'.format(cmd), shell=True) _PATHS[cmd] = out.decode("utf-8").strip() return _PATHS[cmd]
[ "Queries", "bash", "to", "find", "the", "path", "to", "a", "commmand", "on", "the", "system", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L353-L359
[ "def", "_get_path", "(", "cmd", ")", ":", "if", "cmd", "in", "_PATHS", ":", "return", "_PATHS", "[", "cmd", "]", "out", "=", "subprocess", ".", "check_output", "(", "'which {}'", ".", "format", "(", "cmd", ")", ",", "shell", "=", "True", ")", "_PATHS", "[", "cmd", "]", "=", "out", ".", "decode", "(", "\"utf-8\"", ")", ".", "strip", "(", ")", "return", "_PATHS", "[", "cmd", "]" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_build_ssh_command
Uses hostname and other info to construct an SSH command.
src/lsi/lsi.py
def _build_ssh_command(hostname, username, idfile, ssh_command, tunnel): """Uses hostname and other info to construct an SSH command.""" command = [_get_path('ssh'), '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=5'] if idfile is not None: command.extend(['-i', idfile]) if tunnel is not None: # If there's a tunnel, run the ssh command on the tunneled host. command.extend(['-A', '-t', tunnel, 'ssh', '-A', '-t']) if username is not None: command.append('{}@{}'.format(username, hostname)) else: command.append(hostname) if ssh_command is not None: command.append(repr(ssh_command)) return(' '.join(command))
def _build_ssh_command(hostname, username, idfile, ssh_command, tunnel): """Uses hostname and other info to construct an SSH command.""" command = [_get_path('ssh'), '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=5'] if idfile is not None: command.extend(['-i', idfile]) if tunnel is not None: # If there's a tunnel, run the ssh command on the tunneled host. command.extend(['-A', '-t', tunnel, 'ssh', '-A', '-t']) if username is not None: command.append('{}@{}'.format(username, hostname)) else: command.append(hostname) if ssh_command is not None: command.append(repr(ssh_command)) return(' '.join(command))
[ "Uses", "hostname", "and", "other", "info", "to", "construct", "an", "SSH", "command", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L362-L378
[ "def", "_build_ssh_command", "(", "hostname", ",", "username", ",", "idfile", ",", "ssh_command", ",", "tunnel", ")", ":", "command", "=", "[", "_get_path", "(", "'ssh'", ")", ",", "'-o'", ",", "'StrictHostKeyChecking=no'", ",", "'-o'", ",", "'ConnectTimeout=5'", "]", "if", "idfile", "is", "not", "None", ":", "command", ".", "extend", "(", "[", "'-i'", ",", "idfile", "]", ")", "if", "tunnel", "is", "not", "None", ":", "# If there's a tunnel, run the ssh command on the tunneled host.", "command", ".", "extend", "(", "[", "'-A'", ",", "'-t'", ",", "tunnel", ",", "'ssh'", ",", "'-A'", ",", "'-t'", "]", ")", "if", "username", "is", "not", "None", ":", "command", ".", "append", "(", "'{}@{}'", ".", "format", "(", "username", ",", "hostname", ")", ")", "else", ":", "command", ".", "append", "(", "hostname", ")", "if", "ssh_command", "is", "not", "None", ":", "command", ".", "append", "(", "repr", "(", "ssh_command", ")", ")", "return", "(", "' '", ".", "join", "(", "command", ")", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_build_scp_command
Uses hostname and other info to construct an SCP command. :param hostname: The hostname of the remote machine. :type hostname: ``str`` :param username: The username to use on the remote machine. :type username: ``str`` :param idfile: A path to the identity file to use. :type idfile: ``str`` :param is_get: If true, we are getting a file rather than putting a file. :type is_get: ``bool`` :param local_path: The path on the local file system. :type local_path: ``str`` :param remote_path: The path on the remote file system. :type remote_path: ``str``
src/lsi/lsi.py
def _build_scp_command(hostname, username, idfile, is_get, local_path, remote_path): """ Uses hostname and other info to construct an SCP command. :param hostname: The hostname of the remote machine. :type hostname: ``str`` :param username: The username to use on the remote machine. :type username: ``str`` :param idfile: A path to the identity file to use. :type idfile: ``str`` :param is_get: If true, we are getting a file rather than putting a file. :type is_get: ``bool`` :param local_path: The path on the local file system. :type local_path: ``str`` :param remote_path: The path on the remote file system. :type remote_path: ``str`` """ if hostname.strip() == '' or hostname is None: raise ValueError('Empty hostname') command = [_get_path('scp'), '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=5', '-o', 'UserKnownHostsFile={}'.format(_KNOWN_HOSTS_FILE)] if idfile is not None: command.extend(['-i', idfile]) if username is not None: hostname = '%s@%s' % (username, hostname) remote_path = '{}:{}'.format(hostname, remote_path) if is_get: command.extend([remote_path, local_path]) else: command.extend([local_path, remote_path]) return ' '.join(command)
def _build_scp_command(hostname, username, idfile, is_get, local_path, remote_path): """ Uses hostname and other info to construct an SCP command. :param hostname: The hostname of the remote machine. :type hostname: ``str`` :param username: The username to use on the remote machine. :type username: ``str`` :param idfile: A path to the identity file to use. :type idfile: ``str`` :param is_get: If true, we are getting a file rather than putting a file. :type is_get: ``bool`` :param local_path: The path on the local file system. :type local_path: ``str`` :param remote_path: The path on the remote file system. :type remote_path: ``str`` """ if hostname.strip() == '' or hostname is None: raise ValueError('Empty hostname') command = [_get_path('scp'), '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=5', '-o', 'UserKnownHostsFile={}'.format(_KNOWN_HOSTS_FILE)] if idfile is not None: command.extend(['-i', idfile]) if username is not None: hostname = '%s@%s' % (username, hostname) remote_path = '{}:{}'.format(hostname, remote_path) if is_get: command.extend([remote_path, local_path]) else: command.extend([local_path, remote_path]) return ' '.join(command)
[ "Uses", "hostname", "and", "other", "info", "to", "construct", "an", "SCP", "command", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L380-L413
[ "def", "_build_scp_command", "(", "hostname", ",", "username", ",", "idfile", ",", "is_get", ",", "local_path", ",", "remote_path", ")", ":", "if", "hostname", ".", "strip", "(", ")", "==", "''", "or", "hostname", "is", "None", ":", "raise", "ValueError", "(", "'Empty hostname'", ")", "command", "=", "[", "_get_path", "(", "'scp'", ")", ",", "'-o'", ",", "'StrictHostKeyChecking=no'", ",", "'-o'", ",", "'ConnectTimeout=5'", ",", "'-o'", ",", "'UserKnownHostsFile={}'", ".", "format", "(", "_KNOWN_HOSTS_FILE", ")", "]", "if", "idfile", "is", "not", "None", ":", "command", ".", "extend", "(", "[", "'-i'", ",", "idfile", "]", ")", "if", "username", "is", "not", "None", ":", "hostname", "=", "'%s@%s'", "%", "(", "username", ",", "hostname", ")", "remote_path", "=", "'{}:{}'", ".", "format", "(", "hostname", ",", "remote_path", ")", "if", "is_get", ":", "command", ".", "extend", "(", "[", "remote_path", ",", "local_path", "]", ")", "else", ":", "command", ".", "extend", "(", "[", "local_path", ",", "remote_path", "]", ")", "return", "' '", ".", "join", "(", "command", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_copy_to
Performs an SCP command where the remote_path is the target and the local_path is the source. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The target path on the remote machine(s). :type remote_path: ``str`` :param local_path: The source path on the local machine. :type local_path: ``str`` :param profile: The profile, holding username/idfile info, etc. :type profile: :py:class:`Profile`
src/lsi/lsi.py
def _copy_to(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the target and the local_path is the source. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The target path on the remote machine(s). :type remote_path: ``str`` :param local_path: The source path on the local machine. :type local_path: ``str`` :param profile: The profile, holding username/idfile info, etc. :type profile: :py:class:`Profile` """ commands = [] for entry in entries: hname = entry.hostname or entry.public_ip cmd = _build_scp_command(hname, profile.username, profile.identity_file, is_get=False, local_path=local_path, remote_path=remote_path) print('Command:', cmd) commands.append({ 'command': cmd, 'description': entry.display() }) stream_commands(commands) print(green('Finished copying'))
def _copy_to(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the target and the local_path is the source. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The target path on the remote machine(s). :type remote_path: ``str`` :param local_path: The source path on the local machine. :type local_path: ``str`` :param profile: The profile, holding username/idfile info, etc. :type profile: :py:class:`Profile` """ commands = [] for entry in entries: hname = entry.hostname or entry.public_ip cmd = _build_scp_command(hname, profile.username, profile.identity_file, is_get=False, local_path=local_path, remote_path=remote_path) print('Command:', cmd) commands.append({ 'command': cmd, 'description': entry.display() }) stream_commands(commands) print(green('Finished copying'))
[ "Performs", "an", "SCP", "command", "where", "the", "remote_path", "is", "the", "target", "and", "the", "local_path", "is", "the", "source", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L416-L444
[ "def", "_copy_to", "(", "entries", ",", "remote_path", ",", "local_path", ",", "profile", ")", ":", "commands", "=", "[", "]", "for", "entry", "in", "entries", ":", "hname", "=", "entry", ".", "hostname", "or", "entry", ".", "public_ip", "cmd", "=", "_build_scp_command", "(", "hname", ",", "profile", ".", "username", ",", "profile", ".", "identity_file", ",", "is_get", "=", "False", ",", "local_path", "=", "local_path", ",", "remote_path", "=", "remote_path", ")", "print", "(", "'Command:'", ",", "cmd", ")", "commands", ".", "append", "(", "{", "'command'", ":", "cmd", ",", "'description'", ":", "entry", ".", "display", "(", ")", "}", ")", "stream_commands", "(", "commands", ")", "print", "(", "green", "(", "'Finished copying'", ")", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_copy_from
Performs an SCP command where the remote_path is the source and the local_path is a format string, formatted individually for each host being copied from so as to create one or more distinct paths on the local system. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The source path on the remote machine(s). :type remote_path: ``str`` :param local_path: A format string for the path on the local machine. :type local_path: ``str`` :param profile: The profile, holding username/idfile info, etc. :type profile: :py:class:`Profile`
src/lsi/lsi.py
def _copy_from(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the source and the local_path is a format string, formatted individually for each host being copied from so as to create one or more distinct paths on the local system. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The source path on the remote machine(s). :type remote_path: ``str`` :param local_path: A format string for the path on the local machine. :type local_path: ``str`` :param profile: The profile, holding username/idfile info, etc. :type profile: :py:class:`Profile` """ commands = [] paths = set() for entry in entries: hname = entry.hostname or entry.public_ip _local_path = entry.format_string(local_path) if _local_path in paths: raise ValueError('Duplicate local paths: one or more paths ' 'had value {} after formatting.' .format(local_path)) paths.add(_local_path) # If the path references a folder, create the folder if it doesn't # exist. _folder = os.path.split(_local_path)[0] if len(_folder) > 0: if not os.path.exists(_folder): print('Creating directory ' + _folder) os.makedirs(_folder) cmd = _build_scp_command(hname, profile.username, profile.identity_file, is_get=True, local_path=_local_path, remote_path=remote_path) print('Command:', cmd) commands.append({ 'command': cmd, 'description': entry.display() }) stream_commands(commands) print(green('Finished copying'))
def _copy_from(entries, remote_path, local_path, profile): """ Performs an SCP command where the remote_path is the source and the local_path is a format string, formatted individually for each host being copied from so as to create one or more distinct paths on the local system. :param entries: A list of entries. :type entries: ``list`` of :py:class:`HostEntry` :param remote_path: The source path on the remote machine(s). :type remote_path: ``str`` :param local_path: A format string for the path on the local machine. :type local_path: ``str`` :param profile: The profile, holding username/idfile info, etc. :type profile: :py:class:`Profile` """ commands = [] paths = set() for entry in entries: hname = entry.hostname or entry.public_ip _local_path = entry.format_string(local_path) if _local_path in paths: raise ValueError('Duplicate local paths: one or more paths ' 'had value {} after formatting.' .format(local_path)) paths.add(_local_path) # If the path references a folder, create the folder if it doesn't # exist. _folder = os.path.split(_local_path)[0] if len(_folder) > 0: if not os.path.exists(_folder): print('Creating directory ' + _folder) os.makedirs(_folder) cmd = _build_scp_command(hname, profile.username, profile.identity_file, is_get=True, local_path=_local_path, remote_path=remote_path) print('Command:', cmd) commands.append({ 'command': cmd, 'description': entry.display() }) stream_commands(commands) print(green('Finished copying'))
[ "Performs", "an", "SCP", "command", "where", "the", "remote_path", "is", "the", "source", "and", "the", "local_path", "is", "a", "format", "string", "formatted", "individually", "for", "each", "host", "being", "copied", "from", "so", "as", "to", "create", "one", "or", "more", "distinct", "paths", "on", "the", "local", "system", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L447-L491
[ "def", "_copy_from", "(", "entries", ",", "remote_path", ",", "local_path", ",", "profile", ")", ":", "commands", "=", "[", "]", "paths", "=", "set", "(", ")", "for", "entry", "in", "entries", ":", "hname", "=", "entry", ".", "hostname", "or", "entry", ".", "public_ip", "_local_path", "=", "entry", ".", "format_string", "(", "local_path", ")", "if", "_local_path", "in", "paths", ":", "raise", "ValueError", "(", "'Duplicate local paths: one or more paths '", "'had value {} after formatting.'", ".", "format", "(", "local_path", ")", ")", "paths", ".", "add", "(", "_local_path", ")", "# If the path references a folder, create the folder if it doesn't", "# exist.", "_folder", "=", "os", ".", "path", ".", "split", "(", "_local_path", ")", "[", "0", "]", "if", "len", "(", "_folder", ")", ">", "0", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "_folder", ")", ":", "print", "(", "'Creating directory '", "+", "_folder", ")", "os", ".", "makedirs", "(", "_folder", ")", "cmd", "=", "_build_scp_command", "(", "hname", ",", "profile", ".", "username", ",", "profile", ".", "identity_file", ",", "is_get", "=", "True", ",", "local_path", "=", "_local_path", ",", "remote_path", "=", "remote_path", ")", "print", "(", "'Command:'", ",", "cmd", ")", "commands", ".", "append", "(", "{", "'command'", ":", "cmd", ",", "'description'", ":", "entry", ".", "display", "(", ")", "}", ")", "stream_commands", "(", "commands", ")", "print", "(", "green", "(", "'Finished copying'", ")", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_run_ssh_command
Runs the given command over SSH in parallel on all hosts in `entries`. :param entries: The host entries the hostnames from. :type entries: ``list`` of :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity file to use, or none. :type idfile: ``str`` or ``NoneType`` :param command: The command to run. :type command: ``str`` :param parallel: If true, commands will be run in parallel. :type parallel: ``bool``
src/lsi/lsi.py
def _run_ssh_command(entries, username, idfile, command, tunnel, parallel=False): """ Runs the given command over SSH in parallel on all hosts in `entries`. :param entries: The host entries the hostnames from. :type entries: ``list`` of :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity file to use, or none. :type idfile: ``str`` or ``NoneType`` :param command: The command to run. :type command: ``str`` :param parallel: If true, commands will be run in parallel. :type parallel: ``bool`` """ if len(entries) == 0: print('(No hosts to run command on)') return 1 if command.strip() == '' or command is None: raise ValueError('No command given') print('Running command {0} on {1} matching hosts' .format(green(repr(command)), len(entries))) shell_cmds = [] for entry in entries: hname = entry.hostname or entry.public_ip cmd = _build_ssh_command(hname, username, idfile, command, tunnel) shell_cmds.append({ 'command': cmd, 'description': entry.display() }) stream_commands(shell_cmds, parallel=parallel) print(green('All commands finished'))
def _run_ssh_command(entries, username, idfile, command, tunnel, parallel=False): """ Runs the given command over SSH in parallel on all hosts in `entries`. :param entries: The host entries the hostnames from. :type entries: ``list`` of :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity file to use, or none. :type idfile: ``str`` or ``NoneType`` :param command: The command to run. :type command: ``str`` :param parallel: If true, commands will be run in parallel. :type parallel: ``bool`` """ if len(entries) == 0: print('(No hosts to run command on)') return 1 if command.strip() == '' or command is None: raise ValueError('No command given') print('Running command {0} on {1} matching hosts' .format(green(repr(command)), len(entries))) shell_cmds = [] for entry in entries: hname = entry.hostname or entry.public_ip cmd = _build_ssh_command(hname, username, idfile, command, tunnel) shell_cmds.append({ 'command': cmd, 'description': entry.display() }) stream_commands(shell_cmds, parallel=parallel) print(green('All commands finished'))
[ "Runs", "the", "given", "command", "over", "SSH", "in", "parallel", "on", "all", "hosts", "in", "entries", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L494-L526
[ "def", "_run_ssh_command", "(", "entries", ",", "username", ",", "idfile", ",", "command", ",", "tunnel", ",", "parallel", "=", "False", ")", ":", "if", "len", "(", "entries", ")", "==", "0", ":", "print", "(", "'(No hosts to run command on)'", ")", "return", "1", "if", "command", ".", "strip", "(", ")", "==", "''", "or", "command", "is", "None", ":", "raise", "ValueError", "(", "'No command given'", ")", "print", "(", "'Running command {0} on {1} matching hosts'", ".", "format", "(", "green", "(", "repr", "(", "command", ")", ")", ",", "len", "(", "entries", ")", ")", ")", "shell_cmds", "=", "[", "]", "for", "entry", "in", "entries", ":", "hname", "=", "entry", ".", "hostname", "or", "entry", ".", "public_ip", "cmd", "=", "_build_ssh_command", "(", "hname", ",", "username", ",", "idfile", ",", "command", ",", "tunnel", ")", "shell_cmds", ".", "append", "(", "{", "'command'", ":", "cmd", ",", "'description'", ":", "entry", ".", "display", "(", ")", "}", ")", "stream_commands", "(", "shell_cmds", ",", "parallel", "=", "parallel", ")", "print", "(", "green", "(", "'All commands finished'", ")", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_connect_ssh
SSH into to a host. :param entry: The host entry to pull the hostname from. :type entry: :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity file to use, if supplying a username. :type idfile: ``str`` or ``NoneType`` :param tunnel: Host to tunnel SSH command through. :type tunnel: ``str`` or ``NoneType`` :return: An exit status code. :rtype: ``int``
src/lsi/lsi.py
def _connect_ssh(entry, username, idfile, tunnel=None): """ SSH into to a host. :param entry: The host entry to pull the hostname from. :type entry: :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity file to use, if supplying a username. :type idfile: ``str`` or ``NoneType`` :param tunnel: Host to tunnel SSH command through. :type tunnel: ``str`` or ``NoneType`` :return: An exit status code. :rtype: ``int`` """ if entry.hostname != "" and entry.hostname is not None: _host = entry.hostname elif entry.public_ip != "" and entry.public_ip is not None: _host = entry.public_ip elif entry.private_ip != "" and entry.private_ip is not None: if tunnel is None: raise ValueError("Entry does not have a hostname or public IP. " "You can connect via private IP if you use a " "tunnel.") _host = entry.private_ip else: raise ValueError("No hostname, public IP or private IP information " "found on host entry. I don't know how to connect.") command = _build_ssh_command(_host, username, idfile, None, tunnel) print('Connecting to %s...' % cyan(entry.display())) print('SSH command: %s' % green(command)) proc = subprocess.Popen(command, shell=True) return proc.wait()
def _connect_ssh(entry, username, idfile, tunnel=None): """ SSH into to a host. :param entry: The host entry to pull the hostname from. :type entry: :py:class:`HostEntry` :param username: To use a specific username. :type username: ``str`` or ``NoneType`` :param idfile: The SSH identity file to use, if supplying a username. :type idfile: ``str`` or ``NoneType`` :param tunnel: Host to tunnel SSH command through. :type tunnel: ``str`` or ``NoneType`` :return: An exit status code. :rtype: ``int`` """ if entry.hostname != "" and entry.hostname is not None: _host = entry.hostname elif entry.public_ip != "" and entry.public_ip is not None: _host = entry.public_ip elif entry.private_ip != "" and entry.private_ip is not None: if tunnel is None: raise ValueError("Entry does not have a hostname or public IP. " "You can connect via private IP if you use a " "tunnel.") _host = entry.private_ip else: raise ValueError("No hostname, public IP or private IP information " "found on host entry. I don't know how to connect.") command = _build_ssh_command(_host, username, idfile, None, tunnel) print('Connecting to %s...' % cyan(entry.display())) print('SSH command: %s' % green(command)) proc = subprocess.Popen(command, shell=True) return proc.wait()
[ "SSH", "into", "to", "a", "host", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L529-L562
[ "def", "_connect_ssh", "(", "entry", ",", "username", ",", "idfile", ",", "tunnel", "=", "None", ")", ":", "if", "entry", ".", "hostname", "!=", "\"\"", "and", "entry", ".", "hostname", "is", "not", "None", ":", "_host", "=", "entry", ".", "hostname", "elif", "entry", ".", "public_ip", "!=", "\"\"", "and", "entry", ".", "public_ip", "is", "not", "None", ":", "_host", "=", "entry", ".", "public_ip", "elif", "entry", ".", "private_ip", "!=", "\"\"", "and", "entry", ".", "private_ip", "is", "not", "None", ":", "if", "tunnel", "is", "None", ":", "raise", "ValueError", "(", "\"Entry does not have a hostname or public IP. \"", "\"You can connect via private IP if you use a \"", "\"tunnel.\"", ")", "_host", "=", "entry", ".", "private_ip", "else", ":", "raise", "ValueError", "(", "\"No hostname, public IP or private IP information \"", "\"found on host entry. I don't know how to connect.\"", ")", "command", "=", "_build_ssh_command", "(", "_host", ",", "username", ",", "idfile", ",", "None", ",", "tunnel", ")", "print", "(", "'Connecting to %s...'", "%", "cyan", "(", "entry", ".", "display", "(", ")", ")", ")", "print", "(", "'SSH command: %s'", "%", "green", "(", "command", ")", ")", "proc", "=", "subprocess", ".", "Popen", "(", "command", ",", "shell", "=", "True", ")", "return", "proc", ".", "wait", "(", ")" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
_get_args
Parse command-line arguments.
src/lsi/lsi.py
def _get_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser(description='List EC2 instances') parser.add_argument('-l', '--latest', action='store_true', default=False, help='Query AWS for latest instances') parser.add_argument('--version', action='store_true', default=False, help='Print version and exit') parser.add_argument('--refresh-only', action='store_true', default=False, help='Refresh cache and exit') parser.add_argument('--host', help='Specific host to list', default=None) parser.add_argument('-s', '--ssh', action='store_true', help='SSH to instance', default=False) parser.add_argument('-i', '--identity-file', help='SSH identify file', default=None) parser.add_argument('-u', '--username', default=None, help='Log in as this user') parser.add_argument('filters', nargs='*', help='Text filters for output lines') parser.add_argument('-v', '--exclude', nargs='+', help='Exclude results that match these') parser.add_argument('-c', '--command', type=str, help='Command to run on matching instance(s)') parser.add_argument('-y', '--no-prompt', action='store_true', default=False, help="Don't ask for confirmation before running a " "command") parser.add_argument('-p', '--profile', type=str, help='Profile to use (defined in ~/.lsi)') parser.add_argument('--show', nargs='+', default=None, help='Instance attributes to show') parser.add_argument('--only', nargs='+', default=None, help='Show ONLY these instance attributes') parser.add_argument('--sep', type=str, default=None, help='Simple output with given separator') parser.add_argument('--sort-by', type=str, default="name", help='What to sort list by') parser.add_argument('-L', '--limit', type=int, default=None, help='Show at most this many entries') parser.add_argument('--attributes', action='store_true', help='Show all available attributes') parser.add_argument('--get', nargs=2, default=None, help='Get files from matching instances, must be ' 'followed by the source and destination filenames') parser.add_argument('--put', nargs=2, default=None, help='Put a local file on matching instances, must be ' 'followed by the source and destination filenames') parser.add_argument('-t', '--tunnel', default=None, help='Connect via the tunneled host.') parser.add_argument("-r", "--random", action="store_true", default=False, help="Choose a random instance from within results.") parser.add_argument("-n", "--num", type=int, default=None, help="Choose the given number from within results.") args = parser.parse_args() if args.exclude is None: args.exclude = [] # Presumably, if someone is sorting by something, they want to show that # thing... if args.sort_by is not None: args.show = (args.show or []) + [args.sort_by] return args
def _get_args(): """Parse command-line arguments.""" parser = argparse.ArgumentParser(description='List EC2 instances') parser.add_argument('-l', '--latest', action='store_true', default=False, help='Query AWS for latest instances') parser.add_argument('--version', action='store_true', default=False, help='Print version and exit') parser.add_argument('--refresh-only', action='store_true', default=False, help='Refresh cache and exit') parser.add_argument('--host', help='Specific host to list', default=None) parser.add_argument('-s', '--ssh', action='store_true', help='SSH to instance', default=False) parser.add_argument('-i', '--identity-file', help='SSH identify file', default=None) parser.add_argument('-u', '--username', default=None, help='Log in as this user') parser.add_argument('filters', nargs='*', help='Text filters for output lines') parser.add_argument('-v', '--exclude', nargs='+', help='Exclude results that match these') parser.add_argument('-c', '--command', type=str, help='Command to run on matching instance(s)') parser.add_argument('-y', '--no-prompt', action='store_true', default=False, help="Don't ask for confirmation before running a " "command") parser.add_argument('-p', '--profile', type=str, help='Profile to use (defined in ~/.lsi)') parser.add_argument('--show', nargs='+', default=None, help='Instance attributes to show') parser.add_argument('--only', nargs='+', default=None, help='Show ONLY these instance attributes') parser.add_argument('--sep', type=str, default=None, help='Simple output with given separator') parser.add_argument('--sort-by', type=str, default="name", help='What to sort list by') parser.add_argument('-L', '--limit', type=int, default=None, help='Show at most this many entries') parser.add_argument('--attributes', action='store_true', help='Show all available attributes') parser.add_argument('--get', nargs=2, default=None, help='Get files from matching instances, must be ' 'followed by the source and destination filenames') parser.add_argument('--put', nargs=2, default=None, help='Put a local file on matching instances, must be ' 'followed by the source and destination filenames') parser.add_argument('-t', '--tunnel', default=None, help='Connect via the tunneled host.') parser.add_argument("-r", "--random", action="store_true", default=False, help="Choose a random instance from within results.") parser.add_argument("-n", "--num", type=int, default=None, help="Choose the given number from within results.") args = parser.parse_args() if args.exclude is None: args.exclude = [] # Presumably, if someone is sorting by something, they want to show that # thing... if args.sort_by is not None: args.show = (args.show or []) + [args.sort_by] return args
[ "Parse", "command", "-", "line", "arguments", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L572-L631
[ "def", "_get_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'List EC2 instances'", ")", "parser", ".", "add_argument", "(", "'-l'", ",", "'--latest'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Query AWS for latest instances'", ")", "parser", ".", "add_argument", "(", "'--version'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Print version and exit'", ")", "parser", ".", "add_argument", "(", "'--refresh-only'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "'Refresh cache and exit'", ")", "parser", ".", "add_argument", "(", "'--host'", ",", "help", "=", "'Specific host to list'", ",", "default", "=", "None", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--ssh'", ",", "action", "=", "'store_true'", ",", "help", "=", "'SSH to instance'", ",", "default", "=", "False", ")", "parser", ".", "add_argument", "(", "'-i'", ",", "'--identity-file'", ",", "help", "=", "'SSH identify file'", ",", "default", "=", "None", ")", "parser", ".", "add_argument", "(", "'-u'", ",", "'--username'", ",", "default", "=", "None", ",", "help", "=", "'Log in as this user'", ")", "parser", ".", "add_argument", "(", "'filters'", ",", "nargs", "=", "'*'", ",", "help", "=", "'Text filters for output lines'", ")", "parser", ".", "add_argument", "(", "'-v'", ",", "'--exclude'", ",", "nargs", "=", "'+'", ",", "help", "=", "'Exclude results that match these'", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--command'", ",", "type", "=", "str", ",", "help", "=", "'Command to run on matching instance(s)'", ")", "parser", ".", "add_argument", "(", "'-y'", ",", "'--no-prompt'", ",", "action", "=", "'store_true'", ",", "default", "=", "False", ",", "help", "=", "\"Don't ask for confirmation before running a \"", "\"command\"", ")", "parser", ".", "add_argument", "(", "'-p'", ",", "'--profile'", ",", "type", "=", "str", ",", "help", "=", "'Profile to use (defined in ~/.lsi)'", ")", "parser", ".", "add_argument", "(", "'--show'", ",", "nargs", "=", "'+'", ",", "default", "=", "None", ",", "help", "=", "'Instance attributes to show'", ")", "parser", ".", "add_argument", "(", "'--only'", ",", "nargs", "=", "'+'", ",", "default", "=", "None", ",", "help", "=", "'Show ONLY these instance attributes'", ")", "parser", ".", "add_argument", "(", "'--sep'", ",", "type", "=", "str", ",", "default", "=", "None", ",", "help", "=", "'Simple output with given separator'", ")", "parser", ".", "add_argument", "(", "'--sort-by'", ",", "type", "=", "str", ",", "default", "=", "\"name\"", ",", "help", "=", "'What to sort list by'", ")", "parser", ".", "add_argument", "(", "'-L'", ",", "'--limit'", ",", "type", "=", "int", ",", "default", "=", "None", ",", "help", "=", "'Show at most this many entries'", ")", "parser", ".", "add_argument", "(", "'--attributes'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Show all available attributes'", ")", "parser", ".", "add_argument", "(", "'--get'", ",", "nargs", "=", "2", ",", "default", "=", "None", ",", "help", "=", "'Get files from matching instances, must be '", "'followed by the source and destination filenames'", ")", "parser", ".", "add_argument", "(", "'--put'", ",", "nargs", "=", "2", ",", "default", "=", "None", ",", "help", "=", "'Put a local file on matching instances, must be '", "'followed by the source and destination filenames'", ")", "parser", ".", "add_argument", "(", "'-t'", ",", "'--tunnel'", ",", "default", "=", "None", ",", "help", "=", "'Connect via the tunneled host.'", ")", "parser", ".", "add_argument", "(", "\"-r\"", ",", "\"--random\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Choose a random instance from within results.\"", ")", "parser", ".", "add_argument", "(", "\"-n\"", ",", "\"--num\"", ",", "type", "=", "int", ",", "default", "=", "None", ",", "help", "=", "\"Choose the given number from within results.\"", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "exclude", "is", "None", ":", "args", ".", "exclude", "=", "[", "]", "# Presumably, if someone is sorting by something, they want to show that", "# thing...", "if", "args", ".", "sort_by", "is", "not", "None", ":", "args", ".", "show", "=", "(", "args", ".", "show", "or", "[", "]", ")", "+", "[", "args", ".", "sort_by", "]", "return", "args" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
LsiProfile.load
Loads the user's LSI profile, or provides a default.
src/lsi/lsi.py
def load(cls, profile_name=None): """Loads the user's LSI profile, or provides a default.""" lsi_location = os.path.expanduser('~/.lsi') if not os.path.exists(lsi_location): return LsiProfile() cfg_parser = ConfigParser() cfg_parser.read(lsi_location) if profile_name is None: # Load the default profile if one exists; otherwise return empty. if cfg_parser.has_section('default'): profile_name = 'default' else: return cls() elif not cfg_parser.has_section(profile_name): raise cls.LoadError('No such profile {}'.format(profile_name)) def _get(option, alt=None): """Gets an option if it exists; else returns `alt`.""" if cfg_parser.has_option(profile_name, option): return cfg_parser.get(profile_name, option) else: return alt if cfg_parser.has_option(profile_name, 'inherit'): profile = cls.load(cfg_parser.get(profile_name, 'inherit')) else: profile = cls() profile.override('username', _get('username')) profile.override('identity_file', _get('identity file')) profile.override('command', _get('command')) filters = [s for s in _get('filters', '').split(',') if len(s) > 0] exclude = [s for s in _get('exclude', '').split(',') if len(s) > 0] profile.filters.extend(filters) profile.exclude.extend(exclude) return profile
def load(cls, profile_name=None): """Loads the user's LSI profile, or provides a default.""" lsi_location = os.path.expanduser('~/.lsi') if not os.path.exists(lsi_location): return LsiProfile() cfg_parser = ConfigParser() cfg_parser.read(lsi_location) if profile_name is None: # Load the default profile if one exists; otherwise return empty. if cfg_parser.has_section('default'): profile_name = 'default' else: return cls() elif not cfg_parser.has_section(profile_name): raise cls.LoadError('No such profile {}'.format(profile_name)) def _get(option, alt=None): """Gets an option if it exists; else returns `alt`.""" if cfg_parser.has_option(profile_name, option): return cfg_parser.get(profile_name, option) else: return alt if cfg_parser.has_option(profile_name, 'inherit'): profile = cls.load(cfg_parser.get(profile_name, 'inherit')) else: profile = cls() profile.override('username', _get('username')) profile.override('identity_file', _get('identity file')) profile.override('command', _get('command')) filters = [s for s in _get('filters', '').split(',') if len(s) > 0] exclude = [s for s in _get('exclude', '').split(',') if len(s) > 0] profile.filters.extend(filters) profile.exclude.extend(exclude) return profile
[ "Loads", "the", "user", "s", "LSI", "profile", "or", "provides", "a", "default", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L142-L174
[ "def", "load", "(", "cls", ",", "profile_name", "=", "None", ")", ":", "lsi_location", "=", "os", ".", "path", ".", "expanduser", "(", "'~/.lsi'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "lsi_location", ")", ":", "return", "LsiProfile", "(", ")", "cfg_parser", "=", "ConfigParser", "(", ")", "cfg_parser", ".", "read", "(", "lsi_location", ")", "if", "profile_name", "is", "None", ":", "# Load the default profile if one exists; otherwise return empty.", "if", "cfg_parser", ".", "has_section", "(", "'default'", ")", ":", "profile_name", "=", "'default'", "else", ":", "return", "cls", "(", ")", "elif", "not", "cfg_parser", ".", "has_section", "(", "profile_name", ")", ":", "raise", "cls", ".", "LoadError", "(", "'No such profile {}'", ".", "format", "(", "profile_name", ")", ")", "def", "_get", "(", "option", ",", "alt", "=", "None", ")", ":", "\"\"\"Gets an option if it exists; else returns `alt`.\"\"\"", "if", "cfg_parser", ".", "has_option", "(", "profile_name", ",", "option", ")", ":", "return", "cfg_parser", ".", "get", "(", "profile_name", ",", "option", ")", "else", ":", "return", "alt", "if", "cfg_parser", ".", "has_option", "(", "profile_name", ",", "'inherit'", ")", ":", "profile", "=", "cls", ".", "load", "(", "cfg_parser", ".", "get", "(", "profile_name", ",", "'inherit'", ")", ")", "else", ":", "profile", "=", "cls", "(", ")", "profile", ".", "override", "(", "'username'", ",", "_get", "(", "'username'", ")", ")", "profile", ".", "override", "(", "'identity_file'", ",", "_get", "(", "'identity file'", ")", ")", "profile", ".", "override", "(", "'command'", ",", "_get", "(", "'command'", ")", ")", "filters", "=", "[", "s", "for", "s", "in", "_get", "(", "'filters'", ",", "''", ")", ".", "split", "(", "','", ")", "if", "len", "(", "s", ")", ">", "0", "]", "exclude", "=", "[", "s", "for", "s", "in", "_get", "(", "'exclude'", ",", "''", ")", ".", "split", "(", "','", ")", "if", "len", "(", "s", ")", ">", "0", "]", "profile", ".", "filters", ".", "extend", "(", "filters", ")", "profile", ".", "exclude", ".", "extend", "(", "exclude", ")", "return", "profile" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
LsiProfile.from_args
Takes arguments parsed from argparse and returns a profile.
src/lsi/lsi.py
def from_args(args): """Takes arguments parsed from argparse and returns a profile.""" # If the args specify a username explicitly, don't load from file. if args.username is not None or args.identity_file is not None: profile = LsiProfile() else: profile = LsiProfile.load(args.profile) profile.override('username', args.username) profile.override('identity_file', args.identity_file) profile.override('command', args.command) profile.no_prompt = args.no_prompt profile.filters.extend(args.filters) profile.exclude.extend(args.exclude) if profile.identity_file is not None: profile.identity_file = os.path.expanduser(profile.identity_file) return profile
def from_args(args): """Takes arguments parsed from argparse and returns a profile.""" # If the args specify a username explicitly, don't load from file. if args.username is not None or args.identity_file is not None: profile = LsiProfile() else: profile = LsiProfile.load(args.profile) profile.override('username', args.username) profile.override('identity_file', args.identity_file) profile.override('command', args.command) profile.no_prompt = args.no_prompt profile.filters.extend(args.filters) profile.exclude.extend(args.exclude) if profile.identity_file is not None: profile.identity_file = os.path.expanduser(profile.identity_file) return profile
[ "Takes", "arguments", "parsed", "from", "argparse", "and", "returns", "a", "profile", "." ]
NarrativeScience/lsi
python
https://github.com/NarrativeScience/lsi/blob/7d901b03fdb1a34ef795e5412bfe9685d948e32d/src/lsi/lsi.py#L177-L192
[ "def", "from_args", "(", "args", ")", ":", "# If the args specify a username explicitly, don't load from file.", "if", "args", ".", "username", "is", "not", "None", "or", "args", ".", "identity_file", "is", "not", "None", ":", "profile", "=", "LsiProfile", "(", ")", "else", ":", "profile", "=", "LsiProfile", ".", "load", "(", "args", ".", "profile", ")", "profile", ".", "override", "(", "'username'", ",", "args", ".", "username", ")", "profile", ".", "override", "(", "'identity_file'", ",", "args", ".", "identity_file", ")", "profile", ".", "override", "(", "'command'", ",", "args", ".", "command", ")", "profile", ".", "no_prompt", "=", "args", ".", "no_prompt", "profile", ".", "filters", ".", "extend", "(", "args", ".", "filters", ")", "profile", ".", "exclude", ".", "extend", "(", "args", ".", "exclude", ")", "if", "profile", ".", "identity_file", "is", "not", "None", ":", "profile", ".", "identity_file", "=", "os", ".", "path", ".", "expanduser", "(", "profile", ".", "identity_file", ")", "return", "profile" ]
7d901b03fdb1a34ef795e5412bfe9685d948e32d
test
dicto.merge_
Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``self``. :param self: dict onto which the merge is executed :param merge_dct: self merged into self :return: None
dicto/dicto_legacy.py
def merge_(self, merge_dct): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``self``. :param self: dict onto which the merge is executed :param merge_dct: self merged into self :return: None """ for k, v in merge_dct.items(): if (k in self and isinstance(self[k], dict) and isinstance(merge_dct[k], collections.Mapping)): self[k].merge_(dicto(merge_dct[k])) else: self[k] = merge_dct[k] return self
def merge_(self, merge_dct): """ Recursive dict merge. Inspired by :meth:``dict.update()``, instead of updating only top-level keys, dict_merge recurses down into dicts nested to an arbitrary depth, updating keys. The ``merge_dct`` is merged into ``self``. :param self: dict onto which the merge is executed :param merge_dct: self merged into self :return: None """ for k, v in merge_dct.items(): if (k in self and isinstance(self[k], dict) and isinstance(merge_dct[k], collections.Mapping)): self[k].merge_(dicto(merge_dct[k])) else: self[k] = merge_dct[k] return self
[ "Recursive", "dict", "merge", ".", "Inspired", "by", ":", "meth", ":", "dict", ".", "update", "()", "instead", "of", "updating", "only", "top", "-", "level", "keys", "dict_merge", "recurses", "down", "into", "dicts", "nested", "to", "an", "arbitrary", "depth", "updating", "keys", ".", "The", "merge_dct", "is", "merged", "into", "self", ".", ":", "param", "self", ":", "dict", "onto", "which", "the", "merge", "is", "executed", ":", "param", "merge_dct", ":", "self", "merged", "into", "self", ":", "return", ":", "None" ]
cgarciae/dicto
python
https://github.com/cgarciae/dicto/blob/fee67e1abcf2538455fee62414c34eb2354bdafa/dicto/dicto_legacy.py#L54-L70
[ "def", "merge_", "(", "self", ",", "merge_dct", ")", ":", "for", "k", ",", "v", "in", "merge_dct", ".", "items", "(", ")", ":", "if", "(", "k", "in", "self", "and", "isinstance", "(", "self", "[", "k", "]", ",", "dict", ")", "and", "isinstance", "(", "merge_dct", "[", "k", "]", ",", "collections", ".", "Mapping", ")", ")", ":", "self", "[", "k", "]", ".", "merge_", "(", "dicto", "(", "merge_dct", "[", "k", "]", ")", ")", "else", ":", "self", "[", "k", "]", "=", "merge_dct", "[", "k", "]", "return", "self" ]
fee67e1abcf2538455fee62414c34eb2354bdafa
test
Relational.relate
Relate this package component to the supplied part.
openpack/basepack.py
def relate(self, part, id=None): """Relate this package component to the supplied part.""" assert part.name.startswith(self.base) name = part.name[len(self.base):].lstrip('/') rel = Relationship(self, name, part.rel_type, id=id) self.relationships.add(rel) return rel
def relate(self, part, id=None): """Relate this package component to the supplied part.""" assert part.name.startswith(self.base) name = part.name[len(self.base):].lstrip('/') rel = Relationship(self, name, part.rel_type, id=id) self.relationships.add(rel) return rel
[ "Relate", "this", "package", "component", "to", "the", "supplied", "part", "." ]
yougov/openpack
python
https://github.com/yougov/openpack/blob/1412ec34c1bab6ba6c8ae5490c2205d696f13717/openpack/basepack.py#L38-L44
[ "def", "relate", "(", "self", ",", "part", ",", "id", "=", "None", ")", ":", "assert", "part", ".", "name", ".", "startswith", "(", "self", ".", "base", ")", "name", "=", "part", ".", "name", "[", "len", "(", "self", ".", "base", ")", ":", "]", ".", "lstrip", "(", "'/'", ")", "rel", "=", "Relationship", "(", "self", ",", "name", ",", "part", ".", "rel_type", ",", "id", "=", "id", ")", "self", ".", "relationships", ".", "add", "(", "rel", ")", "return", "rel" ]
1412ec34c1bab6ba6c8ae5490c2205d696f13717