repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
paramiko/paramiko
paramiko/packet.py
Packetizer.set_inbound_cipher
def set_inbound_cipher( self, block_engine, block_size, mac_engine, mac_size, mac_key ): """ Switch inbound data cipher. """ self.__block_engine_in = block_engine self.__block_size_in = block_size self.__mac_engine_in = mac_engine self.__mac_size_in = mac_size self.__mac_key_in = mac_key self.__received_bytes = 0 self.__received_packets = 0 self.__received_bytes_overflow = 0 self.__received_packets_overflow = 0 # wait until the reset happens in both directions before clearing # rekey flag self.__init_count |= 2 if self.__init_count == 3: self.__init_count = 0 self.__need_rekey = False
python
def set_inbound_cipher( self, block_engine, block_size, mac_engine, mac_size, mac_key ): """ Switch inbound data cipher. """ self.__block_engine_in = block_engine self.__block_size_in = block_size self.__mac_engine_in = mac_engine self.__mac_size_in = mac_size self.__mac_key_in = mac_key self.__received_bytes = 0 self.__received_packets = 0 self.__received_bytes_overflow = 0 self.__received_packets_overflow = 0 # wait until the reset happens in both directions before clearing # rekey flag self.__init_count |= 2 if self.__init_count == 3: self.__init_count = 0 self.__need_rekey = False
[ "def", "set_inbound_cipher", "(", "self", ",", "block_engine", ",", "block_size", ",", "mac_engine", ",", "mac_size", ",", "mac_key", ")", ":", "self", ".", "__block_engine_in", "=", "block_engine", "self", ".", "__block_size_in", "=", "block_size", "self", ".", "__mac_engine_in", "=", "mac_engine", "self", ".", "__mac_size_in", "=", "mac_size", "self", ".", "__mac_key_in", "=", "mac_key", "self", ".", "__received_bytes", "=", "0", "self", ".", "__received_packets", "=", "0", "self", ".", "__received_bytes_overflow", "=", "0", "self", ".", "__received_packets_overflow", "=", "0", "# wait until the reset happens in both directions before clearing", "# rekey flag", "self", ".", "__init_count", "|=", "2", "if", "self", ".", "__init_count", "==", "3", ":", "self", ".", "__init_count", "=", "0", "self", ".", "__need_rekey", "=", "False" ]
Switch inbound data cipher.
[ "Switch", "inbound", "data", "cipher", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L164-L184
train
paramiko/paramiko
paramiko/packet.py
Packetizer.set_keepalive
def set_keepalive(self, interval, callback): """ Turn on/off the callback keepalive. If ``interval`` seconds pass with no data read from or written to the socket, the callback will be executed and the timer will be reset. """ self.__keepalive_interval = interval self.__keepalive_callback = callback self.__keepalive_last = time.time()
python
def set_keepalive(self, interval, callback): """ Turn on/off the callback keepalive. If ``interval`` seconds pass with no data read from or written to the socket, the callback will be executed and the timer will be reset. """ self.__keepalive_interval = interval self.__keepalive_callback = callback self.__keepalive_last = time.time()
[ "def", "set_keepalive", "(", "self", ",", "interval", ",", "callback", ")", ":", "self", ".", "__keepalive_interval", "=", "interval", "self", ".", "__keepalive_callback", "=", "callback", "self", ".", "__keepalive_last", "=", "time", ".", "time", "(", ")" ]
Turn on/off the callback keepalive. If ``interval`` seconds pass with no data read from or written to the socket, the callback will be executed and the timer will be reset.
[ "Turn", "on", "/", "off", "the", "callback", "keepalive", ".", "If", "interval", "seconds", "pass", "with", "no", "data", "read", "from", "or", "written", "to", "the", "socket", "the", "callback", "will", "be", "executed", "and", "the", "timer", "will", "be", "reset", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L216-L224
train
paramiko/paramiko
paramiko/packet.py
Packetizer.start_handshake
def start_handshake(self, timeout): """ Tells `Packetizer` that the handshake process started. Starts a book keeping timer that can signal a timeout in the handshake process. :param float timeout: amount of seconds to wait before timing out """ if not self.__timer: self.__timer = threading.Timer(float(timeout), self.read_timer) self.__timer.start()
python
def start_handshake(self, timeout): """ Tells `Packetizer` that the handshake process started. Starts a book keeping timer that can signal a timeout in the handshake process. :param float timeout: amount of seconds to wait before timing out """ if not self.__timer: self.__timer = threading.Timer(float(timeout), self.read_timer) self.__timer.start()
[ "def", "start_handshake", "(", "self", ",", "timeout", ")", ":", "if", "not", "self", ".", "__timer", ":", "self", ".", "__timer", "=", "threading", ".", "Timer", "(", "float", "(", "timeout", ")", ",", "self", ".", "read_timer", ")", "self", ".", "__timer", ".", "start", "(", ")" ]
Tells `Packetizer` that the handshake process started. Starts a book keeping timer that can signal a timeout in the handshake process. :param float timeout: amount of seconds to wait before timing out
[ "Tells", "Packetizer", "that", "the", "handshake", "process", "started", ".", "Starts", "a", "book", "keeping", "timer", "that", "can", "signal", "a", "timeout", "in", "the", "handshake", "process", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L229-L239
train
paramiko/paramiko
paramiko/packet.py
Packetizer.handshake_timed_out
def handshake_timed_out(self): """ Checks if the handshake has timed out. If `start_handshake` wasn't called before the call to this function, the return value will always be `False`. If the handshake completed before a timeout was reached, the return value will be `False` :return: handshake time out status, as a `bool` """ if not self.__timer: return False if self.__handshake_complete: return False return self.__timer_expired
python
def handshake_timed_out(self): """ Checks if the handshake has timed out. If `start_handshake` wasn't called before the call to this function, the return value will always be `False`. If the handshake completed before a timeout was reached, the return value will be `False` :return: handshake time out status, as a `bool` """ if not self.__timer: return False if self.__handshake_complete: return False return self.__timer_expired
[ "def", "handshake_timed_out", "(", "self", ")", ":", "if", "not", "self", ".", "__timer", ":", "return", "False", "if", "self", ".", "__handshake_complete", ":", "return", "False", "return", "self", ".", "__timer_expired" ]
Checks if the handshake has timed out. If `start_handshake` wasn't called before the call to this function, the return value will always be `False`. If the handshake completed before a timeout was reached, the return value will be `False` :return: handshake time out status, as a `bool`
[ "Checks", "if", "the", "handshake", "has", "timed", "out", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L241-L255
train
paramiko/paramiko
paramiko/packet.py
Packetizer.complete_handshake
def complete_handshake(self): """ Tells `Packetizer` that the handshake has completed. """ if self.__timer: self.__timer.cancel() self.__timer_expired = False self.__handshake_complete = True
python
def complete_handshake(self): """ Tells `Packetizer` that the handshake has completed. """ if self.__timer: self.__timer.cancel() self.__timer_expired = False self.__handshake_complete = True
[ "def", "complete_handshake", "(", "self", ")", ":", "if", "self", ".", "__timer", ":", "self", ".", "__timer", ".", "cancel", "(", ")", "self", ".", "__timer_expired", "=", "False", "self", ".", "__handshake_complete", "=", "True" ]
Tells `Packetizer` that the handshake has completed.
[ "Tells", "Packetizer", "that", "the", "handshake", "has", "completed", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L257-L264
train
paramiko/paramiko
paramiko/sftp_handle.py
SFTPHandle.close
def close(self): """ When a client closes a file, this method is called on the handle. Normally you would use this method to close the underlying OS level file object(s). The default implementation checks for attributes on ``self`` named ``readfile`` and/or ``writefile``, and if either or both are present, their ``close()`` methods are called. This means that if you are using the default implementations of `read` and `write`, this method's default implementation should be fine also. """ readfile = getattr(self, "readfile", None) if readfile is not None: readfile.close() writefile = getattr(self, "writefile", None) if writefile is not None: writefile.close()
python
def close(self): """ When a client closes a file, this method is called on the handle. Normally you would use this method to close the underlying OS level file object(s). The default implementation checks for attributes on ``self`` named ``readfile`` and/or ``writefile``, and if either or both are present, their ``close()`` methods are called. This means that if you are using the default implementations of `read` and `write`, this method's default implementation should be fine also. """ readfile = getattr(self, "readfile", None) if readfile is not None: readfile.close() writefile = getattr(self, "writefile", None) if writefile is not None: writefile.close()
[ "def", "close", "(", "self", ")", ":", "readfile", "=", "getattr", "(", "self", ",", "\"readfile\"", ",", "None", ")", "if", "readfile", "is", "not", "None", ":", "readfile", ".", "close", "(", ")", "writefile", "=", "getattr", "(", "self", ",", "\"writefile\"", ",", "None", ")", "if", "writefile", "is", "not", "None", ":", "writefile", ".", "close", "(", ")" ]
When a client closes a file, this method is called on the handle. Normally you would use this method to close the underlying OS level file object(s). The default implementation checks for attributes on ``self`` named ``readfile`` and/or ``writefile``, and if either or both are present, their ``close()`` methods are called. This means that if you are using the default implementations of `read` and `write`, this method's default implementation should be fine also.
[ "When", "a", "client", "closes", "a", "file", "this", "method", "is", "called", "on", "the", "handle", ".", "Normally", "you", "would", "use", "this", "method", "to", "close", "the", "underlying", "OS", "level", "file", "object", "(", "s", ")", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_handle.py#L55-L72
train
paramiko/paramiko
paramiko/sftp_handle.py
SFTPHandle._get_next_files
def _get_next_files(self): """ Used by the SFTP server code to retrieve a cached directory listing. """ fnlist = self.__files[:16] self.__files = self.__files[16:] return fnlist
python
def _get_next_files(self): """ Used by the SFTP server code to retrieve a cached directory listing. """ fnlist = self.__files[:16] self.__files = self.__files[16:] return fnlist
[ "def", "_get_next_files", "(", "self", ")", ":", "fnlist", "=", "self", ".", "__files", "[", ":", "16", "]", "self", ".", "__files", "=", "self", ".", "__files", "[", "16", ":", "]", "return", "fnlist" ]
Used by the SFTP server code to retrieve a cached directory listing.
[ "Used", "by", "the", "SFTP", "server", "code", "to", "retrieve", "a", "cached", "directory", "listing", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_handle.py#L180-L187
train
paramiko/paramiko
paramiko/util.py
generate_key_bytes
def generate_key_bytes(hash_alg, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. :param function hash_alg: A function which creates a new hash object, such as ``hashlib.sha256``. :param salt: data to salt the hash with. :type salt: byte string :param str key: human-entered password or passphrase. :param int nbytes: number of bytes to generate. :return: Key data `str` """ keydata = bytes() digest = bytes() if len(salt) > 8: salt = salt[:8] while nbytes > 0: hash_obj = hash_alg() if len(digest) > 0: hash_obj.update(digest) hash_obj.update(b(key)) hash_obj.update(salt) digest = hash_obj.digest() size = min(nbytes, len(digest)) keydata += digest[:size] nbytes -= size return keydata
python
def generate_key_bytes(hash_alg, salt, key, nbytes): """ Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. :param function hash_alg: A function which creates a new hash object, such as ``hashlib.sha256``. :param salt: data to salt the hash with. :type salt: byte string :param str key: human-entered password or passphrase. :param int nbytes: number of bytes to generate. :return: Key data `str` """ keydata = bytes() digest = bytes() if len(salt) > 8: salt = salt[:8] while nbytes > 0: hash_obj = hash_alg() if len(digest) > 0: hash_obj.update(digest) hash_obj.update(b(key)) hash_obj.update(salt) digest = hash_obj.digest() size = min(nbytes, len(digest)) keydata += digest[:size] nbytes -= size return keydata
[ "def", "generate_key_bytes", "(", "hash_alg", ",", "salt", ",", "key", ",", "nbytes", ")", ":", "keydata", "=", "bytes", "(", ")", "digest", "=", "bytes", "(", ")", "if", "len", "(", "salt", ")", ">", "8", ":", "salt", "=", "salt", "[", ":", "8", "]", "while", "nbytes", ">", "0", ":", "hash_obj", "=", "hash_alg", "(", ")", "if", "len", "(", "digest", ")", ">", "0", ":", "hash_obj", ".", "update", "(", "digest", ")", "hash_obj", ".", "update", "(", "b", "(", "key", ")", ")", "hash_obj", ".", "update", "(", "salt", ")", "digest", "=", "hash_obj", ".", "digest", "(", ")", "size", "=", "min", "(", "nbytes", ",", "len", "(", "digest", ")", ")", "keydata", "+=", "digest", "[", ":", "size", "]", "nbytes", "-=", "size", "return", "keydata" ]
Given a password, passphrase, or other human-source key, scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/decrypting private key files. :param function hash_alg: A function which creates a new hash object, such as ``hashlib.sha256``. :param salt: data to salt the hash with. :type salt: byte string :param str key: human-entered password or passphrase. :param int nbytes: number of bytes to generate. :return: Key data `str`
[ "Given", "a", "password", "passphrase", "or", "other", "human", "-", "source", "key", "scramble", "it", "through", "a", "secure", "hash", "into", "some", "keyworthy", "bytes", ".", "This", "specific", "algorithm", "is", "used", "for", "encrypting", "/", "decrypting", "private", "key", "files", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/util.py#L142-L170
train
paramiko/paramiko
paramiko/util.py
log_to_file
def log_to_file(filename, level=DEBUG): """send paramiko logs to a logfile, if they're not already going somewhere""" logger = logging.getLogger("paramiko") if len(logger.handlers) > 0: return logger.setLevel(level) f = open(filename, "a") handler = logging.StreamHandler(f) frm = "%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d" frm += " %(name)s: %(message)s" handler.setFormatter(logging.Formatter(frm, "%Y%m%d-%H:%M:%S")) logger.addHandler(handler)
python
def log_to_file(filename, level=DEBUG): """send paramiko logs to a logfile, if they're not already going somewhere""" logger = logging.getLogger("paramiko") if len(logger.handlers) > 0: return logger.setLevel(level) f = open(filename, "a") handler = logging.StreamHandler(f) frm = "%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d" frm += " %(name)s: %(message)s" handler.setFormatter(logging.Formatter(frm, "%Y%m%d-%H:%M:%S")) logger.addHandler(handler)
[ "def", "log_to_file", "(", "filename", ",", "level", "=", "DEBUG", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"paramiko\"", ")", "if", "len", "(", "logger", ".", "handlers", ")", ">", "0", ":", "return", "logger", ".", "setLevel", "(", "level", ")", "f", "=", "open", "(", "filename", ",", "\"a\"", ")", "handler", "=", "logging", ".", "StreamHandler", "(", "f", ")", "frm", "=", "\"%(levelname)-.3s [%(asctime)s.%(msecs)03d] thr=%(_threadid)-3d\"", "frm", "+=", "\" %(name)s: %(message)s\"", "handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "frm", ",", "\"%Y%m%d-%H:%M:%S\"", ")", ")", "logger", ".", "addHandler", "(", "handler", ")" ]
send paramiko logs to a logfile, if they're not already going somewhere
[ "send", "paramiko", "logs", "to", "a", "logfile", "if", "they", "re", "not", "already", "going", "somewhere" ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/util.py#L245-L257
train
paramiko/paramiko
paramiko/proxy.py
ProxyCommand.send
def send(self, content): """ Write the content received from the SSH client to the standard input of the forked command. :param str content: string to be sent to the forked command """ try: self.process.stdin.write(content) except IOError as e: # There was a problem with the child process. It probably # died and we can't proceed. The best option here is to # raise an exception informing the user that the informed # ProxyCommand is not working. raise ProxyCommandFailure(" ".join(self.cmd), e.strerror) return len(content)
python
def send(self, content): """ Write the content received from the SSH client to the standard input of the forked command. :param str content: string to be sent to the forked command """ try: self.process.stdin.write(content) except IOError as e: # There was a problem with the child process. It probably # died and we can't proceed. The best option here is to # raise an exception informing the user that the informed # ProxyCommand is not working. raise ProxyCommandFailure(" ".join(self.cmd), e.strerror) return len(content)
[ "def", "send", "(", "self", ",", "content", ")", ":", "try", ":", "self", ".", "process", ".", "stdin", ".", "write", "(", "content", ")", "except", "IOError", "as", "e", ":", "# There was a problem with the child process. It probably", "# died and we can't proceed. The best option here is to", "# raise an exception informing the user that the informed", "# ProxyCommand is not working.", "raise", "ProxyCommandFailure", "(", "\" \"", ".", "join", "(", "self", ".", "cmd", ")", ",", "e", ".", "strerror", ")", "return", "len", "(", "content", ")" ]
Write the content received from the SSH client to the standard input of the forked command. :param str content: string to be sent to the forked command
[ "Write", "the", "content", "received", "from", "the", "SSH", "client", "to", "the", "standard", "input", "of", "the", "forked", "command", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/proxy.py#L61-L76
train
paramiko/paramiko
paramiko/proxy.py
ProxyCommand.recv
def recv(self, size): """ Read from the standard output of the forked program. :param int size: how many chars should be read :return: the string of bytes read, which may be shorter than requested """ try: buffer = b"" start = time.time() while len(buffer) < size: select_timeout = None if self.timeout is not None: elapsed = time.time() - start if elapsed >= self.timeout: raise socket.timeout() select_timeout = self.timeout - elapsed r, w, x = select([self.process.stdout], [], [], select_timeout) if r and r[0] == self.process.stdout: buffer += os.read( self.process.stdout.fileno(), size - len(buffer) ) return buffer except socket.timeout: if buffer: # Don't raise socket.timeout, return partial result instead return buffer raise # socket.timeout is a subclass of IOError except IOError as e: raise ProxyCommandFailure(" ".join(self.cmd), e.strerror)
python
def recv(self, size): """ Read from the standard output of the forked program. :param int size: how many chars should be read :return: the string of bytes read, which may be shorter than requested """ try: buffer = b"" start = time.time() while len(buffer) < size: select_timeout = None if self.timeout is not None: elapsed = time.time() - start if elapsed >= self.timeout: raise socket.timeout() select_timeout = self.timeout - elapsed r, w, x = select([self.process.stdout], [], [], select_timeout) if r and r[0] == self.process.stdout: buffer += os.read( self.process.stdout.fileno(), size - len(buffer) ) return buffer except socket.timeout: if buffer: # Don't raise socket.timeout, return partial result instead return buffer raise # socket.timeout is a subclass of IOError except IOError as e: raise ProxyCommandFailure(" ".join(self.cmd), e.strerror)
[ "def", "recv", "(", "self", ",", "size", ")", ":", "try", ":", "buffer", "=", "b\"\"", "start", "=", "time", ".", "time", "(", ")", "while", "len", "(", "buffer", ")", "<", "size", ":", "select_timeout", "=", "None", "if", "self", ".", "timeout", "is", "not", "None", ":", "elapsed", "=", "time", ".", "time", "(", ")", "-", "start", "if", "elapsed", ">=", "self", ".", "timeout", ":", "raise", "socket", ".", "timeout", "(", ")", "select_timeout", "=", "self", ".", "timeout", "-", "elapsed", "r", ",", "w", ",", "x", "=", "select", "(", "[", "self", ".", "process", ".", "stdout", "]", ",", "[", "]", ",", "[", "]", ",", "select_timeout", ")", "if", "r", "and", "r", "[", "0", "]", "==", "self", ".", "process", ".", "stdout", ":", "buffer", "+=", "os", ".", "read", "(", "self", ".", "process", ".", "stdout", ".", "fileno", "(", ")", ",", "size", "-", "len", "(", "buffer", ")", ")", "return", "buffer", "except", "socket", ".", "timeout", ":", "if", "buffer", ":", "# Don't raise socket.timeout, return partial result instead", "return", "buffer", "raise", "# socket.timeout is a subclass of IOError", "except", "IOError", "as", "e", ":", "raise", "ProxyCommandFailure", "(", "\" \"", ".", "join", "(", "self", ".", "cmd", ")", ",", "e", ".", "strerror", ")" ]
Read from the standard output of the forked program. :param int size: how many chars should be read :return: the string of bytes read, which may be shorter than requested
[ "Read", "from", "the", "standard", "output", "of", "the", "forked", "program", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/proxy.py#L78-L109
train
paramiko/paramiko
paramiko/_winapi.py
format_system_message
def format_system_message(errno): """ Call FormatMessage with a system error number to retrieve the descriptive error message. """ # first some flags used by FormatMessageW ALLOCATE_BUFFER = 0x100 FROM_SYSTEM = 0x1000 # Let FormatMessageW allocate the buffer (we'll free it below) # Also, let it know we want a system error message. flags = ALLOCATE_BUFFER | FROM_SYSTEM source = None message_id = errno language_id = 0 result_buffer = ctypes.wintypes.LPWSTR() buffer_size = 0 arguments = None bytes = ctypes.windll.kernel32.FormatMessageW( flags, source, message_id, language_id, ctypes.byref(result_buffer), buffer_size, arguments, ) # note the following will cause an infinite loop if GetLastError # repeatedly returns an error that cannot be formatted, although # this should not happen. handle_nonzero_success(bytes) message = result_buffer.value ctypes.windll.kernel32.LocalFree(result_buffer) return message
python
def format_system_message(errno): """ Call FormatMessage with a system error number to retrieve the descriptive error message. """ # first some flags used by FormatMessageW ALLOCATE_BUFFER = 0x100 FROM_SYSTEM = 0x1000 # Let FormatMessageW allocate the buffer (we'll free it below) # Also, let it know we want a system error message. flags = ALLOCATE_BUFFER | FROM_SYSTEM source = None message_id = errno language_id = 0 result_buffer = ctypes.wintypes.LPWSTR() buffer_size = 0 arguments = None bytes = ctypes.windll.kernel32.FormatMessageW( flags, source, message_id, language_id, ctypes.byref(result_buffer), buffer_size, arguments, ) # note the following will cause an infinite loop if GetLastError # repeatedly returns an error that cannot be formatted, although # this should not happen. handle_nonzero_success(bytes) message = result_buffer.value ctypes.windll.kernel32.LocalFree(result_buffer) return message
[ "def", "format_system_message", "(", "errno", ")", ":", "# first some flags used by FormatMessageW", "ALLOCATE_BUFFER", "=", "0x100", "FROM_SYSTEM", "=", "0x1000", "# Let FormatMessageW allocate the buffer (we'll free it below)", "# Also, let it know we want a system error message.", "flags", "=", "ALLOCATE_BUFFER", "|", "FROM_SYSTEM", "source", "=", "None", "message_id", "=", "errno", "language_id", "=", "0", "result_buffer", "=", "ctypes", ".", "wintypes", ".", "LPWSTR", "(", ")", "buffer_size", "=", "0", "arguments", "=", "None", "bytes", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "FormatMessageW", "(", "flags", ",", "source", ",", "message_id", ",", "language_id", ",", "ctypes", ".", "byref", "(", "result_buffer", ")", ",", "buffer_size", ",", "arguments", ",", ")", "# note the following will cause an infinite loop if GetLastError", "# repeatedly returns an error that cannot be formatted, although", "# this should not happen.", "handle_nonzero_success", "(", "bytes", ")", "message", "=", "result_buffer", ".", "value", "ctypes", ".", "windll", ".", "kernel32", ".", "LocalFree", "(", "result_buffer", ")", "return", "message" ]
Call FormatMessage with a system error number to retrieve the descriptive error message.
[ "Call", "FormatMessage", "with", "a", "system", "error", "number", "to", "retrieve", "the", "descriptive", "error", "message", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/_winapi.py#L19-L52
train
paramiko/paramiko
paramiko/_winapi.py
GetTokenInformation
def GetTokenInformation(token, information_class): """ Given a token, get the token information for it. """ data_size = ctypes.wintypes.DWORD() ctypes.windll.advapi32.GetTokenInformation( token, information_class.num, 0, 0, ctypes.byref(data_size) ) data = ctypes.create_string_buffer(data_size.value) handle_nonzero_success( ctypes.windll.advapi32.GetTokenInformation( token, information_class.num, ctypes.byref(data), ctypes.sizeof(data), ctypes.byref(data_size), ) ) return ctypes.cast(data, ctypes.POINTER(TOKEN_USER)).contents
python
def GetTokenInformation(token, information_class): """ Given a token, get the token information for it. """ data_size = ctypes.wintypes.DWORD() ctypes.windll.advapi32.GetTokenInformation( token, information_class.num, 0, 0, ctypes.byref(data_size) ) data = ctypes.create_string_buffer(data_size.value) handle_nonzero_success( ctypes.windll.advapi32.GetTokenInformation( token, information_class.num, ctypes.byref(data), ctypes.sizeof(data), ctypes.byref(data_size), ) ) return ctypes.cast(data, ctypes.POINTER(TOKEN_USER)).contents
[ "def", "GetTokenInformation", "(", "token", ",", "information_class", ")", ":", "data_size", "=", "ctypes", ".", "wintypes", ".", "DWORD", "(", ")", "ctypes", ".", "windll", ".", "advapi32", ".", "GetTokenInformation", "(", "token", ",", "information_class", ".", "num", ",", "0", ",", "0", ",", "ctypes", ".", "byref", "(", "data_size", ")", ")", "data", "=", "ctypes", ".", "create_string_buffer", "(", "data_size", ".", "value", ")", "handle_nonzero_success", "(", "ctypes", ".", "windll", ".", "advapi32", ".", "GetTokenInformation", "(", "token", ",", "information_class", ".", "num", ",", "ctypes", ".", "byref", "(", "data", ")", ",", "ctypes", ".", "sizeof", "(", "data", ")", ",", "ctypes", ".", "byref", "(", "data_size", ")", ",", ")", ")", "return", "ctypes", ".", "cast", "(", "data", ",", "ctypes", ".", "POINTER", "(", "TOKEN_USER", ")", ")", ".", "contents" ]
Given a token, get the token information for it.
[ "Given", "a", "token", "get", "the", "token", "information", "for", "it", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/_winapi.py#L351-L369
train
paramiko/paramiko
paramiko/_winapi.py
get_current_user
def get_current_user(): """ Return a TOKEN_USER for the owner of this process. """ process = OpenProcessToken( ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY ) return GetTokenInformation(process, TOKEN_USER)
python
def get_current_user(): """ Return a TOKEN_USER for the owner of this process. """ process = OpenProcessToken( ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY ) return GetTokenInformation(process, TOKEN_USER)
[ "def", "get_current_user", "(", ")", ":", "process", "=", "OpenProcessToken", "(", "ctypes", ".", "windll", ".", "kernel32", ".", "GetCurrentProcess", "(", ")", ",", "TokenAccess", ".", "TOKEN_QUERY", ")", "return", "GetTokenInformation", "(", "process", ",", "TOKEN_USER", ")" ]
Return a TOKEN_USER for the owner of this process.
[ "Return", "a", "TOKEN_USER", "for", "the", "owner", "of", "this", "process", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/_winapi.py#L383-L390
train
paramiko/paramiko
paramiko/dsskey.py
DSSKey.generate
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param progress_func: Unused :return: new `.DSSKey` private key """ numbers = dsa.generate_private_key( bits, backend=default_backend() ).private_numbers() key = DSSKey( vals=( numbers.public_numbers.parameter_numbers.p, numbers.public_numbers.parameter_numbers.q, numbers.public_numbers.parameter_numbers.g, numbers.public_numbers.y, ) ) key.x = numbers.x return key
python
def generate(bits=1024, progress_func=None): """ Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param progress_func: Unused :return: new `.DSSKey` private key """ numbers = dsa.generate_private_key( bits, backend=default_backend() ).private_numbers() key = DSSKey( vals=( numbers.public_numbers.parameter_numbers.p, numbers.public_numbers.parameter_numbers.q, numbers.public_numbers.parameter_numbers.g, numbers.public_numbers.y, ) ) key.x = numbers.x return key
[ "def", "generate", "(", "bits", "=", "1024", ",", "progress_func", "=", "None", ")", ":", "numbers", "=", "dsa", ".", "generate_private_key", "(", "bits", ",", "backend", "=", "default_backend", "(", ")", ")", ".", "private_numbers", "(", ")", "key", "=", "DSSKey", "(", "vals", "=", "(", "numbers", ".", "public_numbers", ".", "parameter_numbers", ".", "p", ",", "numbers", ".", "public_numbers", ".", "parameter_numbers", ".", "q", ",", "numbers", ".", "public_numbers", ".", "parameter_numbers", ".", "g", ",", "numbers", ".", "public_numbers", ".", "y", ",", ")", ")", "key", ".", "x", "=", "numbers", ".", "x", "return", "key" ]
Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. :param int bits: number of bits the generated key should be. :param progress_func: Unused :return: new `.DSSKey` private key
[ "Generate", "a", "new", "private", "DSS", "key", ".", "This", "factory", "function", "can", "be", "used", "to", "generate", "a", "new", "host", "key", "or", "authentication", "key", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/dsskey.py#L198-L219
train
paramiko/paramiko
paramiko/client.py
SSHClient.load_system_host_keys
def load_system_host_keys(self, filename=None): """ Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by `save_host_keys`. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). If ``filename`` is left as ``None``, an attempt will be made to read keys from the user's local "known hosts" file, as used by OpenSSH, and no exception will be raised if the file can't be read. This is probably only useful on posix. :param str filename: the filename to read, or ``None`` :raises: ``IOError`` -- if a filename was provided and the file could not be read """ if filename is None: # try the user's .ssh key file, and mask exceptions filename = os.path.expanduser("~/.ssh/known_hosts") try: self._system_host_keys.load(filename) except IOError: pass return self._system_host_keys.load(filename)
python
def load_system_host_keys(self, filename=None): """ Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by `save_host_keys`. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). If ``filename`` is left as ``None``, an attempt will be made to read keys from the user's local "known hosts" file, as used by OpenSSH, and no exception will be raised if the file can't be read. This is probably only useful on posix. :param str filename: the filename to read, or ``None`` :raises: ``IOError`` -- if a filename was provided and the file could not be read """ if filename is None: # try the user's .ssh key file, and mask exceptions filename = os.path.expanduser("~/.ssh/known_hosts") try: self._system_host_keys.load(filename) except IOError: pass return self._system_host_keys.load(filename)
[ "def", "load_system_host_keys", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "# try the user's .ssh key file, and mask exceptions", "filename", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/.ssh/known_hosts\"", ")", "try", ":", "self", ".", "_system_host_keys", ".", "load", "(", "filename", ")", "except", "IOError", ":", "pass", "return", "self", ".", "_system_host_keys", ".", "load", "(", "filename", ")" ]
Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by `save_host_keys`. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). If ``filename`` is left as ``None``, an attempt will be made to read keys from the user's local "known hosts" file, as used by OpenSSH, and no exception will be raised if the file can't be read. This is probably only useful on posix. :param str filename: the filename to read, or ``None`` :raises: ``IOError`` -- if a filename was provided and the file could not be read
[ "Load", "host", "keys", "from", "a", "system", "(", "read", "-", "only", ")", "file", ".", "Host", "keys", "read", "with", "this", "method", "will", "not", "be", "saved", "back", "by", "save_host_keys", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L81-L108
train
paramiko/paramiko
paramiko/client.py
SSHClient.load_host_keys
def load_host_keys(self, filename): """ Load host keys from a local host-key file. Host keys read with this method will be checked after keys loaded via `load_system_host_keys`, but will be saved back by `save_host_keys` (so they can be modified). The missing host key policy `.AutoAddPolicy` adds keys to this set and saves them, when connecting to a previously-unknown server. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used. :param str filename: the filename to read :raises: ``IOError`` -- if the filename could not be read """ self._host_keys_filename = filename self._host_keys.load(filename)
python
def load_host_keys(self, filename): """ Load host keys from a local host-key file. Host keys read with this method will be checked after keys loaded via `load_system_host_keys`, but will be saved back by `save_host_keys` (so they can be modified). The missing host key policy `.AutoAddPolicy` adds keys to this set and saves them, when connecting to a previously-unknown server. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used. :param str filename: the filename to read :raises: ``IOError`` -- if the filename could not be read """ self._host_keys_filename = filename self._host_keys.load(filename)
[ "def", "load_host_keys", "(", "self", ",", "filename", ")", ":", "self", ".", "_host_keys_filename", "=", "filename", "self", ".", "_host_keys", ".", "load", "(", "filename", ")" ]
Load host keys from a local host-key file. Host keys read with this method will be checked after keys loaded via `load_system_host_keys`, but will be saved back by `save_host_keys` (so they can be modified). The missing host key policy `.AutoAddPolicy` adds keys to this set and saves them, when connecting to a previously-unknown server. This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used. :param str filename: the filename to read :raises: ``IOError`` -- if the filename could not be read
[ "Load", "host", "keys", "from", "a", "local", "host", "-", "key", "file", ".", "Host", "keys", "read", "with", "this", "method", "will", "be", "checked", "after", "keys", "loaded", "via", "load_system_host_keys", "but", "will", "be", "saved", "back", "by", "save_host_keys", "(", "so", "they", "can", "be", "modified", ")", ".", "The", "missing", "host", "key", "policy", ".", "AutoAddPolicy", "adds", "keys", "to", "this", "set", "and", "saves", "them", "when", "connecting", "to", "a", "previously", "-", "unknown", "server", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L110-L127
train
paramiko/paramiko
paramiko/client.py
SSHClient.set_missing_host_key_policy
def set_missing_host_key_policy(self, policy): """ Set policy to use when connecting to servers without a known host key. Specifically: * A **policy** is a "policy class" (or instance thereof), namely some subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created subclass. * A host key is **known** when it appears in the client object's cached host keys structures (those manipulated by `load_system_host_keys` and/or `load_host_keys`). :param .MissingHostKeyPolicy policy: the policy to use when receiving a host key from a previously-unknown server """ if inspect.isclass(policy): policy = policy() self._policy = policy
python
def set_missing_host_key_policy(self, policy): """ Set policy to use when connecting to servers without a known host key. Specifically: * A **policy** is a "policy class" (or instance thereof), namely some subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created subclass. * A host key is **known** when it appears in the client object's cached host keys structures (those manipulated by `load_system_host_keys` and/or `load_host_keys`). :param .MissingHostKeyPolicy policy: the policy to use when receiving a host key from a previously-unknown server """ if inspect.isclass(policy): policy = policy() self._policy = policy
[ "def", "set_missing_host_key_policy", "(", "self", ",", "policy", ")", ":", "if", "inspect", ".", "isclass", "(", "policy", ")", ":", "policy", "=", "policy", "(", ")", "self", ".", "_policy", "=", "policy" ]
Set policy to use when connecting to servers without a known host key. Specifically: * A **policy** is a "policy class" (or instance thereof), namely some subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created subclass. * A host key is **known** when it appears in the client object's cached host keys structures (those manipulated by `load_system_host_keys` and/or `load_host_keys`). :param .MissingHostKeyPolicy policy: the policy to use when receiving a host key from a previously-unknown server
[ "Set", "policy", "to", "use", "when", "connecting", "to", "servers", "without", "a", "known", "host", "key", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L172-L192
train
paramiko/paramiko
paramiko/client.py
SSHClient._families_and_addresses
def _families_and_addresses(self, hostname, port): """ Yield pairs of address families and addresses to try for connecting. :param str hostname: the server to connect to :param int port: the server port to connect to :returns: Yields an iterable of ``(family, address)`` tuples """ guess = True addrinfos = socket.getaddrinfo( hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM ) for (family, socktype, proto, canonname, sockaddr) in addrinfos: if socktype == socket.SOCK_STREAM: yield family, sockaddr guess = False # some OS like AIX don't indicate SOCK_STREAM support, so just # guess. :( We only do this if we did not get a single result marked # as socktype == SOCK_STREAM. if guess: for family, _, _, _, sockaddr in addrinfos: yield family, sockaddr
python
def _families_and_addresses(self, hostname, port): """ Yield pairs of address families and addresses to try for connecting. :param str hostname: the server to connect to :param int port: the server port to connect to :returns: Yields an iterable of ``(family, address)`` tuples """ guess = True addrinfos = socket.getaddrinfo( hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM ) for (family, socktype, proto, canonname, sockaddr) in addrinfos: if socktype == socket.SOCK_STREAM: yield family, sockaddr guess = False # some OS like AIX don't indicate SOCK_STREAM support, so just # guess. :( We only do this if we did not get a single result marked # as socktype == SOCK_STREAM. if guess: for family, _, _, _, sockaddr in addrinfos: yield family, sockaddr
[ "def", "_families_and_addresses", "(", "self", ",", "hostname", ",", "port", ")", ":", "guess", "=", "True", "addrinfos", "=", "socket", ".", "getaddrinfo", "(", "hostname", ",", "port", ",", "socket", ".", "AF_UNSPEC", ",", "socket", ".", "SOCK_STREAM", ")", "for", "(", "family", ",", "socktype", ",", "proto", ",", "canonname", ",", "sockaddr", ")", "in", "addrinfos", ":", "if", "socktype", "==", "socket", ".", "SOCK_STREAM", ":", "yield", "family", ",", "sockaddr", "guess", "=", "False", "# some OS like AIX don't indicate SOCK_STREAM support, so just", "# guess. :( We only do this if we did not get a single result marked", "# as socktype == SOCK_STREAM.", "if", "guess", ":", "for", "family", ",", "_", ",", "_", ",", "_", ",", "sockaddr", "in", "addrinfos", ":", "yield", "family", ",", "sockaddr" ]
Yield pairs of address families and addresses to try for connecting. :param str hostname: the server to connect to :param int port: the server port to connect to :returns: Yields an iterable of ``(family, address)`` tuples
[ "Yield", "pairs", "of", "address", "families", "and", "addresses", "to", "try", "for", "connecting", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L194-L216
train
paramiko/paramiko
paramiko/client.py
SSHClient.connect
def connect( self, hostname, port=SSH_PORT, username=None, password=None, pkey=None, key_filename=None, timeout=None, allow_agent=True, look_for_keys=True, compress=False, sock=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True, gss_host=None, banner_timeout=None, auth_timeout=None, gss_trust_dns=True, passphrase=None, ): """ Connect to an SSH server and authenticate to it. The server's host key is checked against the system host keys (see `load_system_host_keys`) and any local host keys (`load_host_keys`). If the server's hostname is not found in either set of host keys, the missing host key policy is used (see `set_missing_host_key_policy`). The default policy is to reject the key and raise an `.SSHException`. Authentication is attempted in the following order of priority: - The ``pkey`` or ``key_filename`` passed in (if any) - ``key_filename`` may contain OpenSSH public certificate paths as well as regular private-key paths; when files ending in ``-cert.pub`` are found, they are assumed to match a private key, and both components will be loaded. (The private key itself does *not* need to be listed in ``key_filename`` for this to occur - *just* the certificate.) - Any key we can find through an SSH agent - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ``~/.ssh/`` - When OpenSSH-style public certificates exist that match an existing such private key (so e.g. one has ``id_rsa`` and ``id_rsa-cert.pub``) the certificate will be loaded alongside the private key and used for authentication. - Plain username/password auth, if a password was given If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key. :param str hostname: the server to connect to :param int port: the server port to connect to :param str username: the username to authenticate as (defaults to the current local username) :param str password: Used for password authentication; is also used for private key decryption if ``passphrase`` is not given. :param str passphrase: Used for decrypting private keys. :param .PKey pkey: an optional private key to use for authentication :param str key_filename: the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication :param float timeout: an optional timeout (in seconds) for the TCP connect :param bool allow_agent: set to False to disable connecting to the SSH agent :param bool look_for_keys: set to False to disable searching for discoverable private key files in ``~/.ssh/`` :param bool compress: set to True to turn on compression :param socket sock: an open socket or socket-like object (such as a `.Channel`) to use for communication to the target host :param bool gss_auth: ``True`` if you want to use GSS-API authentication :param bool gss_kex: Perform GSS-API Key Exchange and user authentication :param bool gss_deleg_creds: Delegate GSS-API client credentials or not :param str gss_host: The targets name in the kerberos database. default: hostname :param bool gss_trust_dns: Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default ``True``). :param float banner_timeout: an optional timeout (in seconds) to wait for the SSH banner to be presented. :param float auth_timeout: an optional timeout (in seconds) to wait for an authentication response. :raises: `.BadHostKeyException` -- if the server's host key could not be verified :raises: `.AuthenticationException` -- if authentication failed :raises: `.SSHException` -- if there was any other error connecting or establishing an SSH session :raises socket.error: if a socket error occurred while connecting .. versionchanged:: 1.15 Added the ``banner_timeout``, ``gss_auth``, ``gss_kex``, ``gss_deleg_creds`` and ``gss_host`` arguments. .. versionchanged:: 2.3 Added the ``gss_trust_dns`` argument. .. versionchanged:: 2.4 Added the ``passphrase`` argument. """ if not sock: errors = {} # Try multiple possible address families (e.g. IPv4 vs IPv6) to_try = list(self._families_and_addresses(hostname, port)) for af, addr in to_try: try: sock = socket.socket(af, socket.SOCK_STREAM) if timeout is not None: try: sock.settimeout(timeout) except: pass retry_on_signal(lambda: sock.connect(addr)) # Break out of the loop on success break except socket.error as e: # Raise anything that isn't a straight up connection error # (such as a resolution error) if e.errno not in (ECONNREFUSED, EHOSTUNREACH): raise # Capture anything else so we know how the run looks once # iteration is complete. Retain info about which attempt # this was. errors[addr] = e # Make sure we explode usefully if no address family attempts # succeeded. We've no way of knowing which error is the "right" # one, so we construct a hybrid exception containing all the real # ones, of a subclass that client code should still be watching for # (socket.error) if len(errors) == len(to_try): raise NoValidConnectionsError(errors) t = self._transport = Transport( sock, gss_kex=gss_kex, gss_deleg_creds=gss_deleg_creds ) t.use_compression(compress=compress) t.set_gss_host( # t.hostname may be None, but GSS-API requires a target name. # Therefore use hostname as fallback. gss_host=gss_host or hostname, trust_dns=gss_trust_dns, gssapi_requested=gss_auth or gss_kex, ) if self._log_channel is not None: t.set_log_channel(self._log_channel) if banner_timeout is not None: t.banner_timeout = banner_timeout if auth_timeout is not None: t.auth_timeout = auth_timeout if port == SSH_PORT: server_hostkey_name = hostname else: server_hostkey_name = "[{}]:{}".format(hostname, port) our_server_keys = None our_server_keys = self._system_host_keys.get(server_hostkey_name) if our_server_keys is None: our_server_keys = self._host_keys.get(server_hostkey_name) if our_server_keys is not None: keytype = our_server_keys.keys()[0] sec_opts = t.get_security_options() other_types = [x for x in sec_opts.key_types if x != keytype] sec_opts.key_types = [keytype] + other_types t.start_client(timeout=timeout) # If GSS-API Key Exchange is performed we are not required to check the # host key, because the host is authenticated via GSS-API / SSPI as # well as our client. if not self._transport.gss_kex_used: server_key = t.get_remote_server_key() if our_server_keys is None: # will raise exception if the key is rejected self._policy.missing_host_key( self, server_hostkey_name, server_key ) else: our_key = our_server_keys.get(server_key.get_name()) if our_key != server_key: if our_key is None: our_key = list(our_server_keys.values())[0] raise BadHostKeyException(hostname, server_key, our_key) if username is None: username = getpass.getuser() if key_filename is None: key_filenames = [] elif isinstance(key_filename, string_types): key_filenames = [key_filename] else: key_filenames = key_filename self._auth( username, password, pkey, key_filenames, allow_agent, look_for_keys, gss_auth, gss_kex, gss_deleg_creds, t.gss_host, passphrase, )
python
def connect( self, hostname, port=SSH_PORT, username=None, password=None, pkey=None, key_filename=None, timeout=None, allow_agent=True, look_for_keys=True, compress=False, sock=None, gss_auth=False, gss_kex=False, gss_deleg_creds=True, gss_host=None, banner_timeout=None, auth_timeout=None, gss_trust_dns=True, passphrase=None, ): """ Connect to an SSH server and authenticate to it. The server's host key is checked against the system host keys (see `load_system_host_keys`) and any local host keys (`load_host_keys`). If the server's hostname is not found in either set of host keys, the missing host key policy is used (see `set_missing_host_key_policy`). The default policy is to reject the key and raise an `.SSHException`. Authentication is attempted in the following order of priority: - The ``pkey`` or ``key_filename`` passed in (if any) - ``key_filename`` may contain OpenSSH public certificate paths as well as regular private-key paths; when files ending in ``-cert.pub`` are found, they are assumed to match a private key, and both components will be loaded. (The private key itself does *not* need to be listed in ``key_filename`` for this to occur - *just* the certificate.) - Any key we can find through an SSH agent - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ``~/.ssh/`` - When OpenSSH-style public certificates exist that match an existing such private key (so e.g. one has ``id_rsa`` and ``id_rsa-cert.pub``) the certificate will be loaded alongside the private key and used for authentication. - Plain username/password auth, if a password was given If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key. :param str hostname: the server to connect to :param int port: the server port to connect to :param str username: the username to authenticate as (defaults to the current local username) :param str password: Used for password authentication; is also used for private key decryption if ``passphrase`` is not given. :param str passphrase: Used for decrypting private keys. :param .PKey pkey: an optional private key to use for authentication :param str key_filename: the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication :param float timeout: an optional timeout (in seconds) for the TCP connect :param bool allow_agent: set to False to disable connecting to the SSH agent :param bool look_for_keys: set to False to disable searching for discoverable private key files in ``~/.ssh/`` :param bool compress: set to True to turn on compression :param socket sock: an open socket or socket-like object (such as a `.Channel`) to use for communication to the target host :param bool gss_auth: ``True`` if you want to use GSS-API authentication :param bool gss_kex: Perform GSS-API Key Exchange and user authentication :param bool gss_deleg_creds: Delegate GSS-API client credentials or not :param str gss_host: The targets name in the kerberos database. default: hostname :param bool gss_trust_dns: Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default ``True``). :param float banner_timeout: an optional timeout (in seconds) to wait for the SSH banner to be presented. :param float auth_timeout: an optional timeout (in seconds) to wait for an authentication response. :raises: `.BadHostKeyException` -- if the server's host key could not be verified :raises: `.AuthenticationException` -- if authentication failed :raises: `.SSHException` -- if there was any other error connecting or establishing an SSH session :raises socket.error: if a socket error occurred while connecting .. versionchanged:: 1.15 Added the ``banner_timeout``, ``gss_auth``, ``gss_kex``, ``gss_deleg_creds`` and ``gss_host`` arguments. .. versionchanged:: 2.3 Added the ``gss_trust_dns`` argument. .. versionchanged:: 2.4 Added the ``passphrase`` argument. """ if not sock: errors = {} # Try multiple possible address families (e.g. IPv4 vs IPv6) to_try = list(self._families_and_addresses(hostname, port)) for af, addr in to_try: try: sock = socket.socket(af, socket.SOCK_STREAM) if timeout is not None: try: sock.settimeout(timeout) except: pass retry_on_signal(lambda: sock.connect(addr)) # Break out of the loop on success break except socket.error as e: # Raise anything that isn't a straight up connection error # (such as a resolution error) if e.errno not in (ECONNREFUSED, EHOSTUNREACH): raise # Capture anything else so we know how the run looks once # iteration is complete. Retain info about which attempt # this was. errors[addr] = e # Make sure we explode usefully if no address family attempts # succeeded. We've no way of knowing which error is the "right" # one, so we construct a hybrid exception containing all the real # ones, of a subclass that client code should still be watching for # (socket.error) if len(errors) == len(to_try): raise NoValidConnectionsError(errors) t = self._transport = Transport( sock, gss_kex=gss_kex, gss_deleg_creds=gss_deleg_creds ) t.use_compression(compress=compress) t.set_gss_host( # t.hostname may be None, but GSS-API requires a target name. # Therefore use hostname as fallback. gss_host=gss_host or hostname, trust_dns=gss_trust_dns, gssapi_requested=gss_auth or gss_kex, ) if self._log_channel is not None: t.set_log_channel(self._log_channel) if banner_timeout is not None: t.banner_timeout = banner_timeout if auth_timeout is not None: t.auth_timeout = auth_timeout if port == SSH_PORT: server_hostkey_name = hostname else: server_hostkey_name = "[{}]:{}".format(hostname, port) our_server_keys = None our_server_keys = self._system_host_keys.get(server_hostkey_name) if our_server_keys is None: our_server_keys = self._host_keys.get(server_hostkey_name) if our_server_keys is not None: keytype = our_server_keys.keys()[0] sec_opts = t.get_security_options() other_types = [x for x in sec_opts.key_types if x != keytype] sec_opts.key_types = [keytype] + other_types t.start_client(timeout=timeout) # If GSS-API Key Exchange is performed we are not required to check the # host key, because the host is authenticated via GSS-API / SSPI as # well as our client. if not self._transport.gss_kex_used: server_key = t.get_remote_server_key() if our_server_keys is None: # will raise exception if the key is rejected self._policy.missing_host_key( self, server_hostkey_name, server_key ) else: our_key = our_server_keys.get(server_key.get_name()) if our_key != server_key: if our_key is None: our_key = list(our_server_keys.values())[0] raise BadHostKeyException(hostname, server_key, our_key) if username is None: username = getpass.getuser() if key_filename is None: key_filenames = [] elif isinstance(key_filename, string_types): key_filenames = [key_filename] else: key_filenames = key_filename self._auth( username, password, pkey, key_filenames, allow_agent, look_for_keys, gss_auth, gss_kex, gss_deleg_creds, t.gss_host, passphrase, )
[ "def", "connect", "(", "self", ",", "hostname", ",", "port", "=", "SSH_PORT", ",", "username", "=", "None", ",", "password", "=", "None", ",", "pkey", "=", "None", ",", "key_filename", "=", "None", ",", "timeout", "=", "None", ",", "allow_agent", "=", "True", ",", "look_for_keys", "=", "True", ",", "compress", "=", "False", ",", "sock", "=", "None", ",", "gss_auth", "=", "False", ",", "gss_kex", "=", "False", ",", "gss_deleg_creds", "=", "True", ",", "gss_host", "=", "None", ",", "banner_timeout", "=", "None", ",", "auth_timeout", "=", "None", ",", "gss_trust_dns", "=", "True", ",", "passphrase", "=", "None", ",", ")", ":", "if", "not", "sock", ":", "errors", "=", "{", "}", "# Try multiple possible address families (e.g. IPv4 vs IPv6)", "to_try", "=", "list", "(", "self", ".", "_families_and_addresses", "(", "hostname", ",", "port", ")", ")", "for", "af", ",", "addr", "in", "to_try", ":", "try", ":", "sock", "=", "socket", ".", "socket", "(", "af", ",", "socket", ".", "SOCK_STREAM", ")", "if", "timeout", "is", "not", "None", ":", "try", ":", "sock", ".", "settimeout", "(", "timeout", ")", "except", ":", "pass", "retry_on_signal", "(", "lambda", ":", "sock", ".", "connect", "(", "addr", ")", ")", "# Break out of the loop on success", "break", "except", "socket", ".", "error", "as", "e", ":", "# Raise anything that isn't a straight up connection error", "# (such as a resolution error)", "if", "e", ".", "errno", "not", "in", "(", "ECONNREFUSED", ",", "EHOSTUNREACH", ")", ":", "raise", "# Capture anything else so we know how the run looks once", "# iteration is complete. Retain info about which attempt", "# this was.", "errors", "[", "addr", "]", "=", "e", "# Make sure we explode usefully if no address family attempts", "# succeeded. We've no way of knowing which error is the \"right\"", "# one, so we construct a hybrid exception containing all the real", "# ones, of a subclass that client code should still be watching for", "# (socket.error)", "if", "len", "(", "errors", ")", "==", "len", "(", "to_try", ")", ":", "raise", "NoValidConnectionsError", "(", "errors", ")", "t", "=", "self", ".", "_transport", "=", "Transport", "(", "sock", ",", "gss_kex", "=", "gss_kex", ",", "gss_deleg_creds", "=", "gss_deleg_creds", ")", "t", ".", "use_compression", "(", "compress", "=", "compress", ")", "t", ".", "set_gss_host", "(", "# t.hostname may be None, but GSS-API requires a target name.", "# Therefore use hostname as fallback.", "gss_host", "=", "gss_host", "or", "hostname", ",", "trust_dns", "=", "gss_trust_dns", ",", "gssapi_requested", "=", "gss_auth", "or", "gss_kex", ",", ")", "if", "self", ".", "_log_channel", "is", "not", "None", ":", "t", ".", "set_log_channel", "(", "self", ".", "_log_channel", ")", "if", "banner_timeout", "is", "not", "None", ":", "t", ".", "banner_timeout", "=", "banner_timeout", "if", "auth_timeout", "is", "not", "None", ":", "t", ".", "auth_timeout", "=", "auth_timeout", "if", "port", "==", "SSH_PORT", ":", "server_hostkey_name", "=", "hostname", "else", ":", "server_hostkey_name", "=", "\"[{}]:{}\"", ".", "format", "(", "hostname", ",", "port", ")", "our_server_keys", "=", "None", "our_server_keys", "=", "self", ".", "_system_host_keys", ".", "get", "(", "server_hostkey_name", ")", "if", "our_server_keys", "is", "None", ":", "our_server_keys", "=", "self", ".", "_host_keys", ".", "get", "(", "server_hostkey_name", ")", "if", "our_server_keys", "is", "not", "None", ":", "keytype", "=", "our_server_keys", ".", "keys", "(", ")", "[", "0", "]", "sec_opts", "=", "t", ".", "get_security_options", "(", ")", "other_types", "=", "[", "x", "for", "x", "in", "sec_opts", ".", "key_types", "if", "x", "!=", "keytype", "]", "sec_opts", ".", "key_types", "=", "[", "keytype", "]", "+", "other_types", "t", ".", "start_client", "(", "timeout", "=", "timeout", ")", "# If GSS-API Key Exchange is performed we are not required to check the", "# host key, because the host is authenticated via GSS-API / SSPI as", "# well as our client.", "if", "not", "self", ".", "_transport", ".", "gss_kex_used", ":", "server_key", "=", "t", ".", "get_remote_server_key", "(", ")", "if", "our_server_keys", "is", "None", ":", "# will raise exception if the key is rejected", "self", ".", "_policy", ".", "missing_host_key", "(", "self", ",", "server_hostkey_name", ",", "server_key", ")", "else", ":", "our_key", "=", "our_server_keys", ".", "get", "(", "server_key", ".", "get_name", "(", ")", ")", "if", "our_key", "!=", "server_key", ":", "if", "our_key", "is", "None", ":", "our_key", "=", "list", "(", "our_server_keys", ".", "values", "(", ")", ")", "[", "0", "]", "raise", "BadHostKeyException", "(", "hostname", ",", "server_key", ",", "our_key", ")", "if", "username", "is", "None", ":", "username", "=", "getpass", ".", "getuser", "(", ")", "if", "key_filename", "is", "None", ":", "key_filenames", "=", "[", "]", "elif", "isinstance", "(", "key_filename", ",", "string_types", ")", ":", "key_filenames", "=", "[", "key_filename", "]", "else", ":", "key_filenames", "=", "key_filename", "self", ".", "_auth", "(", "username", ",", "password", ",", "pkey", ",", "key_filenames", ",", "allow_agent", ",", "look_for_keys", ",", "gss_auth", ",", "gss_kex", ",", "gss_deleg_creds", ",", "t", ".", "gss_host", ",", "passphrase", ",", ")" ]
Connect to an SSH server and authenticate to it. The server's host key is checked against the system host keys (see `load_system_host_keys`) and any local host keys (`load_host_keys`). If the server's hostname is not found in either set of host keys, the missing host key policy is used (see `set_missing_host_key_policy`). The default policy is to reject the key and raise an `.SSHException`. Authentication is attempted in the following order of priority: - The ``pkey`` or ``key_filename`` passed in (if any) - ``key_filename`` may contain OpenSSH public certificate paths as well as regular private-key paths; when files ending in ``-cert.pub`` are found, they are assumed to match a private key, and both components will be loaded. (The private key itself does *not* need to be listed in ``key_filename`` for this to occur - *just* the certificate.) - Any key we can find through an SSH agent - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ``~/.ssh/`` - When OpenSSH-style public certificates exist that match an existing such private key (so e.g. one has ``id_rsa`` and ``id_rsa-cert.pub``) the certificate will be loaded alongside the private key and used for authentication. - Plain username/password auth, if a password was given If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key. :param str hostname: the server to connect to :param int port: the server port to connect to :param str username: the username to authenticate as (defaults to the current local username) :param str password: Used for password authentication; is also used for private key decryption if ``passphrase`` is not given. :param str passphrase: Used for decrypting private keys. :param .PKey pkey: an optional private key to use for authentication :param str key_filename: the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication :param float timeout: an optional timeout (in seconds) for the TCP connect :param bool allow_agent: set to False to disable connecting to the SSH agent :param bool look_for_keys: set to False to disable searching for discoverable private key files in ``~/.ssh/`` :param bool compress: set to True to turn on compression :param socket sock: an open socket or socket-like object (such as a `.Channel`) to use for communication to the target host :param bool gss_auth: ``True`` if you want to use GSS-API authentication :param bool gss_kex: Perform GSS-API Key Exchange and user authentication :param bool gss_deleg_creds: Delegate GSS-API client credentials or not :param str gss_host: The targets name in the kerberos database. default: hostname :param bool gss_trust_dns: Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default ``True``). :param float banner_timeout: an optional timeout (in seconds) to wait for the SSH banner to be presented. :param float auth_timeout: an optional timeout (in seconds) to wait for an authentication response. :raises: `.BadHostKeyException` -- if the server's host key could not be verified :raises: `.AuthenticationException` -- if authentication failed :raises: `.SSHException` -- if there was any other error connecting or establishing an SSH session :raises socket.error: if a socket error occurred while connecting .. versionchanged:: 1.15 Added the ``banner_timeout``, ``gss_auth``, ``gss_kex``, ``gss_deleg_creds`` and ``gss_host`` arguments. .. versionchanged:: 2.3 Added the ``gss_trust_dns`` argument. .. versionchanged:: 2.4 Added the ``passphrase`` argument.
[ "Connect", "to", "an", "SSH", "server", "and", "authenticate", "to", "it", ".", "The", "server", "s", "host", "key", "is", "checked", "against", "the", "system", "host", "keys", "(", "see", "load_system_host_keys", ")", "and", "any", "local", "host", "keys", "(", "load_host_keys", ")", ".", "If", "the", "server", "s", "hostname", "is", "not", "found", "in", "either", "set", "of", "host", "keys", "the", "missing", "host", "key", "policy", "is", "used", "(", "see", "set_missing_host_key_policy", ")", ".", "The", "default", "policy", "is", "to", "reject", "the", "key", "and", "raise", "an", ".", "SSHException", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L218-L438
train
paramiko/paramiko
paramiko/client.py
SSHClient.close
def close(self): """ Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client objects anytime you're done using them, instead of relying on garbage collection. """ if self._transport is None: return self._transport.close() self._transport = None if self._agent is not None: self._agent.close() self._agent = None
python
def close(self): """ Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client objects anytime you're done using them, instead of relying on garbage collection. """ if self._transport is None: return self._transport.close() self._transport = None if self._agent is not None: self._agent.close() self._agent = None
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_transport", "is", "None", ":", "return", "self", ".", "_transport", ".", "close", "(", ")", "self", ".", "_transport", "=", "None", "if", "self", ".", "_agent", "is", "not", "None", ":", "self", ".", "_agent", ".", "close", "(", ")", "self", ".", "_agent", "=", "None" ]
Close this SSHClient and its underlying `.Transport`. .. warning:: Failure to do this may, in some situations, cause your Python interpreter to hang at shutdown (often due to race conditions). It's good practice to `close` your client objects anytime you're done using them, instead of relying on garbage collection.
[ "Close", "this", "SSHClient", "and", "its", "underlying", ".", "Transport", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L440-L457
train
paramiko/paramiko
paramiko/client.py
SSHClient.exec_command
def exec_command( self, command, bufsize=-1, timeout=None, get_pty=False, environment=None, ): """ Execute a command on the SSH server. A new `.Channel` is opened and the requested command is executed. The command's input and output streams are returned as Python ``file``-like objects representing stdin, stdout, and stderr. :param str command: the command to execute :param int bufsize: interpreted the same way as by the built-in ``file()`` function in Python :param int timeout: set command's channel timeout. See `.Channel.settimeout` :param bool get_pty: Request a pseudo-terminal from the server (default ``False``). See `.Channel.get_pty` :param dict environment: a dict of shell environment variables, to be merged into the default environment that the remote command executes within. .. warning:: Servers may silently reject some environment variables; see the warning in `.Channel.set_environment_variable` for details. :return: the stdin, stdout, and stderr of the executing command, as a 3-tuple :raises: `.SSHException` -- if the server fails to execute the command .. versionchanged:: 1.10 Added the ``get_pty`` kwarg. """ chan = self._transport.open_session(timeout=timeout) if get_pty: chan.get_pty() chan.settimeout(timeout) if environment: chan.update_environment(environment) chan.exec_command(command) stdin = chan.makefile("wb", bufsize) stdout = chan.makefile("r", bufsize) stderr = chan.makefile_stderr("r", bufsize) return stdin, stdout, stderr
python
def exec_command( self, command, bufsize=-1, timeout=None, get_pty=False, environment=None, ): """ Execute a command on the SSH server. A new `.Channel` is opened and the requested command is executed. The command's input and output streams are returned as Python ``file``-like objects representing stdin, stdout, and stderr. :param str command: the command to execute :param int bufsize: interpreted the same way as by the built-in ``file()`` function in Python :param int timeout: set command's channel timeout. See `.Channel.settimeout` :param bool get_pty: Request a pseudo-terminal from the server (default ``False``). See `.Channel.get_pty` :param dict environment: a dict of shell environment variables, to be merged into the default environment that the remote command executes within. .. warning:: Servers may silently reject some environment variables; see the warning in `.Channel.set_environment_variable` for details. :return: the stdin, stdout, and stderr of the executing command, as a 3-tuple :raises: `.SSHException` -- if the server fails to execute the command .. versionchanged:: 1.10 Added the ``get_pty`` kwarg. """ chan = self._transport.open_session(timeout=timeout) if get_pty: chan.get_pty() chan.settimeout(timeout) if environment: chan.update_environment(environment) chan.exec_command(command) stdin = chan.makefile("wb", bufsize) stdout = chan.makefile("r", bufsize) stderr = chan.makefile_stderr("r", bufsize) return stdin, stdout, stderr
[ "def", "exec_command", "(", "self", ",", "command", ",", "bufsize", "=", "-", "1", ",", "timeout", "=", "None", ",", "get_pty", "=", "False", ",", "environment", "=", "None", ",", ")", ":", "chan", "=", "self", ".", "_transport", ".", "open_session", "(", "timeout", "=", "timeout", ")", "if", "get_pty", ":", "chan", ".", "get_pty", "(", ")", "chan", ".", "settimeout", "(", "timeout", ")", "if", "environment", ":", "chan", ".", "update_environment", "(", "environment", ")", "chan", ".", "exec_command", "(", "command", ")", "stdin", "=", "chan", ".", "makefile", "(", "\"wb\"", ",", "bufsize", ")", "stdout", "=", "chan", ".", "makefile", "(", "\"r\"", ",", "bufsize", ")", "stderr", "=", "chan", ".", "makefile_stderr", "(", "\"r\"", ",", "bufsize", ")", "return", "stdin", ",", "stdout", ",", "stderr" ]
Execute a command on the SSH server. A new `.Channel` is opened and the requested command is executed. The command's input and output streams are returned as Python ``file``-like objects representing stdin, stdout, and stderr. :param str command: the command to execute :param int bufsize: interpreted the same way as by the built-in ``file()`` function in Python :param int timeout: set command's channel timeout. See `.Channel.settimeout` :param bool get_pty: Request a pseudo-terminal from the server (default ``False``). See `.Channel.get_pty` :param dict environment: a dict of shell environment variables, to be merged into the default environment that the remote command executes within. .. warning:: Servers may silently reject some environment variables; see the warning in `.Channel.set_environment_variable` for details. :return: the stdin, stdout, and stderr of the executing command, as a 3-tuple :raises: `.SSHException` -- if the server fails to execute the command .. versionchanged:: 1.10 Added the ``get_pty`` kwarg.
[ "Execute", "a", "command", "on", "the", "SSH", "server", ".", "A", "new", ".", "Channel", "is", "opened", "and", "the", "requested", "command", "is", "executed", ".", "The", "command", "s", "input", "and", "output", "streams", "are", "returned", "as", "Python", "file", "-", "like", "objects", "representing", "stdin", "stdout", "and", "stderr", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L459-L509
train
paramiko/paramiko
paramiko/client.py
SSHClient.invoke_shell
def invoke_shell( self, term="vt100", width=80, height=24, width_pixels=0, height_pixels=0, environment=None, ): """ Start an interactive shell session on the SSH server. A new `.Channel` is opened and connected to a pseudo-terminal using the requested terminal type and size. :param str term: the terminal type to emulate (for example, ``"vt100"``) :param int width: the width (in characters) of the terminal window :param int height: the height (in characters) of the terminal window :param int width_pixels: the width (in pixels) of the terminal window :param int height_pixels: the height (in pixels) of the terminal window :param dict environment: the command's environment :return: a new `.Channel` connected to the remote shell :raises: `.SSHException` -- if the server fails to invoke a shell """ chan = self._transport.open_session() chan.get_pty(term, width, height, width_pixels, height_pixels) chan.invoke_shell() return chan
python
def invoke_shell( self, term="vt100", width=80, height=24, width_pixels=0, height_pixels=0, environment=None, ): """ Start an interactive shell session on the SSH server. A new `.Channel` is opened and connected to a pseudo-terminal using the requested terminal type and size. :param str term: the terminal type to emulate (for example, ``"vt100"``) :param int width: the width (in characters) of the terminal window :param int height: the height (in characters) of the terminal window :param int width_pixels: the width (in pixels) of the terminal window :param int height_pixels: the height (in pixels) of the terminal window :param dict environment: the command's environment :return: a new `.Channel` connected to the remote shell :raises: `.SSHException` -- if the server fails to invoke a shell """ chan = self._transport.open_session() chan.get_pty(term, width, height, width_pixels, height_pixels) chan.invoke_shell() return chan
[ "def", "invoke_shell", "(", "self", ",", "term", "=", "\"vt100\"", ",", "width", "=", "80", ",", "height", "=", "24", ",", "width_pixels", "=", "0", ",", "height_pixels", "=", "0", ",", "environment", "=", "None", ",", ")", ":", "chan", "=", "self", ".", "_transport", ".", "open_session", "(", ")", "chan", ".", "get_pty", "(", "term", ",", "width", ",", "height", ",", "width_pixels", ",", "height_pixels", ")", "chan", ".", "invoke_shell", "(", ")", "return", "chan" ]
Start an interactive shell session on the SSH server. A new `.Channel` is opened and connected to a pseudo-terminal using the requested terminal type and size. :param str term: the terminal type to emulate (for example, ``"vt100"``) :param int width: the width (in characters) of the terminal window :param int height: the height (in characters) of the terminal window :param int width_pixels: the width (in pixels) of the terminal window :param int height_pixels: the height (in pixels) of the terminal window :param dict environment: the command's environment :return: a new `.Channel` connected to the remote shell :raises: `.SSHException` -- if the server fails to invoke a shell
[ "Start", "an", "interactive", "shell", "session", "on", "the", "SSH", "server", ".", "A", "new", ".", "Channel", "is", "opened", "and", "connected", "to", "a", "pseudo", "-", "terminal", "using", "the", "requested", "terminal", "type", "and", "size", "." ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L511-L539
train
paramiko/paramiko
paramiko/client.py
SSHClient._key_from_filepath
def _key_from_filepath(self, filename, klass, password): """ Attempt to derive a `.PKey` from given string path ``filename``: - If ``filename`` appears to be a cert, the matching private key is loaded. - Otherwise, the filename is assumed to be a private key, and the matching public cert will be loaded if it exists. """ cert_suffix = "-cert.pub" # Assume privkey, not cert, by default if filename.endswith(cert_suffix): key_path = filename[: -len(cert_suffix)] cert_path = filename else: key_path = filename cert_path = filename + cert_suffix # Blindly try the key path; if no private key, nothing will work. key = klass.from_private_key_file(key_path, password) # TODO: change this to 'Loading' instead of 'Trying' sometime; probably # when #387 is released, since this is a critical log message users are # likely testing/filtering for (bah.) msg = "Trying discovered key {} in {}".format( hexlify(key.get_fingerprint()), key_path ) self._log(DEBUG, msg) # Attempt to load cert if it exists. if os.path.isfile(cert_path): key.load_certificate(cert_path) self._log(DEBUG, "Adding public certificate {}".format(cert_path)) return key
python
def _key_from_filepath(self, filename, klass, password): """ Attempt to derive a `.PKey` from given string path ``filename``: - If ``filename`` appears to be a cert, the matching private key is loaded. - Otherwise, the filename is assumed to be a private key, and the matching public cert will be loaded if it exists. """ cert_suffix = "-cert.pub" # Assume privkey, not cert, by default if filename.endswith(cert_suffix): key_path = filename[: -len(cert_suffix)] cert_path = filename else: key_path = filename cert_path = filename + cert_suffix # Blindly try the key path; if no private key, nothing will work. key = klass.from_private_key_file(key_path, password) # TODO: change this to 'Loading' instead of 'Trying' sometime; probably # when #387 is released, since this is a critical log message users are # likely testing/filtering for (bah.) msg = "Trying discovered key {} in {}".format( hexlify(key.get_fingerprint()), key_path ) self._log(DEBUG, msg) # Attempt to load cert if it exists. if os.path.isfile(cert_path): key.load_certificate(cert_path) self._log(DEBUG, "Adding public certificate {}".format(cert_path)) return key
[ "def", "_key_from_filepath", "(", "self", ",", "filename", ",", "klass", ",", "password", ")", ":", "cert_suffix", "=", "\"-cert.pub\"", "# Assume privkey, not cert, by default", "if", "filename", ".", "endswith", "(", "cert_suffix", ")", ":", "key_path", "=", "filename", "[", ":", "-", "len", "(", "cert_suffix", ")", "]", "cert_path", "=", "filename", "else", ":", "key_path", "=", "filename", "cert_path", "=", "filename", "+", "cert_suffix", "# Blindly try the key path; if no private key, nothing will work.", "key", "=", "klass", ".", "from_private_key_file", "(", "key_path", ",", "password", ")", "# TODO: change this to 'Loading' instead of 'Trying' sometime; probably", "# when #387 is released, since this is a critical log message users are", "# likely testing/filtering for (bah.)", "msg", "=", "\"Trying discovered key {} in {}\"", ".", "format", "(", "hexlify", "(", "key", ".", "get_fingerprint", "(", ")", ")", ",", "key_path", ")", "self", ".", "_log", "(", "DEBUG", ",", "msg", ")", "# Attempt to load cert if it exists.", "if", "os", ".", "path", ".", "isfile", "(", "cert_path", ")", ":", "key", ".", "load_certificate", "(", "cert_path", ")", "self", ".", "_log", "(", "DEBUG", ",", "\"Adding public certificate {}\"", ".", "format", "(", "cert_path", ")", ")", "return", "key" ]
Attempt to derive a `.PKey` from given string path ``filename``: - If ``filename`` appears to be a cert, the matching private key is loaded. - Otherwise, the filename is assumed to be a private key, and the matching public cert will be loaded if it exists.
[ "Attempt", "to", "derive", "a", ".", "PKey", "from", "given", "string", "path", "filename", ":" ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L559-L589
train
paramiko/paramiko
paramiko/client.py
SSHClient._auth
def _auth( self, username, password, pkey, key_filenames, allow_agent, look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host, passphrase, ): """ Try, in order: - The key(s) passed in, if one was passed in. - Any key we can find through an SSH agent (if allowed). - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ~/.ssh/ (if allowed). - Plain username/password auth, if a password was given. (The password might be needed to unlock a private key [if 'passphrase' isn't also given], or for two-factor authentication [for which it is required].) """ saved_exception = None two_factor = False allowed_types = set() two_factor_types = {"keyboard-interactive", "password"} if passphrase is None and password is not None: passphrase = password # If GSS-API support and GSS-PI Key Exchange was performed, we attempt # authentication with gssapi-keyex. if gss_kex and self._transport.gss_kex_used: try: self._transport.auth_gssapi_keyex(username) return except Exception as e: saved_exception = e # Try GSS-API authentication (gssapi-with-mic) only if GSS-API Key # Exchange is not performed, because if we use GSS-API for the key # exchange, there is already a fully established GSS-API context, so # why should we do that again? if gss_auth: try: return self._transport.auth_gssapi_with_mic( username, gss_host, gss_deleg_creds ) except Exception as e: saved_exception = e if pkey is not None: try: self._log( DEBUG, "Trying SSH key {}".format( hexlify(pkey.get_fingerprint()) ), ) allowed_types = set( self._transport.auth_publickey(username, pkey) ) two_factor = allowed_types & two_factor_types if not two_factor: return except SSHException as e: saved_exception = e if not two_factor: for key_filename in key_filenames: for pkey_class in (RSAKey, DSSKey, ECDSAKey, Ed25519Key): try: key = self._key_from_filepath( key_filename, pkey_class, passphrase ) allowed_types = set( self._transport.auth_publickey(username, key) ) two_factor = allowed_types & two_factor_types if not two_factor: return break except SSHException as e: saved_exception = e if not two_factor and allow_agent: if self._agent is None: self._agent = Agent() for key in self._agent.get_keys(): try: id_ = hexlify(key.get_fingerprint()) self._log(DEBUG, "Trying SSH agent key {}".format(id_)) # for 2-factor auth a successfully auth'd key password # will return an allowed 2fac auth method allowed_types = set( self._transport.auth_publickey(username, key) ) two_factor = allowed_types & two_factor_types if not two_factor: return break except SSHException as e: saved_exception = e if not two_factor: keyfiles = [] for keytype, name in [ (RSAKey, "rsa"), (DSSKey, "dsa"), (ECDSAKey, "ecdsa"), (Ed25519Key, "ed25519"), ]: # ~/ssh/ is for windows for directory in [".ssh", "ssh"]: full_path = os.path.expanduser( "~/{}/id_{}".format(directory, name) ) if os.path.isfile(full_path): # TODO: only do this append if below did not run keyfiles.append((keytype, full_path)) if os.path.isfile(full_path + "-cert.pub"): keyfiles.append((keytype, full_path + "-cert.pub")) if not look_for_keys: keyfiles = [] for pkey_class, filename in keyfiles: try: key = self._key_from_filepath( filename, pkey_class, passphrase ) # for 2-factor auth a successfully auth'd key will result # in ['password'] allowed_types = set( self._transport.auth_publickey(username, key) ) two_factor = allowed_types & two_factor_types if not two_factor: return break except (SSHException, IOError) as e: saved_exception = e if password is not None: try: self._transport.auth_password(username, password) return except SSHException as e: saved_exception = e elif two_factor: try: self._transport.auth_interactive_dumb(username) return except SSHException as e: saved_exception = e # if we got an auth-failed exception earlier, re-raise it if saved_exception is not None: raise saved_exception raise SSHException("No authentication methods available")
python
def _auth( self, username, password, pkey, key_filenames, allow_agent, look_for_keys, gss_auth, gss_kex, gss_deleg_creds, gss_host, passphrase, ): """ Try, in order: - The key(s) passed in, if one was passed in. - Any key we can find through an SSH agent (if allowed). - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ~/.ssh/ (if allowed). - Plain username/password auth, if a password was given. (The password might be needed to unlock a private key [if 'passphrase' isn't also given], or for two-factor authentication [for which it is required].) """ saved_exception = None two_factor = False allowed_types = set() two_factor_types = {"keyboard-interactive", "password"} if passphrase is None and password is not None: passphrase = password # If GSS-API support and GSS-PI Key Exchange was performed, we attempt # authentication with gssapi-keyex. if gss_kex and self._transport.gss_kex_used: try: self._transport.auth_gssapi_keyex(username) return except Exception as e: saved_exception = e # Try GSS-API authentication (gssapi-with-mic) only if GSS-API Key # Exchange is not performed, because if we use GSS-API for the key # exchange, there is already a fully established GSS-API context, so # why should we do that again? if gss_auth: try: return self._transport.auth_gssapi_with_mic( username, gss_host, gss_deleg_creds ) except Exception as e: saved_exception = e if pkey is not None: try: self._log( DEBUG, "Trying SSH key {}".format( hexlify(pkey.get_fingerprint()) ), ) allowed_types = set( self._transport.auth_publickey(username, pkey) ) two_factor = allowed_types & two_factor_types if not two_factor: return except SSHException as e: saved_exception = e if not two_factor: for key_filename in key_filenames: for pkey_class in (RSAKey, DSSKey, ECDSAKey, Ed25519Key): try: key = self._key_from_filepath( key_filename, pkey_class, passphrase ) allowed_types = set( self._transport.auth_publickey(username, key) ) two_factor = allowed_types & two_factor_types if not two_factor: return break except SSHException as e: saved_exception = e if not two_factor and allow_agent: if self._agent is None: self._agent = Agent() for key in self._agent.get_keys(): try: id_ = hexlify(key.get_fingerprint()) self._log(DEBUG, "Trying SSH agent key {}".format(id_)) # for 2-factor auth a successfully auth'd key password # will return an allowed 2fac auth method allowed_types = set( self._transport.auth_publickey(username, key) ) two_factor = allowed_types & two_factor_types if not two_factor: return break except SSHException as e: saved_exception = e if not two_factor: keyfiles = [] for keytype, name in [ (RSAKey, "rsa"), (DSSKey, "dsa"), (ECDSAKey, "ecdsa"), (Ed25519Key, "ed25519"), ]: # ~/ssh/ is for windows for directory in [".ssh", "ssh"]: full_path = os.path.expanduser( "~/{}/id_{}".format(directory, name) ) if os.path.isfile(full_path): # TODO: only do this append if below did not run keyfiles.append((keytype, full_path)) if os.path.isfile(full_path + "-cert.pub"): keyfiles.append((keytype, full_path + "-cert.pub")) if not look_for_keys: keyfiles = [] for pkey_class, filename in keyfiles: try: key = self._key_from_filepath( filename, pkey_class, passphrase ) # for 2-factor auth a successfully auth'd key will result # in ['password'] allowed_types = set( self._transport.auth_publickey(username, key) ) two_factor = allowed_types & two_factor_types if not two_factor: return break except (SSHException, IOError) as e: saved_exception = e if password is not None: try: self._transport.auth_password(username, password) return except SSHException as e: saved_exception = e elif two_factor: try: self._transport.auth_interactive_dumb(username) return except SSHException as e: saved_exception = e # if we got an auth-failed exception earlier, re-raise it if saved_exception is not None: raise saved_exception raise SSHException("No authentication methods available")
[ "def", "_auth", "(", "self", ",", "username", ",", "password", ",", "pkey", ",", "key_filenames", ",", "allow_agent", ",", "look_for_keys", ",", "gss_auth", ",", "gss_kex", ",", "gss_deleg_creds", ",", "gss_host", ",", "passphrase", ",", ")", ":", "saved_exception", "=", "None", "two_factor", "=", "False", "allowed_types", "=", "set", "(", ")", "two_factor_types", "=", "{", "\"keyboard-interactive\"", ",", "\"password\"", "}", "if", "passphrase", "is", "None", "and", "password", "is", "not", "None", ":", "passphrase", "=", "password", "# If GSS-API support and GSS-PI Key Exchange was performed, we attempt", "# authentication with gssapi-keyex.", "if", "gss_kex", "and", "self", ".", "_transport", ".", "gss_kex_used", ":", "try", ":", "self", ".", "_transport", ".", "auth_gssapi_keyex", "(", "username", ")", "return", "except", "Exception", "as", "e", ":", "saved_exception", "=", "e", "# Try GSS-API authentication (gssapi-with-mic) only if GSS-API Key", "# Exchange is not performed, because if we use GSS-API for the key", "# exchange, there is already a fully established GSS-API context, so", "# why should we do that again?", "if", "gss_auth", ":", "try", ":", "return", "self", ".", "_transport", ".", "auth_gssapi_with_mic", "(", "username", ",", "gss_host", ",", "gss_deleg_creds", ")", "except", "Exception", "as", "e", ":", "saved_exception", "=", "e", "if", "pkey", "is", "not", "None", ":", "try", ":", "self", ".", "_log", "(", "DEBUG", ",", "\"Trying SSH key {}\"", ".", "format", "(", "hexlify", "(", "pkey", ".", "get_fingerprint", "(", ")", ")", ")", ",", ")", "allowed_types", "=", "set", "(", "self", ".", "_transport", ".", "auth_publickey", "(", "username", ",", "pkey", ")", ")", "two_factor", "=", "allowed_types", "&", "two_factor_types", "if", "not", "two_factor", ":", "return", "except", "SSHException", "as", "e", ":", "saved_exception", "=", "e", "if", "not", "two_factor", ":", "for", "key_filename", "in", "key_filenames", ":", "for", "pkey_class", "in", "(", "RSAKey", ",", "DSSKey", ",", "ECDSAKey", ",", "Ed25519Key", ")", ":", "try", ":", "key", "=", "self", ".", "_key_from_filepath", "(", "key_filename", ",", "pkey_class", ",", "passphrase", ")", "allowed_types", "=", "set", "(", "self", ".", "_transport", ".", "auth_publickey", "(", "username", ",", "key", ")", ")", "two_factor", "=", "allowed_types", "&", "two_factor_types", "if", "not", "two_factor", ":", "return", "break", "except", "SSHException", "as", "e", ":", "saved_exception", "=", "e", "if", "not", "two_factor", "and", "allow_agent", ":", "if", "self", ".", "_agent", "is", "None", ":", "self", ".", "_agent", "=", "Agent", "(", ")", "for", "key", "in", "self", ".", "_agent", ".", "get_keys", "(", ")", ":", "try", ":", "id_", "=", "hexlify", "(", "key", ".", "get_fingerprint", "(", ")", ")", "self", ".", "_log", "(", "DEBUG", ",", "\"Trying SSH agent key {}\"", ".", "format", "(", "id_", ")", ")", "# for 2-factor auth a successfully auth'd key password", "# will return an allowed 2fac auth method", "allowed_types", "=", "set", "(", "self", ".", "_transport", ".", "auth_publickey", "(", "username", ",", "key", ")", ")", "two_factor", "=", "allowed_types", "&", "two_factor_types", "if", "not", "two_factor", ":", "return", "break", "except", "SSHException", "as", "e", ":", "saved_exception", "=", "e", "if", "not", "two_factor", ":", "keyfiles", "=", "[", "]", "for", "keytype", ",", "name", "in", "[", "(", "RSAKey", ",", "\"rsa\"", ")", ",", "(", "DSSKey", ",", "\"dsa\"", ")", ",", "(", "ECDSAKey", ",", "\"ecdsa\"", ")", ",", "(", "Ed25519Key", ",", "\"ed25519\"", ")", ",", "]", ":", "# ~/ssh/ is for windows", "for", "directory", "in", "[", "\".ssh\"", ",", "\"ssh\"", "]", ":", "full_path", "=", "os", ".", "path", ".", "expanduser", "(", "\"~/{}/id_{}\"", ".", "format", "(", "directory", ",", "name", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "full_path", ")", ":", "# TODO: only do this append if below did not run", "keyfiles", ".", "append", "(", "(", "keytype", ",", "full_path", ")", ")", "if", "os", ".", "path", ".", "isfile", "(", "full_path", "+", "\"-cert.pub\"", ")", ":", "keyfiles", ".", "append", "(", "(", "keytype", ",", "full_path", "+", "\"-cert.pub\"", ")", ")", "if", "not", "look_for_keys", ":", "keyfiles", "=", "[", "]", "for", "pkey_class", ",", "filename", "in", "keyfiles", ":", "try", ":", "key", "=", "self", ".", "_key_from_filepath", "(", "filename", ",", "pkey_class", ",", "passphrase", ")", "# for 2-factor auth a successfully auth'd key will result", "# in ['password']", "allowed_types", "=", "set", "(", "self", ".", "_transport", ".", "auth_publickey", "(", "username", ",", "key", ")", ")", "two_factor", "=", "allowed_types", "&", "two_factor_types", "if", "not", "two_factor", ":", "return", "break", "except", "(", "SSHException", ",", "IOError", ")", "as", "e", ":", "saved_exception", "=", "e", "if", "password", "is", "not", "None", ":", "try", ":", "self", ".", "_transport", ".", "auth_password", "(", "username", ",", "password", ")", "return", "except", "SSHException", "as", "e", ":", "saved_exception", "=", "e", "elif", "two_factor", ":", "try", ":", "self", ".", "_transport", ".", "auth_interactive_dumb", "(", "username", ")", "return", "except", "SSHException", "as", "e", ":", "saved_exception", "=", "e", "# if we got an auth-failed exception earlier, re-raise it", "if", "saved_exception", "is", "not", "None", ":", "raise", "saved_exception", "raise", "SSHException", "(", "\"No authentication methods available\"", ")" ]
Try, in order: - The key(s) passed in, if one was passed in. - Any key we can find through an SSH agent (if allowed). - Any "id_rsa", "id_dsa" or "id_ecdsa" key discoverable in ~/.ssh/ (if allowed). - Plain username/password auth, if a password was given. (The password might be needed to unlock a private key [if 'passphrase' isn't also given], or for two-factor authentication [for which it is required].)
[ "Try", "in", "order", ":" ]
cf7d49d66f3b1fbc8b0853518a54050182b3b5eb
https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L591-L756
train
Kaggle/kaggle-api
kaggle/models/kernel_push_request.py
KernelPushRequest.language
def language(self, language): """Sets the language of this KernelPushRequest. The language that the kernel is written in # noqa: E501 :param language: The language of this KernelPushRequest. # noqa: E501 :type: str """ if language is None: raise ValueError("Invalid value for `language`, must not be `None`") # noqa: E501 allowed_values = ["python", "r", "rmarkdown"] # noqa: E501 if language not in allowed_values: raise ValueError( "Invalid value for `language` ({0}), must be one of {1}" # noqa: E501 .format(language, allowed_values) ) self._language = language
python
def language(self, language): """Sets the language of this KernelPushRequest. The language that the kernel is written in # noqa: E501 :param language: The language of this KernelPushRequest. # noqa: E501 :type: str """ if language is None: raise ValueError("Invalid value for `language`, must not be `None`") # noqa: E501 allowed_values = ["python", "r", "rmarkdown"] # noqa: E501 if language not in allowed_values: raise ValueError( "Invalid value for `language` ({0}), must be one of {1}" # noqa: E501 .format(language, allowed_values) ) self._language = language
[ "def", "language", "(", "self", ",", "language", ")", ":", "if", "language", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `language`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"python\"", ",", "\"r\"", ",", "\"rmarkdown\"", "]", "# noqa: E501", "if", "language", "not", "in", "allowed_values", ":", "raise", "ValueError", "(", "\"Invalid value for `language` ({0}), must be one of {1}\"", "# noqa: E501", ".", "format", "(", "language", ",", "allowed_values", ")", ")", "self", ".", "_language", "=", "language" ]
Sets the language of this KernelPushRequest. The language that the kernel is written in # noqa: E501 :param language: The language of this KernelPushRequest. # noqa: E501 :type: str
[ "Sets", "the", "language", "of", "this", "KernelPushRequest", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/kernel_push_request.py#L229-L246
train
Kaggle/kaggle-api
kaggle/models/kernel_push_request.py
KernelPushRequest.kernel_type
def kernel_type(self, kernel_type): """Sets the kernel_type of this KernelPushRequest. The type of kernel. Cannot be changed once the kernel has been created # noqa: E501 :param kernel_type: The kernel_type of this KernelPushRequest. # noqa: E501 :type: str """ if kernel_type is None: raise ValueError("Invalid value for `kernel_type`, must not be `None`") # noqa: E501 allowed_values = ["script", "notebook"] # noqa: E501 if kernel_type not in allowed_values: raise ValueError( "Invalid value for `kernel_type` ({0}), must be one of {1}" # noqa: E501 .format(kernel_type, allowed_values) ) self._kernel_type = kernel_type
python
def kernel_type(self, kernel_type): """Sets the kernel_type of this KernelPushRequest. The type of kernel. Cannot be changed once the kernel has been created # noqa: E501 :param kernel_type: The kernel_type of this KernelPushRequest. # noqa: E501 :type: str """ if kernel_type is None: raise ValueError("Invalid value for `kernel_type`, must not be `None`") # noqa: E501 allowed_values = ["script", "notebook"] # noqa: E501 if kernel_type not in allowed_values: raise ValueError( "Invalid value for `kernel_type` ({0}), must be one of {1}" # noqa: E501 .format(kernel_type, allowed_values) ) self._kernel_type = kernel_type
[ "def", "kernel_type", "(", "self", ",", "kernel_type", ")", ":", "if", "kernel_type", "is", "None", ":", "raise", "ValueError", "(", "\"Invalid value for `kernel_type`, must not be `None`\"", ")", "# noqa: E501", "allowed_values", "=", "[", "\"script\"", ",", "\"notebook\"", "]", "# noqa: E501", "if", "kernel_type", "not", "in", "allowed_values", ":", "raise", "ValueError", "(", "\"Invalid value for `kernel_type` ({0}), must be one of {1}\"", "# noqa: E501", ".", "format", "(", "kernel_type", ",", "allowed_values", ")", ")", "self", ".", "_kernel_type", "=", "kernel_type" ]
Sets the kernel_type of this KernelPushRequest. The type of kernel. Cannot be changed once the kernel has been created # noqa: E501 :param kernel_type: The kernel_type of this KernelPushRequest. # noqa: E501 :type: str
[ "Sets", "the", "kernel_type", "of", "this", "KernelPushRequest", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/models/kernel_push_request.py#L260-L277
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competition_download_leaderboard
def competition_download_leaderboard(self, id, **kwargs): # noqa: E501 """Download competition leaderboard # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competition_download_leaderboard(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competition_download_leaderboard_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competition_download_leaderboard_with_http_info(id, **kwargs) # noqa: E501 return data
python
def competition_download_leaderboard(self, id, **kwargs): # noqa: E501 """Download competition leaderboard # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competition_download_leaderboard(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competition_download_leaderboard_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competition_download_leaderboard_with_http_info(id, **kwargs) # noqa: E501 return data
[ "def", "competition_download_leaderboard", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competition_download_leaderboard_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competition_download_leaderboard_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Download competition leaderboard # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competition_download_leaderboard(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Download", "competition", "leaderboard", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L52-L71
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competition_view_leaderboard
def competition_view_leaderboard(self, id, **kwargs): # noqa: E501 """VIew competition leaderboard # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competition_view_leaderboard(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competition_view_leaderboard_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competition_view_leaderboard_with_http_info(id, **kwargs) # noqa: E501 return data
python
def competition_view_leaderboard(self, id, **kwargs): # noqa: E501 """VIew competition leaderboard # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competition_view_leaderboard(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competition_view_leaderboard_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competition_view_leaderboard_with_http_info(id, **kwargs) # noqa: E501 return data
[ "def", "competition_view_leaderboard", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competition_view_leaderboard_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competition_view_leaderboard_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
VIew competition leaderboard # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competition_view_leaderboard(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "VIew", "competition", "leaderboard", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L141-L160
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competitions_data_download_file
def competitions_data_download_file(self, id, file_name, **kwargs): # noqa: E501 """Download competition data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_download_file(id, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param str file_name: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_data_download_file_with_http_info(id, file_name, **kwargs) # noqa: E501 else: (data) = self.competitions_data_download_file_with_http_info(id, file_name, **kwargs) # noqa: E501 return data
python
def competitions_data_download_file(self, id, file_name, **kwargs): # noqa: E501 """Download competition data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_download_file(id, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param str file_name: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_data_download_file_with_http_info(id, file_name, **kwargs) # noqa: E501 else: (data) = self.competitions_data_download_file_with_http_info(id, file_name, **kwargs) # noqa: E501 return data
[ "def", "competitions_data_download_file", "(", "self", ",", "id", ",", "file_name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competitions_data_download_file_with_http_info", "(", "id", ",", "file_name", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competitions_data_download_file_with_http_info", "(", "id", ",", "file_name", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Download competition data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_download_file(id, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param str file_name: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Download", "competition", "data", "file", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L230-L250
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competitions_data_list_files
def competitions_data_list_files(self, id, **kwargs): # noqa: E501 """List competition data files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_list_files(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_data_list_files_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competitions_data_list_files_with_http_info(id, **kwargs) # noqa: E501 return data
python
def competitions_data_list_files(self, id, **kwargs): # noqa: E501 """List competition data files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_list_files(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_data_list_files_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competitions_data_list_files_with_http_info(id, **kwargs) # noqa: E501 return data
[ "def", "competitions_data_list_files", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competitions_data_list_files_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competitions_data_list_files_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
List competition data files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_data_list_files(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "List", "competition", "data", "files", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L327-L346
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competitions_list
def competitions_list(self, **kwargs): # noqa: E501 """List competitions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_list(async_req=True) >>> result = thread.get() :param async_req bool :param str group: Filter competitions by a particular group :param str category: Filter competitions by a particular category :param str sort_by: Sort the results :param int page: Page number :param str search: Search terms :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_list_with_http_info(**kwargs) # noqa: E501 else: (data) = self.competitions_list_with_http_info(**kwargs) # noqa: E501 return data
python
def competitions_list(self, **kwargs): # noqa: E501 """List competitions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_list(async_req=True) >>> result = thread.get() :param async_req bool :param str group: Filter competitions by a particular group :param str category: Filter competitions by a particular category :param str sort_by: Sort the results :param int page: Page number :param str search: Search terms :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_list_with_http_info(**kwargs) # noqa: E501 else: (data) = self.competitions_list_with_http_info(**kwargs) # noqa: E501 return data
[ "def", "competitions_list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competitions_list_with_http_info", "(", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competitions_list_with_http_info", "(", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
List competitions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_list(async_req=True) >>> result = thread.get() :param async_req bool :param str group: Filter competitions by a particular group :param str category: Filter competitions by a particular category :param str sort_by: Sort the results :param int page: Page number :param str search: Search terms :return: Result If the method is called asynchronously, returns the request thread.
[ "List", "competitions", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L420-L443
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competitions_submissions_list
def competitions_submissions_list(self, id, **kwargs): # noqa: E501 """List competition submissions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_list(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param int page: Page number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_list_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_list_with_http_info(id, **kwargs) # noqa: E501 return data
python
def competitions_submissions_list(self, id, **kwargs): # noqa: E501 """List competition submissions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_list(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param int page: Page number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_list_with_http_info(id, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_list_with_http_info(id, **kwargs) # noqa: E501 return data
[ "def", "competitions_submissions_list", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competitions_submissions_list_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competitions_submissions_list_with_http_info", "(", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
List competition submissions # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_list(id, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name (required) :param int page: Page number :return: Result If the method is called asynchronously, returns the request thread.
[ "List", "competition", "submissions", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L525-L545
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competitions_submissions_submit
def competitions_submissions_submit(self, blob_file_tokens, submission_description, id, **kwargs): # noqa: E501 """Submit to competition # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_submit(blob_file_tokens, submission_description, id, async_req=True) >>> result = thread.get() :param async_req bool :param str blob_file_tokens: Token identifying location of uploaded submission file (required) :param str submission_description: Description of competition submission (required) :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_submit_with_http_info(blob_file_tokens, submission_description, id, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_submit_with_http_info(blob_file_tokens, submission_description, id, **kwargs) # noqa: E501 return data
python
def competitions_submissions_submit(self, blob_file_tokens, submission_description, id, **kwargs): # noqa: E501 """Submit to competition # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_submit(blob_file_tokens, submission_description, id, async_req=True) >>> result = thread.get() :param async_req bool :param str blob_file_tokens: Token identifying location of uploaded submission file (required) :param str submission_description: Description of competition submission (required) :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_submit_with_http_info(blob_file_tokens, submission_description, id, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_submit_with_http_info(blob_file_tokens, submission_description, id, **kwargs) # noqa: E501 return data
[ "def", "competitions_submissions_submit", "(", "self", ",", "blob_file_tokens", ",", "submission_description", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competitions_submissions_submit_with_http_info", "(", "blob_file_tokens", ",", "submission_description", ",", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competitions_submissions_submit_with_http_info", "(", "blob_file_tokens", ",", "submission_description", ",", "id", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Submit to competition # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_submit(blob_file_tokens, submission_description, id, async_req=True) >>> result = thread.get() :param async_req bool :param str blob_file_tokens: Token identifying location of uploaded submission file (required) :param str submission_description: Description of competition submission (required) :param str id: Competition name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Submit", "to", "competition", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L622-L643
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competitions_submissions_upload
def competitions_submissions_upload(self, file, guid, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Upload competition submission file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_upload(file, guid, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param file file: Competition submission file (required) :param str guid: Location where submission should be uploaded (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_upload_with_http_info(file, guid, content_length, last_modified_date_utc, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_upload_with_http_info(file, guid, content_length, last_modified_date_utc, **kwargs) # noqa: E501 return data
python
def competitions_submissions_upload(self, file, guid, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Upload competition submission file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_upload(file, guid, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param file file: Competition submission file (required) :param str guid: Location where submission should be uploaded (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_upload_with_http_info(file, guid, content_length, last_modified_date_utc, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_upload_with_http_info(file, guid, content_length, last_modified_date_utc, **kwargs) # noqa: E501 return data
[ "def", "competitions_submissions_upload", "(", "self", ",", "file", ",", "guid", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competitions_submissions_upload_with_http_info", "(", "file", ",", "guid", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competitions_submissions_upload_with_http_info", "(", "file", ",", "guid", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Upload competition submission file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_upload(file, guid, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param file file: Competition submission file (required) :param str guid: Location where submission should be uploaded (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Upload", "competition", "submission", "file", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L735-L757
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.competitions_submissions_url
def competitions_submissions_url(self, id, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Generate competition submission URL # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_url(id, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name, as it appears in the competition's URL (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :param str file_name: Competition submission file name :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_url_with_http_info(id, content_length, last_modified_date_utc, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_url_with_http_info(id, content_length, last_modified_date_utc, **kwargs) # noqa: E501 return data
python
def competitions_submissions_url(self, id, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Generate competition submission URL # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_url(id, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name, as it appears in the competition's URL (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :param str file_name: Competition submission file name :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.competitions_submissions_url_with_http_info(id, content_length, last_modified_date_utc, **kwargs) # noqa: E501 else: (data) = self.competitions_submissions_url_with_http_info(id, content_length, last_modified_date_utc, **kwargs) # noqa: E501 return data
[ "def", "competitions_submissions_url", "(", "self", ",", "id", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "competitions_submissions_url_with_http_info", "(", "id", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "competitions_submissions_url_with_http_info", "(", "id", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Generate competition submission URL # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.competitions_submissions_url(id, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param str id: Competition name, as it appears in the competition's URL (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :param str file_name: Competition submission file name :return: Result If the method is called asynchronously, returns the request thread.
[ "Generate", "competition", "submission", "URL", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L856-L878
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_create_new
def datasets_create_new(self, dataset_new_request, **kwargs): # noqa: E501 """Create a new dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_new(dataset_new_request, async_req=True) >>> result = thread.get() :param async_req bool :param DatasetNewRequest dataset_new_request: Information for creating a new dataset (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_create_new_with_http_info(dataset_new_request, **kwargs) # noqa: E501 else: (data) = self.datasets_create_new_with_http_info(dataset_new_request, **kwargs) # noqa: E501 return data
python
def datasets_create_new(self, dataset_new_request, **kwargs): # noqa: E501 """Create a new dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_new(dataset_new_request, async_req=True) >>> result = thread.get() :param async_req bool :param DatasetNewRequest dataset_new_request: Information for creating a new dataset (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_create_new_with_http_info(dataset_new_request, **kwargs) # noqa: E501 else: (data) = self.datasets_create_new_with_http_info(dataset_new_request, **kwargs) # noqa: E501 return data
[ "def", "datasets_create_new", "(", "self", ",", "dataset_new_request", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_create_new_with_http_info", "(", "dataset_new_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_create_new_with_http_info", "(", "dataset_new_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Create a new dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_new(dataset_new_request, async_req=True) >>> result = thread.get() :param async_req bool :param DatasetNewRequest dataset_new_request: Information for creating a new dataset (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Create", "a", "new", "dataset", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L973-L992
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_create_version
def datasets_create_version(self, owner_slug, dataset_slug, dataset_new_version_request, **kwargs): # noqa: E501 """Create a new dataset version # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_version(owner_slug, dataset_slug, dataset_new_version_request, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param DatasetNewVersionRequest dataset_new_version_request: Information for creating a new dataset version (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_create_version_with_http_info(owner_slug, dataset_slug, dataset_new_version_request, **kwargs) # noqa: E501 else: (data) = self.datasets_create_version_with_http_info(owner_slug, dataset_slug, dataset_new_version_request, **kwargs) # noqa: E501 return data
python
def datasets_create_version(self, owner_slug, dataset_slug, dataset_new_version_request, **kwargs): # noqa: E501 """Create a new dataset version # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_version(owner_slug, dataset_slug, dataset_new_version_request, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param DatasetNewVersionRequest dataset_new_version_request: Information for creating a new dataset version (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_create_version_with_http_info(owner_slug, dataset_slug, dataset_new_version_request, **kwargs) # noqa: E501 else: (data) = self.datasets_create_version_with_http_info(owner_slug, dataset_slug, dataset_new_version_request, **kwargs) # noqa: E501 return data
[ "def", "datasets_create_version", "(", "self", ",", "owner_slug", ",", "dataset_slug", ",", "dataset_new_version_request", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_create_version_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "dataset_new_version_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_create_version_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "dataset_new_version_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Create a new dataset version # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_version(owner_slug, dataset_slug, dataset_new_version_request, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param DatasetNewVersionRequest dataset_new_version_request: Information for creating a new dataset version (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Create", "a", "new", "dataset", "version", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1070-L1091
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_create_version_by_id
def datasets_create_version_by_id(self, id, dataset_new_version_request, **kwargs): # noqa: E501 """Create a new dataset version by id # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_version_by_id(id, dataset_new_version_request, async_req=True) >>> result = thread.get() :param async_req bool :param int id: Dataset ID (required) :param DatasetNewVersionRequest dataset_new_version_request: Information for creating a new dataset version (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_create_version_by_id_with_http_info(id, dataset_new_version_request, **kwargs) # noqa: E501 else: (data) = self.datasets_create_version_by_id_with_http_info(id, dataset_new_version_request, **kwargs) # noqa: E501 return data
python
def datasets_create_version_by_id(self, id, dataset_new_version_request, **kwargs): # noqa: E501 """Create a new dataset version by id # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_version_by_id(id, dataset_new_version_request, async_req=True) >>> result = thread.get() :param async_req bool :param int id: Dataset ID (required) :param DatasetNewVersionRequest dataset_new_version_request: Information for creating a new dataset version (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_create_version_by_id_with_http_info(id, dataset_new_version_request, **kwargs) # noqa: E501 else: (data) = self.datasets_create_version_by_id_with_http_info(id, dataset_new_version_request, **kwargs) # noqa: E501 return data
[ "def", "datasets_create_version_by_id", "(", "self", ",", "id", ",", "dataset_new_version_request", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_create_version_by_id_with_http_info", "(", "id", ",", "dataset_new_version_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_create_version_by_id_with_http_info", "(", "id", ",", "dataset_new_version_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Create a new dataset version by id # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_create_version_by_id(id, dataset_new_version_request, async_req=True) >>> result = thread.get() :param async_req bool :param int id: Dataset ID (required) :param DatasetNewVersionRequest dataset_new_version_request: Information for creating a new dataset version (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Create", "a", "new", "dataset", "version", "by", "id", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1183-L1203
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_download
def datasets_download(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """Download dataset file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_download(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param str dataset_version_number: Dataset version number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
python
def datasets_download(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """Download dataset file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_download(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param str dataset_version_number: Dataset version number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_download_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
[ "def", "datasets_download", "(", "self", ",", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_download_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_download_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Download dataset file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_download(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param str dataset_version_number: Dataset version number :return: Result If the method is called asynchronously, returns the request thread.
[ "Download", "dataset", "file", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1288-L1309
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_download_file
def datasets_download_file(self, owner_slug, dataset_slug, file_name, **kwargs): # noqa: E501 """Download dataset file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_download_file(owner_slug, dataset_slug, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param str file_name: File name (required) :param str dataset_version_number: Dataset version number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_download_file_with_http_info(owner_slug, dataset_slug, file_name, **kwargs) # noqa: E501 else: (data) = self.datasets_download_file_with_http_info(owner_slug, dataset_slug, file_name, **kwargs) # noqa: E501 return data
python
def datasets_download_file(self, owner_slug, dataset_slug, file_name, **kwargs): # noqa: E501 """Download dataset file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_download_file(owner_slug, dataset_slug, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param str file_name: File name (required) :param str dataset_version_number: Dataset version number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_download_file_with_http_info(owner_slug, dataset_slug, file_name, **kwargs) # noqa: E501 else: (data) = self.datasets_download_file_with_http_info(owner_slug, dataset_slug, file_name, **kwargs) # noqa: E501 return data
[ "def", "datasets_download_file", "(", "self", ",", "owner_slug", ",", "dataset_slug", ",", "file_name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_download_file_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "file_name", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_download_file_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "file_name", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Download dataset file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_download_file(owner_slug, dataset_slug, file_name, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :param str file_name: File name (required) :param str dataset_version_number: Dataset version number :return: Result If the method is called asynchronously, returns the request thread.
[ "Download", "dataset", "file", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1393-L1415
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_list
def datasets_list(self, **kwargs): # noqa: E501 """List datasets # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_list(async_req=True) >>> result = thread.get() :param async_req bool :param str group: Display datasets by a particular group :param str sort_by: Sort the results :param str size: Display datasets of a specific size :param str filetype: Display datasets of a specific file type :param str license: Display datasets with a specific license :param str tagids: A comma separated list of tags to filter by :param str search: Search terms :param str user: Display datasets by a specific user or organization :param int page: Page number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_list_with_http_info(**kwargs) # noqa: E501 else: (data) = self.datasets_list_with_http_info(**kwargs) # noqa: E501 return data
python
def datasets_list(self, **kwargs): # noqa: E501 """List datasets # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_list(async_req=True) >>> result = thread.get() :param async_req bool :param str group: Display datasets by a particular group :param str sort_by: Sort the results :param str size: Display datasets of a specific size :param str filetype: Display datasets of a specific file type :param str license: Display datasets with a specific license :param str tagids: A comma separated list of tags to filter by :param str search: Search terms :param str user: Display datasets by a specific user or organization :param int page: Page number :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_list_with_http_info(**kwargs) # noqa: E501 else: (data) = self.datasets_list_with_http_info(**kwargs) # noqa: E501 return data
[ "def", "datasets_list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_list_with_http_info", "(", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_list_with_http_info", "(", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
List datasets # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_list(async_req=True) >>> result = thread.get() :param async_req bool :param str group: Display datasets by a particular group :param str sort_by: Sort the results :param str size: Display datasets of a specific size :param str filetype: Display datasets of a specific file type :param str license: Display datasets with a specific license :param str tagids: A comma separated list of tags to filter by :param str search: Search terms :param str user: Display datasets by a specific user or organization :param int page: Page number :return: Result If the method is called asynchronously, returns the request thread.
[ "List", "datasets", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1506-L1533
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_list_files
def datasets_list_files(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """List dataset files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_list_files(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_list_files_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_list_files_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
python
def datasets_list_files(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """List dataset files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_list_files(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_list_files_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_list_files_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
[ "def", "datasets_list_files", "(", "self", ",", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_list_files_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_list_files_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
List dataset files # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_list_files(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "List", "dataset", "files", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1627-L1647
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_status
def datasets_status(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """Get dataset creation status # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_status(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_status_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_status_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
python
def datasets_status(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """Get dataset creation status # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_status(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_status_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_status_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
[ "def", "datasets_status", "(", "self", ",", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_status_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_status_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Get dataset creation status # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_status(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Get", "dataset", "creation", "status", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1728-L1748
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_upload_file
def datasets_upload_file(self, file_name, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Get URL and token to start uploading a data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_upload_file(file_name, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param str file_name: Dataset file name (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_upload_file_with_http_info(file_name, content_length, last_modified_date_utc, **kwargs) # noqa: E501 else: (data) = self.datasets_upload_file_with_http_info(file_name, content_length, last_modified_date_utc, **kwargs) # noqa: E501 return data
python
def datasets_upload_file(self, file_name, content_length, last_modified_date_utc, **kwargs): # noqa: E501 """Get URL and token to start uploading a data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_upload_file(file_name, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param str file_name: Dataset file name (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_upload_file_with_http_info(file_name, content_length, last_modified_date_utc, **kwargs) # noqa: E501 else: (data) = self.datasets_upload_file_with_http_info(file_name, content_length, last_modified_date_utc, **kwargs) # noqa: E501 return data
[ "def", "datasets_upload_file", "(", "self", ",", "file_name", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_upload_file_with_http_info", "(", "file_name", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_upload_file_with_http_info", "(", "file_name", ",", "content_length", ",", "last_modified_date_utc", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Get URL and token to start uploading a data file # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_upload_file(file_name, content_length, last_modified_date_utc, async_req=True) >>> result = thread.get() :param async_req bool :param str file_name: Dataset file name (required) :param int content_length: Content length of file in bytes (required) :param int last_modified_date_utc: Last modified date of file in milliseconds since epoch in UTC (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Get", "URL", "and", "token", "to", "start", "uploading", "a", "data", "file", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1829-L1850
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.datasets_view
def datasets_view(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """Show details about a dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_view(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_view_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_view_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
python
def datasets_view(self, owner_slug, dataset_slug, **kwargs): # noqa: E501 """Show details about a dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_view(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.datasets_view_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 else: (data) = self.datasets_view_with_http_info(owner_slug, dataset_slug, **kwargs) # noqa: E501 return data
[ "def", "datasets_view", "(", "self", ",", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "datasets_view_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "datasets_view_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Show details about a dataset # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.datasets_view(owner_slug, dataset_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str owner_slug: Dataset owner (required) :param str dataset_slug: Dataset name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Show", "details", "about", "a", "dataset", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L1942-L1962
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.kernel_output
def kernel_output(self, user_name, kernel_slug, **kwargs): # noqa: E501 """Download the latest output from a kernel # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_output(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_output_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 else: (data) = self.kernel_output_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 return data
python
def kernel_output(self, user_name, kernel_slug, **kwargs): # noqa: E501 """Download the latest output from a kernel # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_output(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_output_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 else: (data) = self.kernel_output_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 return data
[ "def", "kernel_output", "(", "self", ",", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "kernel_output_with_http_info", "(", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "kernel_output_with_http_info", "(", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Download the latest output from a kernel # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_output(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Download", "the", "latest", "output", "from", "a", "kernel", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L2043-L2063
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.kernel_pull
def kernel_pull(self, user_name, kernel_slug, **kwargs): # noqa: E501 """Pull the latest code from a kernel # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_pull(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_pull_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 else: (data) = self.kernel_pull_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 return data
python
def kernel_pull(self, user_name, kernel_slug, **kwargs): # noqa: E501 """Pull the latest code from a kernel # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_pull(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_pull_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 else: (data) = self.kernel_pull_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 return data
[ "def", "kernel_pull", "(", "self", ",", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "kernel_pull_with_http_info", "(", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "kernel_pull_with_http_info", "(", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Pull the latest code from a kernel # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_pull(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Pull", "the", "latest", "code", "from", "a", "kernel", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L2144-L2164
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.kernel_push
def kernel_push(self, kernel_push_request, **kwargs): # noqa: E501 """Push a new kernel version. Can be used to create a new kernel and update an existing one. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_push(kernel_push_request, async_req=True) >>> result = thread.get() :param async_req bool :param KernelPushRequest kernel_push_request: Information for pushing a new kernel version (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_push_with_http_info(kernel_push_request, **kwargs) # noqa: E501 else: (data) = self.kernel_push_with_http_info(kernel_push_request, **kwargs) # noqa: E501 return data
python
def kernel_push(self, kernel_push_request, **kwargs): # noqa: E501 """Push a new kernel version. Can be used to create a new kernel and update an existing one. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_push(kernel_push_request, async_req=True) >>> result = thread.get() :param async_req bool :param KernelPushRequest kernel_push_request: Information for pushing a new kernel version (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_push_with_http_info(kernel_push_request, **kwargs) # noqa: E501 else: (data) = self.kernel_push_with_http_info(kernel_push_request, **kwargs) # noqa: E501 return data
[ "def", "kernel_push", "(", "self", ",", "kernel_push_request", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "kernel_push_with_http_info", "(", "kernel_push_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "kernel_push_with_http_info", "(", "kernel_push_request", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Push a new kernel version. Can be used to create a new kernel and update an existing one. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_push(kernel_push_request, async_req=True) >>> result = thread.get() :param async_req bool :param KernelPushRequest kernel_push_request: Information for pushing a new kernel version (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Push", "a", "new", "kernel", "version", ".", "Can", "be", "used", "to", "create", "a", "new", "kernel", "and", "update", "an", "existing", "one", ".", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L2245-L2264
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.kernel_status
def kernel_status(self, user_name, kernel_slug, **kwargs): # noqa: E501 """Get the status of the latest kernel version # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_status(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_status_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 else: (data) = self.kernel_status_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 return data
python
def kernel_status(self, user_name, kernel_slug, **kwargs): # noqa: E501 """Get the status of the latest kernel version # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_status(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernel_status_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 else: (data) = self.kernel_status_with_http_info(user_name, kernel_slug, **kwargs) # noqa: E501 return data
[ "def", "kernel_status", "(", "self", ",", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "kernel_status_with_http_info", "(", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "kernel_status_with_http_info", "(", "user_name", ",", "kernel_slug", ",", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
Get the status of the latest kernel version # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernel_status(user_name, kernel_slug, async_req=True) >>> result = thread.get() :param async_req bool :param str user_name: Kernel owner (required) :param str kernel_slug: Kernel name (required) :return: Result If the method is called asynchronously, returns the request thread.
[ "Get", "the", "status", "of", "the", "latest", "kernel", "version", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L2342-L2362
train
Kaggle/kaggle-api
kaggle/api/kaggle_api.py
KaggleApi.kernels_list
def kernels_list(self, **kwargs): # noqa: E501 """List kernels # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernels_list(async_req=True) >>> result = thread.get() :param async_req bool :param int page: Page number :param int page_size: Page size :param str search: Search terms :param str group: Display only your kernels :param str user: Display kernels by a particular group :param str language: Display kernels in a specific language :param str kernel_type: Display kernels of a specific type :param str output_type: Display kernels with a specific output type :param str sort_by: Sort the results. 'relevance' only works if there is a search query :param str dataset: Display kernels using the specified dataset :param str competition: Display kernels using the specified competition :param str parent_kernel: Display kernels that have forked the specified kernel :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernels_list_with_http_info(**kwargs) # noqa: E501 else: (data) = self.kernels_list_with_http_info(**kwargs) # noqa: E501 return data
python
def kernels_list(self, **kwargs): # noqa: E501 """List kernels # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernels_list(async_req=True) >>> result = thread.get() :param async_req bool :param int page: Page number :param int page_size: Page size :param str search: Search terms :param str group: Display only your kernels :param str user: Display kernels by a particular group :param str language: Display kernels in a specific language :param str kernel_type: Display kernels of a specific type :param str output_type: Display kernels with a specific output type :param str sort_by: Sort the results. 'relevance' only works if there is a search query :param str dataset: Display kernels using the specified dataset :param str competition: Display kernels using the specified competition :param str parent_kernel: Display kernels that have forked the specified kernel :return: Result If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.kernels_list_with_http_info(**kwargs) # noqa: E501 else: (data) = self.kernels_list_with_http_info(**kwargs) # noqa: E501 return data
[ "def", "kernels_list", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "kernels_list_with_http_info", "(", "*", "*", "kwargs", ")", "# noqa: E501", "else", ":", "(", "data", ")", "=", "self", ".", "kernels_list_with_http_info", "(", "*", "*", "kwargs", ")", "# noqa: E501", "return", "data" ]
List kernels # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.kernels_list(async_req=True) >>> result = thread.get() :param async_req bool :param int page: Page number :param int page_size: Page size :param str search: Search terms :param str group: Display only your kernels :param str user: Display kernels by a particular group :param str language: Display kernels in a specific language :param str kernel_type: Display kernels of a specific type :param str output_type: Display kernels with a specific output type :param str sort_by: Sort the results. 'relevance' only works if there is a search query :param str dataset: Display kernels using the specified dataset :param str competition: Display kernels using the specified competition :param str parent_kernel: Display kernels that have forked the specified kernel :return: Result If the method is called asynchronously, returns the request thread.
[ "List", "kernels", "#", "noqa", ":", "E501" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api.py#L2443-L2473
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.authenticate
def authenticate(self): """authenticate the user with the Kaggle API. This method will generate a configuration, first checking the environment for credential variables, and falling back to looking for the .kaggle/kaggle.json configuration file. """ config_data = {} # Step 1: try getting username/password from environment config_data = self.read_config_environment(config_data) # Step 2: if credentials were not in env read in configuration file if self.CONFIG_NAME_USER not in config_data \ or self.CONFIG_NAME_KEY not in config_data: if os.path.exists(self.config): config_data = self.read_config_file(config_data) else: raise IOError('Could not find {}. Make sure it\'s located in' ' {}. Or use the environment method.'.format( self.config_file, self.config_dir)) # Step 3: load into configuration! self._load_config(config_data)
python
def authenticate(self): """authenticate the user with the Kaggle API. This method will generate a configuration, first checking the environment for credential variables, and falling back to looking for the .kaggle/kaggle.json configuration file. """ config_data = {} # Step 1: try getting username/password from environment config_data = self.read_config_environment(config_data) # Step 2: if credentials were not in env read in configuration file if self.CONFIG_NAME_USER not in config_data \ or self.CONFIG_NAME_KEY not in config_data: if os.path.exists(self.config): config_data = self.read_config_file(config_data) else: raise IOError('Could not find {}. Make sure it\'s located in' ' {}. Or use the environment method.'.format( self.config_file, self.config_dir)) # Step 3: load into configuration! self._load_config(config_data)
[ "def", "authenticate", "(", "self", ")", ":", "config_data", "=", "{", "}", "# Step 1: try getting username/password from environment", "config_data", "=", "self", ".", "read_config_environment", "(", "config_data", ")", "# Step 2: if credentials were not in env read in configuration file", "if", "self", ".", "CONFIG_NAME_USER", "not", "in", "config_data", "or", "self", ".", "CONFIG_NAME_KEY", "not", "in", "config_data", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "config", ")", ":", "config_data", "=", "self", ".", "read_config_file", "(", "config_data", ")", "else", ":", "raise", "IOError", "(", "'Could not find {}. Make sure it\\'s located in'", "' {}. Or use the environment method.'", ".", "format", "(", "self", ".", "config_file", ",", "self", ".", "config_dir", ")", ")", "# Step 3: load into configuration!", "self", ".", "_load_config", "(", "config_data", ")" ]
authenticate the user with the Kaggle API. This method will generate a configuration, first checking the environment for credential variables, and falling back to looking for the .kaggle/kaggle.json configuration file.
[ "authenticate", "the", "user", "with", "the", "Kaggle", "API", ".", "This", "method", "will", "generate", "a", "configuration", "first", "checking", "the", "environment", "for", "credential", "variables", "and", "falling", "back", "to", "looking", "for", "the", ".", "kaggle", "/", "kaggle", ".", "json", "configuration", "file", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L96-L119
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.read_config_environment
def read_config_environment(self, config_data=None, quiet=False): """read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a unique namespace. Parameters ========== config_data: a partially loaded configuration dictionary (optional) quiet: suppress verbose print of output (default is False) """ # Add all variables that start with KAGGLE_ to config data if config_data is None: config_data = {} for key, val in os.environ.items(): if key.startswith('KAGGLE_'): config_key = key.replace('KAGGLE_', '', 1).lower() config_data[config_key] = val return config_data
python
def read_config_environment(self, config_data=None, quiet=False): """read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a unique namespace. Parameters ========== config_data: a partially loaded configuration dictionary (optional) quiet: suppress verbose print of output (default is False) """ # Add all variables that start with KAGGLE_ to config data if config_data is None: config_data = {} for key, val in os.environ.items(): if key.startswith('KAGGLE_'): config_key = key.replace('KAGGLE_', '', 1).lower() config_data[config_key] = val return config_data
[ "def", "read_config_environment", "(", "self", ",", "config_data", "=", "None", ",", "quiet", "=", "False", ")", ":", "# Add all variables that start with KAGGLE_ to config data", "if", "config_data", "is", "None", ":", "config_data", "=", "{", "}", "for", "key", ",", "val", "in", "os", ".", "environ", ".", "items", "(", ")", ":", "if", "key", ".", "startswith", "(", "'KAGGLE_'", ")", ":", "config_key", "=", "key", ".", "replace", "(", "'KAGGLE_'", ",", "''", ",", "1", ")", ".", "lower", "(", ")", "config_data", "[", "config_key", "]", "=", "val", "return", "config_data" ]
read_config_environment is the second effort to get a username and key to authenticate to the Kaggle API. The environment keys are equivalent to the kaggle.json file, but with "KAGGLE_" prefix to define a unique namespace. Parameters ========== config_data: a partially loaded configuration dictionary (optional) quiet: suppress verbose print of output (default is False)
[ "read_config_environment", "is", "the", "second", "effort", "to", "get", "a", "username", "and", "key", "to", "authenticate", "to", "the", "Kaggle", "API", ".", "The", "environment", "keys", "are", "equivalent", "to", "the", "kaggle", ".", "json", "file", "but", "with", "KAGGLE_", "prefix", "to", "define", "a", "unique", "namespace", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L121-L142
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi._load_config
def _load_config(self, config_data): """the final step of the authenticate steps, where we load the values from config_data into the Configuration object. Parameters ========== config_data: a dictionary with configuration values (keys) to read into self.config_values """ # Username and password are required. for item in [self.CONFIG_NAME_USER, self.CONFIG_NAME_KEY]: if item not in config_data: raise ValueError('Error: Missing %s in configuration.' % item) configuration = Configuration() # Add to the final configuration (required) configuration.username = config_data[self.CONFIG_NAME_USER] configuration.password = config_data[self.CONFIG_NAME_KEY] # Proxy if self.CONFIG_NAME_PROXY in config_data: configuration.proxy = config_data[self.CONFIG_NAME_PROXY] # Cert File if self.CONFIG_NAME_SSL_CA_CERT in config_data: configuration.ssl_ca_cert = config_data[self. CONFIG_NAME_SSL_CA_CERT] # Keep config values with class instance, and load api client! self.config_values = config_data try: self.api_client = ApiClient(configuration) except Exception as error: if 'Proxy' in type(error).__name__: raise ValueError( 'The specified proxy ' + config_data[self.CONFIG_NAME_PROXY] + ' is not valid, please check your proxy settings') else: raise ValueError( 'Unauthorized: you must download an API key or export ' 'credentials to the environment. Please see\n ' + 'https://github.com/Kaggle/kaggle-api#api-credentials ' + 'for instructions.')
python
def _load_config(self, config_data): """the final step of the authenticate steps, where we load the values from config_data into the Configuration object. Parameters ========== config_data: a dictionary with configuration values (keys) to read into self.config_values """ # Username and password are required. for item in [self.CONFIG_NAME_USER, self.CONFIG_NAME_KEY]: if item not in config_data: raise ValueError('Error: Missing %s in configuration.' % item) configuration = Configuration() # Add to the final configuration (required) configuration.username = config_data[self.CONFIG_NAME_USER] configuration.password = config_data[self.CONFIG_NAME_KEY] # Proxy if self.CONFIG_NAME_PROXY in config_data: configuration.proxy = config_data[self.CONFIG_NAME_PROXY] # Cert File if self.CONFIG_NAME_SSL_CA_CERT in config_data: configuration.ssl_ca_cert = config_data[self. CONFIG_NAME_SSL_CA_CERT] # Keep config values with class instance, and load api client! self.config_values = config_data try: self.api_client = ApiClient(configuration) except Exception as error: if 'Proxy' in type(error).__name__: raise ValueError( 'The specified proxy ' + config_data[self.CONFIG_NAME_PROXY] + ' is not valid, please check your proxy settings') else: raise ValueError( 'Unauthorized: you must download an API key or export ' 'credentials to the environment. Please see\n ' + 'https://github.com/Kaggle/kaggle-api#api-credentials ' + 'for instructions.')
[ "def", "_load_config", "(", "self", ",", "config_data", ")", ":", "# Username and password are required.", "for", "item", "in", "[", "self", ".", "CONFIG_NAME_USER", ",", "self", ".", "CONFIG_NAME_KEY", "]", ":", "if", "item", "not", "in", "config_data", ":", "raise", "ValueError", "(", "'Error: Missing %s in configuration.'", "%", "item", ")", "configuration", "=", "Configuration", "(", ")", "# Add to the final configuration (required)", "configuration", ".", "username", "=", "config_data", "[", "self", ".", "CONFIG_NAME_USER", "]", "configuration", ".", "password", "=", "config_data", "[", "self", ".", "CONFIG_NAME_KEY", "]", "# Proxy", "if", "self", ".", "CONFIG_NAME_PROXY", "in", "config_data", ":", "configuration", ".", "proxy", "=", "config_data", "[", "self", ".", "CONFIG_NAME_PROXY", "]", "# Cert File", "if", "self", ".", "CONFIG_NAME_SSL_CA_CERT", "in", "config_data", ":", "configuration", ".", "ssl_ca_cert", "=", "config_data", "[", "self", ".", "CONFIG_NAME_SSL_CA_CERT", "]", "# Keep config values with class instance, and load api client!", "self", ".", "config_values", "=", "config_data", "try", ":", "self", ".", "api_client", "=", "ApiClient", "(", "configuration", ")", "except", "Exception", "as", "error", ":", "if", "'Proxy'", "in", "type", "(", "error", ")", ".", "__name__", ":", "raise", "ValueError", "(", "'The specified proxy '", "+", "config_data", "[", "self", ".", "CONFIG_NAME_PROXY", "]", "+", "' is not valid, please check your proxy settings'", ")", "else", ":", "raise", "ValueError", "(", "'Unauthorized: you must download an API key or export '", "'credentials to the environment. Please see\\n '", "+", "'https://github.com/Kaggle/kaggle-api#api-credentials '", "+", "'for instructions.'", ")" ]
the final step of the authenticate steps, where we load the values from config_data into the Configuration object. Parameters ========== config_data: a dictionary with configuration values (keys) to read into self.config_values
[ "the", "final", "step", "of", "the", "authenticate", "steps", "where", "we", "load", "the", "values", "from", "config_data", "into", "the", "Configuration", "object", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L146-L199
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.read_config_file
def read_config_file(self, config_data=None, quiet=False): """read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. Since we can get the username and password from the environment, it's not required. Parameters ========== config_data: the Configuration object to save a username and password, if defined quiet: suppress verbose print of output (default is False) """ if config_data is None: config_data = {} if os.path.exists(self.config): try: if os.name != 'nt': permissions = os.stat(self.config).st_mode if (permissions & 4) or (permissions & 32): print( 'Warning: Your Kaggle API key is readable by other ' 'users on this system! To fix this, you can run ' + '\'chmod 600 {}\''.format(self.config)) with open(self.config) as f: config_data = json.load(f) except: pass else: # Warn the user that configuration will be reliant on environment if not quiet: print('No Kaggle API config file found, will use environment.') return config_data
python
def read_config_file(self, config_data=None, quiet=False): """read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. Since we can get the username and password from the environment, it's not required. Parameters ========== config_data: the Configuration object to save a username and password, if defined quiet: suppress verbose print of output (default is False) """ if config_data is None: config_data = {} if os.path.exists(self.config): try: if os.name != 'nt': permissions = os.stat(self.config).st_mode if (permissions & 4) or (permissions & 32): print( 'Warning: Your Kaggle API key is readable by other ' 'users on this system! To fix this, you can run ' + '\'chmod 600 {}\''.format(self.config)) with open(self.config) as f: config_data = json.load(f) except: pass else: # Warn the user that configuration will be reliant on environment if not quiet: print('No Kaggle API config file found, will use environment.') return config_data
[ "def", "read_config_file", "(", "self", ",", "config_data", "=", "None", ",", "quiet", "=", "False", ")", ":", "if", "config_data", "is", "None", ":", "config_data", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "config", ")", ":", "try", ":", "if", "os", ".", "name", "!=", "'nt'", ":", "permissions", "=", "os", ".", "stat", "(", "self", ".", "config", ")", ".", "st_mode", "if", "(", "permissions", "&", "4", ")", "or", "(", "permissions", "&", "32", ")", ":", "print", "(", "'Warning: Your Kaggle API key is readable by other '", "'users on this system! To fix this, you can run '", "+", "'\\'chmod 600 {}\\''", ".", "format", "(", "self", ".", "config", ")", ")", "with", "open", "(", "self", ".", "config", ")", "as", "f", ":", "config_data", "=", "json", ".", "load", "(", "f", ")", "except", ":", "pass", "else", ":", "# Warn the user that configuration will be reliant on environment", "if", "not", "quiet", ":", "print", "(", "'No Kaggle API config file found, will use environment.'", ")", "return", "config_data" ]
read_config_file is the first effort to get a username and key to authenticate to the Kaggle API. Since we can get the username and password from the environment, it's not required. Parameters ========== config_data: the Configuration object to save a username and password, if defined quiet: suppress verbose print of output (default is False)
[ "read_config_file", "is", "the", "first", "effort", "to", "get", "a", "username", "and", "key", "to", "authenticate", "to", "the", "Kaggle", "API", ".", "Since", "we", "can", "get", "the", "username", "and", "password", "from", "the", "environment", "it", "s", "not", "required", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L201-L237
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi._read_config_file
def _read_config_file(self): """read in the configuration file, a json file defined at self.config""" try: with open(self.config, 'r') as f: config_data = json.load(f) except FileNotFoundError: config_data = {} return config_data
python
def _read_config_file(self): """read in the configuration file, a json file defined at self.config""" try: with open(self.config, 'r') as f: config_data = json.load(f) except FileNotFoundError: config_data = {} return config_data
[ "def", "_read_config_file", "(", "self", ")", ":", "try", ":", "with", "open", "(", "self", ".", "config", ",", "'r'", ")", "as", "f", ":", "config_data", "=", "json", ".", "load", "(", "f", ")", "except", "FileNotFoundError", ":", "config_data", "=", "{", "}", "return", "config_data" ]
read in the configuration file, a json file defined at self.config
[ "read", "in", "the", "configuration", "file", "a", "json", "file", "defined", "at", "self", ".", "config" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L239-L248
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi._write_config_file
def _write_config_file(self, config_data, indent=2): """write config data to file. Parameters ========== config_data: the Configuration object to save a username and password, if defined indent: number of tab indentations to use when writing json """ with open(self.config, 'w') as f: json.dump(config_data, f, indent=indent)
python
def _write_config_file(self, config_data, indent=2): """write config data to file. Parameters ========== config_data: the Configuration object to save a username and password, if defined indent: number of tab indentations to use when writing json """ with open(self.config, 'w') as f: json.dump(config_data, f, indent=indent)
[ "def", "_write_config_file", "(", "self", ",", "config_data", ",", "indent", "=", "2", ")", ":", "with", "open", "(", "self", ".", "config", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "config_data", ",", "f", ",", "indent", "=", "indent", ")" ]
write config data to file. Parameters ========== config_data: the Configuration object to save a username and password, if defined indent: number of tab indentations to use when writing json
[ "write", "config", "data", "to", "file", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L250-L260
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.set_config_value
def set_config_value(self, name, value, quiet=False): """a client helper function to set a configuration value, meaning reading in the configuration file (if it exists), saving a new config value, and then writing back Parameters ========== name: the name of the value to set (key in dictionary) value: the value to set at the key quiet: disable verbose output if True (default is False) """ config_data = self._read_config_file() if value is not None: # Update the config file with the value config_data[name] = value # Update the instance with the value self.config_values[name] = value # If defined by client, set and save! self._write_config_file(config_data) if not quiet: self.print_config_value(name, separator=' is now set to: ')
python
def set_config_value(self, name, value, quiet=False): """a client helper function to set a configuration value, meaning reading in the configuration file (if it exists), saving a new config value, and then writing back Parameters ========== name: the name of the value to set (key in dictionary) value: the value to set at the key quiet: disable verbose output if True (default is False) """ config_data = self._read_config_file() if value is not None: # Update the config file with the value config_data[name] = value # Update the instance with the value self.config_values[name] = value # If defined by client, set and save! self._write_config_file(config_data) if not quiet: self.print_config_value(name, separator=' is now set to: ')
[ "def", "set_config_value", "(", "self", ",", "name", ",", "value", ",", "quiet", "=", "False", ")", ":", "config_data", "=", "self", ".", "_read_config_file", "(", ")", "if", "value", "is", "not", "None", ":", "# Update the config file with the value", "config_data", "[", "name", "]", "=", "value", "# Update the instance with the value", "self", ".", "config_values", "[", "name", "]", "=", "value", "# If defined by client, set and save!", "self", ".", "_write_config_file", "(", "config_data", ")", "if", "not", "quiet", ":", "self", ".", "print_config_value", "(", "name", ",", "separator", "=", "' is now set to: '", ")" ]
a client helper function to set a configuration value, meaning reading in the configuration file (if it exists), saving a new config value, and then writing back Parameters ========== name: the name of the value to set (key in dictionary) value: the value to set at the key quiet: disable verbose output if True (default is False)
[ "a", "client", "helper", "function", "to", "set", "a", "configuration", "value", "meaning", "reading", "in", "the", "configuration", "file", "(", "if", "it", "exists", ")", "saving", "a", "new", "config", "value", "and", "then", "writing", "back" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L262-L288
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.unset_config_value
def unset_config_value(self, name, quiet=False): """unset a configuration value Parameters ========== name: the name of the value to unset (remove key in dictionary) quiet: disable verbose output if True (default is False) """ config_data = self._read_config_file() if name in config_data: del config_data[name] self._write_config_file(config_data) if not quiet: self.print_config_value(name, separator=' is now set to: ')
python
def unset_config_value(self, name, quiet=False): """unset a configuration value Parameters ========== name: the name of the value to unset (remove key in dictionary) quiet: disable verbose output if True (default is False) """ config_data = self._read_config_file() if name in config_data: del config_data[name] self._write_config_file(config_data) if not quiet: self.print_config_value(name, separator=' is now set to: ')
[ "def", "unset_config_value", "(", "self", ",", "name", ",", "quiet", "=", "False", ")", ":", "config_data", "=", "self", ".", "_read_config_file", "(", ")", "if", "name", "in", "config_data", ":", "del", "config_data", "[", "name", "]", "self", ".", "_write_config_file", "(", "config_data", ")", "if", "not", "quiet", ":", "self", ".", "print_config_value", "(", "name", ",", "separator", "=", "' is now set to: '", ")" ]
unset a configuration value Parameters ========== name: the name of the value to unset (remove key in dictionary) quiet: disable verbose output if True (default is False)
[ "unset", "a", "configuration", "value", "Parameters", "==========", "name", ":", "the", "name", "of", "the", "value", "to", "unset", "(", "remove", "key", "in", "dictionary", ")", "quiet", ":", "disable", "verbose", "output", "if", "True", "(", "default", "is", "False", ")" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L290-L307
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.get_default_download_dir
def get_default_download_dir(self, *subdirs): """ Get the download path for a file. If not defined, return default from config. Parameters ========== subdirs: a single (or list of) subfolders under the basepath """ # Look up value for key "path" in the config path = self.get_config_value(self.CONFIG_NAME_PATH) # If not set in config, default to present working directory if path is None: return os.getcwd() return os.path.join(path, *subdirs)
python
def get_default_download_dir(self, *subdirs): """ Get the download path for a file. If not defined, return default from config. Parameters ========== subdirs: a single (or list of) subfolders under the basepath """ # Look up value for key "path" in the config path = self.get_config_value(self.CONFIG_NAME_PATH) # If not set in config, default to present working directory if path is None: return os.getcwd() return os.path.join(path, *subdirs)
[ "def", "get_default_download_dir", "(", "self", ",", "*", "subdirs", ")", ":", "# Look up value for key \"path\" in the config", "path", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_PATH", ")", "# If not set in config, default to present working directory", "if", "path", "is", "None", ":", "return", "os", ".", "getcwd", "(", ")", "return", "os", ".", "path", ".", "join", "(", "path", ",", "*", "subdirs", ")" ]
Get the download path for a file. If not defined, return default from config. Parameters ========== subdirs: a single (or list of) subfolders under the basepath
[ "Get", "the", "download", "path", "for", "a", "file", ".", "If", "not", "defined", "return", "default", "from", "config", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L321-L336
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.print_config_value
def print_config_value(self, name, prefix='- ', separator=': '): """print a single configuration value, based on a prefix and separator Parameters ========== name: the key of the config valur in self.config_values to print prefix: the prefix to print separator: the separator to use (default is : ) """ value_out = 'None' if name in self.config_values and self.config_values[name] is not None: value_out = self.config_values[name] print(prefix + name + separator + value_out)
python
def print_config_value(self, name, prefix='- ', separator=': '): """print a single configuration value, based on a prefix and separator Parameters ========== name: the key of the config valur in self.config_values to print prefix: the prefix to print separator: the separator to use (default is : ) """ value_out = 'None' if name in self.config_values and self.config_values[name] is not None: value_out = self.config_values[name] print(prefix + name + separator + value_out)
[ "def", "print_config_value", "(", "self", ",", "name", ",", "prefix", "=", "'- '", ",", "separator", "=", "': '", ")", ":", "value_out", "=", "'None'", "if", "name", "in", "self", ".", "config_values", "and", "self", ".", "config_values", "[", "name", "]", "is", "not", "None", ":", "value_out", "=", "self", ".", "config_values", "[", "name", "]", "print", "(", "prefix", "+", "name", "+", "separator", "+", "value_out", ")" ]
print a single configuration value, based on a prefix and separator Parameters ========== name: the key of the config valur in self.config_values to print prefix: the prefix to print separator: the separator to use (default is : )
[ "print", "a", "single", "configuration", "value", "based", "on", "a", "prefix", "and", "separator" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L338-L351
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.print_config_values
def print_config_values(self, prefix='- '): """a wrapper to print_config_value to print all configuration values Parameters ========== prefix: the character prefix to put before the printed config value defaults to "- " """ print('Configuration values from ' + self.config_dir) self.print_config_value(self.CONFIG_NAME_USER, prefix=prefix) self.print_config_value(self.CONFIG_NAME_PATH, prefix=prefix) self.print_config_value(self.CONFIG_NAME_PROXY, prefix=prefix) self.print_config_value(self.CONFIG_NAME_COMPETITION, prefix=prefix)
python
def print_config_values(self, prefix='- '): """a wrapper to print_config_value to print all configuration values Parameters ========== prefix: the character prefix to put before the printed config value defaults to "- " """ print('Configuration values from ' + self.config_dir) self.print_config_value(self.CONFIG_NAME_USER, prefix=prefix) self.print_config_value(self.CONFIG_NAME_PATH, prefix=prefix) self.print_config_value(self.CONFIG_NAME_PROXY, prefix=prefix) self.print_config_value(self.CONFIG_NAME_COMPETITION, prefix=prefix)
[ "def", "print_config_values", "(", "self", ",", "prefix", "=", "'- '", ")", ":", "print", "(", "'Configuration values from '", "+", "self", ".", "config_dir", ")", "self", ".", "print_config_value", "(", "self", ".", "CONFIG_NAME_USER", ",", "prefix", "=", "prefix", ")", "self", ".", "print_config_value", "(", "self", ".", "CONFIG_NAME_PATH", ",", "prefix", "=", "prefix", ")", "self", ".", "print_config_value", "(", "self", ".", "CONFIG_NAME_PROXY", ",", "prefix", "=", "prefix", ")", "self", ".", "print_config_value", "(", "self", ".", "CONFIG_NAME_COMPETITION", ",", "prefix", "=", "prefix", ")" ]
a wrapper to print_config_value to print all configuration values Parameters ========== prefix: the character prefix to put before the printed config value defaults to "- "
[ "a", "wrapper", "to", "print_config_value", "to", "print", "all", "configuration", "values", "Parameters", "==========", "prefix", ":", "the", "character", "prefix", "to", "put", "before", "the", "printed", "config", "value", "defaults", "to", "-" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L353-L364
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competitions_list
def competitions_list(self, group=None, category=None, sort_by=None, page=1, search=None): """ make call to list competitions, format the response, and return a list of Competition instances Parameters ========== page: the page to return (default is 1) search: a search term to use (default is empty string) sort_by: how to sort the result, see valid_sort_by for options category: category to filter result to group: group to filter result to """ valid_groups = ['general', 'entered', 'inClass'] if group and group not in valid_groups: raise ValueError('Invalid group specified. Valid options are ' + str(valid_groups)) valid_categories = [ 'all', 'featured', 'research', 'recruitment', 'gettingStarted', 'masters', 'playground' ] if category and category not in valid_categories: raise ValueError('Invalid category specified. Valid options are ' + str(valid_categories)) valid_sort_by = [ 'grouped', 'prize', 'earliestDeadline', 'latestDeadline', 'numberOfTeams', 'recentlyCreated' ] if sort_by and sort_by not in valid_sort_by: raise ValueError('Invalid sort_by specified. Valid options are ' + str(valid_sort_by)) competitions_list_result = self.process_response( self.competitions_list_with_http_info( group=group or '', category=category or '', sort_by=sort_by or '', page=page, search=search or '')) return [Competition(c) for c in competitions_list_result]
python
def competitions_list(self, group=None, category=None, sort_by=None, page=1, search=None): """ make call to list competitions, format the response, and return a list of Competition instances Parameters ========== page: the page to return (default is 1) search: a search term to use (default is empty string) sort_by: how to sort the result, see valid_sort_by for options category: category to filter result to group: group to filter result to """ valid_groups = ['general', 'entered', 'inClass'] if group and group not in valid_groups: raise ValueError('Invalid group specified. Valid options are ' + str(valid_groups)) valid_categories = [ 'all', 'featured', 'research', 'recruitment', 'gettingStarted', 'masters', 'playground' ] if category and category not in valid_categories: raise ValueError('Invalid category specified. Valid options are ' + str(valid_categories)) valid_sort_by = [ 'grouped', 'prize', 'earliestDeadline', 'latestDeadline', 'numberOfTeams', 'recentlyCreated' ] if sort_by and sort_by not in valid_sort_by: raise ValueError('Invalid sort_by specified. Valid options are ' + str(valid_sort_by)) competitions_list_result = self.process_response( self.competitions_list_with_http_info( group=group or '', category=category or '', sort_by=sort_by or '', page=page, search=search or '')) return [Competition(c) for c in competitions_list_result]
[ "def", "competitions_list", "(", "self", ",", "group", "=", "None", ",", "category", "=", "None", ",", "sort_by", "=", "None", ",", "page", "=", "1", ",", "search", "=", "None", ")", ":", "valid_groups", "=", "[", "'general'", ",", "'entered'", ",", "'inClass'", "]", "if", "group", "and", "group", "not", "in", "valid_groups", ":", "raise", "ValueError", "(", "'Invalid group specified. Valid options are '", "+", "str", "(", "valid_groups", ")", ")", "valid_categories", "=", "[", "'all'", ",", "'featured'", ",", "'research'", ",", "'recruitment'", ",", "'gettingStarted'", ",", "'masters'", ",", "'playground'", "]", "if", "category", "and", "category", "not", "in", "valid_categories", ":", "raise", "ValueError", "(", "'Invalid category specified. Valid options are '", "+", "str", "(", "valid_categories", ")", ")", "valid_sort_by", "=", "[", "'grouped'", ",", "'prize'", ",", "'earliestDeadline'", ",", "'latestDeadline'", ",", "'numberOfTeams'", ",", "'recentlyCreated'", "]", "if", "sort_by", "and", "sort_by", "not", "in", "valid_sort_by", ":", "raise", "ValueError", "(", "'Invalid sort_by specified. Valid options are '", "+", "str", "(", "valid_sort_by", ")", ")", "competitions_list_result", "=", "self", ".", "process_response", "(", "self", ".", "competitions_list_with_http_info", "(", "group", "=", "group", "or", "''", ",", "category", "=", "category", "or", "''", ",", "sort_by", "=", "sort_by", "or", "''", ",", "page", "=", "page", ",", "search", "=", "search", "or", "''", ")", ")", "return", "[", "Competition", "(", "c", ")", "for", "c", "in", "competitions_list_result", "]" ]
make call to list competitions, format the response, and return a list of Competition instances Parameters ========== page: the page to return (default is 1) search: a search term to use (default is empty string) sort_by: how to sort the result, see valid_sort_by for options category: category to filter result to group: group to filter result to
[ "make", "call", "to", "list", "competitions", "format", "the", "response", "and", "return", "a", "list", "of", "Competition", "instances" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L369-L415
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competitions_list_cli
def competitions_list_cli(self, group=None, category=None, sort_by=None, page=1, search=None, csv_display=False): """ a wrapper for competitions_list for the client. Parameters ========== group: group to filter result to category: category to filter result to sort_by: how to sort the result, see valid_sort_by for options page: the page to return (default is 1) search: a search term to use (default is empty string) csv_display: if True, print comma separated values """ competitions = self.competitions_list( group=group, category=category, sort_by=sort_by, page=page, search=search) fields = [ 'ref', 'deadline', 'category', 'reward', 'teamCount', 'userHasEntered' ] if competitions: if csv_display: self.print_csv(competitions, fields) else: self.print_table(competitions, fields) else: print('No competitions found')
python
def competitions_list_cli(self, group=None, category=None, sort_by=None, page=1, search=None, csv_display=False): """ a wrapper for competitions_list for the client. Parameters ========== group: group to filter result to category: category to filter result to sort_by: how to sort the result, see valid_sort_by for options page: the page to return (default is 1) search: a search term to use (default is empty string) csv_display: if True, print comma separated values """ competitions = self.competitions_list( group=group, category=category, sort_by=sort_by, page=page, search=search) fields = [ 'ref', 'deadline', 'category', 'reward', 'teamCount', 'userHasEntered' ] if competitions: if csv_display: self.print_csv(competitions, fields) else: self.print_table(competitions, fields) else: print('No competitions found')
[ "def", "competitions_list_cli", "(", "self", ",", "group", "=", "None", ",", "category", "=", "None", ",", "sort_by", "=", "None", ",", "page", "=", "1", ",", "search", "=", "None", ",", "csv_display", "=", "False", ")", ":", "competitions", "=", "self", ".", "competitions_list", "(", "group", "=", "group", ",", "category", "=", "category", ",", "sort_by", "=", "sort_by", ",", "page", "=", "page", ",", "search", "=", "search", ")", "fields", "=", "[", "'ref'", ",", "'deadline'", ",", "'category'", ",", "'reward'", ",", "'teamCount'", ",", "'userHasEntered'", "]", "if", "competitions", ":", "if", "csv_display", ":", "self", ".", "print_csv", "(", "competitions", ",", "fields", ")", "else", ":", "self", ".", "print_table", "(", "competitions", ",", "fields", ")", "else", ":", "print", "(", "'No competitions found'", ")" ]
a wrapper for competitions_list for the client. Parameters ========== group: group to filter result to category: category to filter result to sort_by: how to sort the result, see valid_sort_by for options page: the page to return (default is 1) search: a search term to use (default is empty string) csv_display: if True, print comma separated values
[ "a", "wrapper", "for", "competitions_list", "for", "the", "client", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L417-L451
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_submit
def competition_submit(self, file_name, message, competition, quiet=False): """ submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quiet: suppress verbose output (default is False) """ if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: url_result = self.process_response( self.competitions_submissions_url_with_http_info( id=competition, file_name=os.path.basename(file_name), content_length=os.path.getsize(file_name), last_modified_date_utc=int(os.path.getmtime(file_name)))) # Temporary while new worker is gradually turned on. 'isComplete' # exists on the old DTO but not the new, so this is an hacky but # easy solution to figure out which submission logic to use if 'isComplete' in url_result: # Old submissions path url_result_list = url_result['createUrl'].split('/') upload_result = self.process_response( self.competitions_submissions_upload_with_http_info( file=file_name, guid=url_result_list[-3], content_length=url_result_list[-2], last_modified_date_utc=url_result_list[-1])) upload_result_token = upload_result['token'] else: # New submissions path! success = self.upload_complete(file_name, url_result['createUrl'], quiet) if not success: # Actual error is printed during upload_complete. Not # ideal but changing would not be backwards compatible return "Could not submit to competition" upload_result_token = url_result['token'] submit_result = self.process_response( self.competitions_submissions_submit_with_http_info( id=competition, blob_file_tokens=upload_result_token, submission_description=message)) return SubmitResult(submit_result)
python
def competition_submit(self, file_name, message, competition, quiet=False): """ submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quiet: suppress verbose output (default is False) """ if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: url_result = self.process_response( self.competitions_submissions_url_with_http_info( id=competition, file_name=os.path.basename(file_name), content_length=os.path.getsize(file_name), last_modified_date_utc=int(os.path.getmtime(file_name)))) # Temporary while new worker is gradually turned on. 'isComplete' # exists on the old DTO but not the new, so this is an hacky but # easy solution to figure out which submission logic to use if 'isComplete' in url_result: # Old submissions path url_result_list = url_result['createUrl'].split('/') upload_result = self.process_response( self.competitions_submissions_upload_with_http_info( file=file_name, guid=url_result_list[-3], content_length=url_result_list[-2], last_modified_date_utc=url_result_list[-1])) upload_result_token = upload_result['token'] else: # New submissions path! success = self.upload_complete(file_name, url_result['createUrl'], quiet) if not success: # Actual error is printed during upload_complete. Not # ideal but changing would not be backwards compatible return "Could not submit to competition" upload_result_token = url_result['token'] submit_result = self.process_response( self.competitions_submissions_submit_with_http_info( id=competition, blob_file_tokens=upload_result_token, submission_description=message)) return SubmitResult(submit_result)
[ "def", "competition_submit", "(", "self", ",", "file_name", ",", "message", ",", "competition", ",", "quiet", "=", "False", ")", ":", "if", "competition", "is", "None", ":", "competition", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_COMPETITION", ")", "if", "competition", "is", "not", "None", "and", "not", "quiet", ":", "print", "(", "'Using competition: '", "+", "competition", ")", "if", "competition", "is", "None", ":", "raise", "ValueError", "(", "'No competition specified'", ")", "else", ":", "url_result", "=", "self", ".", "process_response", "(", "self", ".", "competitions_submissions_url_with_http_info", "(", "id", "=", "competition", ",", "file_name", "=", "os", ".", "path", ".", "basename", "(", "file_name", ")", ",", "content_length", "=", "os", ".", "path", ".", "getsize", "(", "file_name", ")", ",", "last_modified_date_utc", "=", "int", "(", "os", ".", "path", ".", "getmtime", "(", "file_name", ")", ")", ")", ")", "# Temporary while new worker is gradually turned on. 'isComplete'", "# exists on the old DTO but not the new, so this is an hacky but", "# easy solution to figure out which submission logic to use", "if", "'isComplete'", "in", "url_result", ":", "# Old submissions path", "url_result_list", "=", "url_result", "[", "'createUrl'", "]", ".", "split", "(", "'/'", ")", "upload_result", "=", "self", ".", "process_response", "(", "self", ".", "competitions_submissions_upload_with_http_info", "(", "file", "=", "file_name", ",", "guid", "=", "url_result_list", "[", "-", "3", "]", ",", "content_length", "=", "url_result_list", "[", "-", "2", "]", ",", "last_modified_date_utc", "=", "url_result_list", "[", "-", "1", "]", ")", ")", "upload_result_token", "=", "upload_result", "[", "'token'", "]", "else", ":", "# New submissions path!", "success", "=", "self", ".", "upload_complete", "(", "file_name", ",", "url_result", "[", "'createUrl'", "]", ",", "quiet", ")", "if", "not", "success", ":", "# Actual error is printed during upload_complete. Not", "# ideal but changing would not be backwards compatible", "return", "\"Could not submit to competition\"", "upload_result_token", "=", "url_result", "[", "'token'", "]", "submit_result", "=", "self", ".", "process_response", "(", "self", ".", "competitions_submissions_submit_with_http_info", "(", "id", "=", "competition", ",", "blob_file_tokens", "=", "upload_result_token", ",", "submission_description", "=", "message", ")", ")", "return", "SubmitResult", "(", "submit_result", ")" ]
submit a competition! Parameters ========== file_name: the competition metadata file message: the submission description competition: the competition name quiet: suppress verbose output (default is False)
[ "submit", "a", "competition!" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L453-L507
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_submit_cli
def competition_submit_cli(self, file_name, message, competition, competition_opt=None, quiet=False): """ submit a competition using the client. Arguments are same as for competition_submit, except for extra arguments provided here. Parameters ========== competition_opt: an alternative competition option provided by cli """ competition = competition or competition_opt try: submit_result = self.competition_submit(file_name, message, competition, quiet) except ApiException as e: if e.status == 404: print('Could not find competition - please verify that you ' 'entered the correct competition ID and that the ' 'competition is still accepting submissions.') return None else: raise e return submit_result
python
def competition_submit_cli(self, file_name, message, competition, competition_opt=None, quiet=False): """ submit a competition using the client. Arguments are same as for competition_submit, except for extra arguments provided here. Parameters ========== competition_opt: an alternative competition option provided by cli """ competition = competition or competition_opt try: submit_result = self.competition_submit(file_name, message, competition, quiet) except ApiException as e: if e.status == 404: print('Could not find competition - please verify that you ' 'entered the correct competition ID and that the ' 'competition is still accepting submissions.') return None else: raise e return submit_result
[ "def", "competition_submit_cli", "(", "self", ",", "file_name", ",", "message", ",", "competition", ",", "competition_opt", "=", "None", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "try", ":", "submit_result", "=", "self", ".", "competition_submit", "(", "file_name", ",", "message", ",", "competition", ",", "quiet", ")", "except", "ApiException", "as", "e", ":", "if", "e", ".", "status", "==", "404", ":", "print", "(", "'Could not find competition - please verify that you '", "'entered the correct competition ID and that the '", "'competition is still accepting submissions.'", ")", "return", "None", "else", ":", "raise", "e", "return", "submit_result" ]
submit a competition using the client. Arguments are same as for competition_submit, except for extra arguments provided here. Parameters ========== competition_opt: an alternative competition option provided by cli
[ "submit", "a", "competition", "using", "the", "client", ".", "Arguments", "are", "same", "as", "for", "competition_submit", "except", "for", "extra", "arguments", "provided", "here", ".", "Parameters", "==========", "competition_opt", ":", "an", "alternative", "competition", "option", "provided", "by", "cli" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L509-L533
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_submissions
def competition_submissions(self, competition): """ get the list of Submission for a particular competition Parameters ========== competition: the name of the competition """ submissions_result = self.process_response( self.competitions_submissions_list_with_http_info(id=competition)) return [Submission(s) for s in submissions_result]
python
def competition_submissions(self, competition): """ get the list of Submission for a particular competition Parameters ========== competition: the name of the competition """ submissions_result = self.process_response( self.competitions_submissions_list_with_http_info(id=competition)) return [Submission(s) for s in submissions_result]
[ "def", "competition_submissions", "(", "self", ",", "competition", ")", ":", "submissions_result", "=", "self", ".", "process_response", "(", "self", ".", "competitions_submissions_list_with_http_info", "(", "id", "=", "competition", ")", ")", "return", "[", "Submission", "(", "s", ")", "for", "s", "in", "submissions_result", "]" ]
get the list of Submission for a particular competition Parameters ========== competition: the name of the competition
[ "get", "the", "list", "of", "Submission", "for", "a", "particular", "competition" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L535-L544
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_submissions_cli
def competition_submissions_cli(self, competition=None, competition_opt=None, csv_display=False, quiet=False): """ wrapper to competition_submission, will return either json or csv to the user. Additional parameters are listed below, see competition_submissions for rest. Parameters ========== competition: the name of the competition. If None, look to config competition_opt: an alternative competition option provided by cli csv_display: if True, print comma separated values quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: submissions = self.competition_submissions(competition) fields = [ 'fileName', 'date', 'description', 'status', 'publicScore', 'privateScore' ] if submissions: if csv_display: self.print_csv(submissions, fields) else: self.print_table(submissions, fields) else: print('No submissions found')
python
def competition_submissions_cli(self, competition=None, competition_opt=None, csv_display=False, quiet=False): """ wrapper to competition_submission, will return either json or csv to the user. Additional parameters are listed below, see competition_submissions for rest. Parameters ========== competition: the name of the competition. If None, look to config competition_opt: an alternative competition option provided by cli csv_display: if True, print comma separated values quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: submissions = self.competition_submissions(competition) fields = [ 'fileName', 'date', 'description', 'status', 'publicScore', 'privateScore' ] if submissions: if csv_display: self.print_csv(submissions, fields) else: self.print_table(submissions, fields) else: print('No submissions found')
[ "def", "competition_submissions_cli", "(", "self", ",", "competition", "=", "None", ",", "competition_opt", "=", "None", ",", "csv_display", "=", "False", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "if", "competition", "is", "None", ":", "competition", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_COMPETITION", ")", "if", "competition", "is", "not", "None", "and", "not", "quiet", ":", "print", "(", "'Using competition: '", "+", "competition", ")", "if", "competition", "is", "None", ":", "raise", "ValueError", "(", "'No competition specified'", ")", "else", ":", "submissions", "=", "self", ".", "competition_submissions", "(", "competition", ")", "fields", "=", "[", "'fileName'", ",", "'date'", ",", "'description'", ",", "'status'", ",", "'publicScore'", ",", "'privateScore'", "]", "if", "submissions", ":", "if", "csv_display", ":", "self", ".", "print_csv", "(", "submissions", ",", "fields", ")", "else", ":", "self", ".", "print_table", "(", "submissions", ",", "fields", ")", "else", ":", "print", "(", "'No submissions found'", ")" ]
wrapper to competition_submission, will return either json or csv to the user. Additional parameters are listed below, see competition_submissions for rest. Parameters ========== competition: the name of the competition. If None, look to config competition_opt: an alternative competition option provided by cli csv_display: if True, print comma separated values quiet: suppress verbose output (default is False)
[ "wrapper", "to", "competition_submission", "will", "return", "either", "json", "or", "csv", "to", "the", "user", ".", "Additional", "parameters", "are", "listed", "below", "see", "competition_submissions", "for", "rest", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L546-L582
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_list_files
def competition_list_files(self, competition): """ list files for competition Parameters ========== competition: the name of the competition """ competition_list_files_result = self.process_response( self.competitions_data_list_files_with_http_info(id=competition)) return [File(f) for f in competition_list_files_result]
python
def competition_list_files(self, competition): """ list files for competition Parameters ========== competition: the name of the competition """ competition_list_files_result = self.process_response( self.competitions_data_list_files_with_http_info(id=competition)) return [File(f) for f in competition_list_files_result]
[ "def", "competition_list_files", "(", "self", ",", "competition", ")", ":", "competition_list_files_result", "=", "self", ".", "process_response", "(", "self", ".", "competitions_data_list_files_with_http_info", "(", "id", "=", "competition", ")", ")", "return", "[", "File", "(", "f", ")", "for", "f", "in", "competition_list_files_result", "]" ]
list files for competition Parameters ========== competition: the name of the competition
[ "list", "files", "for", "competition", "Parameters", "==========", "competition", ":", "the", "name", "of", "the", "competition" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L584-L592
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_list_files_cli
def competition_list_files_cli(self, competition, competition_opt=None, csv_display=False, quiet=False): """ List files for a competition, if it exists Parameters ========== competition: the name of the competition. If None, look to config competition_opt: an alternative competition option provided by cli csv_display: if True, print comma separated values quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: files = self.competition_list_files(competition) fields = ['name', 'size', 'creationDate'] if files: if csv_display: self.print_csv(files, fields) else: self.print_table(files, fields) else: print('No files found')
python
def competition_list_files_cli(self, competition, competition_opt=None, csv_display=False, quiet=False): """ List files for a competition, if it exists Parameters ========== competition: the name of the competition. If None, look to config competition_opt: an alternative competition option provided by cli csv_display: if True, print comma separated values quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: files = self.competition_list_files(competition) fields = ['name', 'size', 'creationDate'] if files: if csv_display: self.print_csv(files, fields) else: self.print_table(files, fields) else: print('No files found')
[ "def", "competition_list_files_cli", "(", "self", ",", "competition", ",", "competition_opt", "=", "None", ",", "csv_display", "=", "False", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "if", "competition", "is", "None", ":", "competition", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_COMPETITION", ")", "if", "competition", "is", "not", "None", "and", "not", "quiet", ":", "print", "(", "'Using competition: '", "+", "competition", ")", "if", "competition", "is", "None", ":", "raise", "ValueError", "(", "'No competition specified'", ")", "else", ":", "files", "=", "self", ".", "competition_list_files", "(", "competition", ")", "fields", "=", "[", "'name'", ",", "'size'", ",", "'creationDate'", "]", "if", "files", ":", "if", "csv_display", ":", "self", ".", "print_csv", "(", "files", ",", "fields", ")", "else", ":", "self", ".", "print_table", "(", "files", ",", "fields", ")", "else", ":", "print", "(", "'No files found'", ")" ]
List files for a competition, if it exists Parameters ========== competition: the name of the competition. If None, look to config competition_opt: an alternative competition option provided by cli csv_display: if True, print comma separated values quiet: suppress verbose output (default is False)
[ "List", "files", "for", "a", "competition", "if", "it", "exists" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L594-L625
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_download_file
def competition_download_file(self, competition, file_name, path=None, force=False, quiet=False): """ download a competition file to a designated location, or use a default location Paramters ========= competition: the name of the competition file_name: the configuration file name path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False) """ if path is None: effective_path = self.get_default_download_dir( 'competitions', competition) else: effective_path = path response = self.process_response( self.competitions_data_download_file_with_http_info( id=competition, file_name=file_name, _preload_content=False)) url = response.retries.history[0].redirect_location.split('?')[0] outfile = os.path.join(effective_path, url.split('/')[-1]) if force or self.download_needed(response, outfile, quiet): self.download_file(response, outfile, quiet)
python
def competition_download_file(self, competition, file_name, path=None, force=False, quiet=False): """ download a competition file to a designated location, or use a default location Paramters ========= competition: the name of the competition file_name: the configuration file name path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False) """ if path is None: effective_path = self.get_default_download_dir( 'competitions', competition) else: effective_path = path response = self.process_response( self.competitions_data_download_file_with_http_info( id=competition, file_name=file_name, _preload_content=False)) url = response.retries.history[0].redirect_location.split('?')[0] outfile = os.path.join(effective_path, url.split('/')[-1]) if force or self.download_needed(response, outfile, quiet): self.download_file(response, outfile, quiet)
[ "def", "competition_download_file", "(", "self", ",", "competition", ",", "file_name", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "False", ")", ":", "if", "path", "is", "None", ":", "effective_path", "=", "self", ".", "get_default_download_dir", "(", "'competitions'", ",", "competition", ")", "else", ":", "effective_path", "=", "path", "response", "=", "self", ".", "process_response", "(", "self", ".", "competitions_data_download_file_with_http_info", "(", "id", "=", "competition", ",", "file_name", "=", "file_name", ",", "_preload_content", "=", "False", ")", ")", "url", "=", "response", ".", "retries", ".", "history", "[", "0", "]", ".", "redirect_location", ".", "split", "(", "'?'", ")", "[", "0", "]", "outfile", "=", "os", ".", "path", ".", "join", "(", "effective_path", ",", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "if", "force", "or", "self", ".", "download_needed", "(", "response", ",", "outfile", ",", "quiet", ")", ":", "self", ".", "download_file", "(", "response", ",", "outfile", ",", "quiet", ")" ]
download a competition file to a designated location, or use a default location Paramters ========= competition: the name of the competition file_name: the configuration file name path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False)
[ "download", "a", "competition", "file", "to", "a", "designated", "location", "or", "use", "a", "default", "location" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L627-L657
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_download_files
def competition_download_files(self, competition, path=None, force=False, quiet=True): """ a wrapper to competition_download_file to download all competition files. Parameters ========= competition: the name of the competition path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True) """ files = self.competition_list_files(competition) if not files: print('This competition does not have any available data files') for file_name in files: self.competition_download_file(competition, file_name.ref, path, force, quiet)
python
def competition_download_files(self, competition, path=None, force=False, quiet=True): """ a wrapper to competition_download_file to download all competition files. Parameters ========= competition: the name of the competition path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True) """ files = self.competition_list_files(competition) if not files: print('This competition does not have any available data files') for file_name in files: self.competition_download_file(competition, file_name.ref, path, force, quiet)
[ "def", "competition_download_files", "(", "self", ",", "competition", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "True", ")", ":", "files", "=", "self", ".", "competition_list_files", "(", "competition", ")", "if", "not", "files", ":", "print", "(", "'This competition does not have any available data files'", ")", "for", "file_name", "in", "files", ":", "self", ".", "competition_download_file", "(", "competition", ",", "file_name", ".", "ref", ",", "path", ",", "force", ",", "quiet", ")" ]
a wrapper to competition_download_file to download all competition files. Parameters ========= competition: the name of the competition path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True)
[ "a", "wrapper", "to", "competition_download_file", "to", "download", "all", "competition", "files", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L659-L679
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_download_cli
def competition_download_cli(self, competition, competition_opt=None, file_name=None, path=None, force=False, quiet=False): """ a wrapper to competition_download_files, but first will parse input from API client. Additional parameters are listed here, see competition_download for remaining. Parameters ========= competition: the name of the competition competition_opt: an alternative competition option provided by cli file_name: the configuration file name path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: if file_name is None: self.competition_download_files(competition, path, force, quiet) else: self.competition_download_file(competition, file_name, path, force, quiet)
python
def competition_download_cli(self, competition, competition_opt=None, file_name=None, path=None, force=False, quiet=False): """ a wrapper to competition_download_files, but first will parse input from API client. Additional parameters are listed here, see competition_download for remaining. Parameters ========= competition: the name of the competition competition_opt: an alternative competition option provided by cli file_name: the configuration file name path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') else: if file_name is None: self.competition_download_files(competition, path, force, quiet) else: self.competition_download_file(competition, file_name, path, force, quiet)
[ "def", "competition_download_cli", "(", "self", ",", "competition", ",", "competition_opt", "=", "None", ",", "file_name", "=", "None", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "if", "competition", "is", "None", ":", "competition", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_COMPETITION", ")", "if", "competition", "is", "not", "None", "and", "not", "quiet", ":", "print", "(", "'Using competition: '", "+", "competition", ")", "if", "competition", "is", "None", ":", "raise", "ValueError", "(", "'No competition specified'", ")", "else", ":", "if", "file_name", "is", "None", ":", "self", ".", "competition_download_files", "(", "competition", ",", "path", ",", "force", ",", "quiet", ")", "else", ":", "self", ".", "competition_download_file", "(", "competition", ",", "file_name", ",", "path", ",", "force", ",", "quiet", ")" ]
a wrapper to competition_download_files, but first will parse input from API client. Additional parameters are listed here, see competition_download for remaining. Parameters ========= competition: the name of the competition competition_opt: an alternative competition option provided by cli file_name: the configuration file name path: a path to download the file to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False)
[ "a", "wrapper", "to", "competition_download_files", "but", "first", "will", "parse", "input", "from", "API", "client", ".", "Additional", "parameters", "are", "listed", "here", "see", "competition_download", "for", "remaining", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L681-L715
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_leaderboard_download
def competition_leaderboard_download(self, competition, path, quiet=True): """ Download competition leaderboards Parameters ========= competition: the name of the competition path: a path to download the file to quiet: suppress verbose output (default is True) """ response = self.process_response( self.competition_download_leaderboard_with_http_info( competition, _preload_content=False)) if path is None: effective_path = self.get_default_download_dir( 'competitions', competition) else: effective_path = path file_name = competition + '.zip' outfile = os.path.join(effective_path, file_name) self.download_file(response, outfile, quiet)
python
def competition_leaderboard_download(self, competition, path, quiet=True): """ Download competition leaderboards Parameters ========= competition: the name of the competition path: a path to download the file to quiet: suppress verbose output (default is True) """ response = self.process_response( self.competition_download_leaderboard_with_http_info( competition, _preload_content=False)) if path is None: effective_path = self.get_default_download_dir( 'competitions', competition) else: effective_path = path file_name = competition + '.zip' outfile = os.path.join(effective_path, file_name) self.download_file(response, outfile, quiet)
[ "def", "competition_leaderboard_download", "(", "self", ",", "competition", ",", "path", ",", "quiet", "=", "True", ")", ":", "response", "=", "self", ".", "process_response", "(", "self", ".", "competition_download_leaderboard_with_http_info", "(", "competition", ",", "_preload_content", "=", "False", ")", ")", "if", "path", "is", "None", ":", "effective_path", "=", "self", ".", "get_default_download_dir", "(", "'competitions'", ",", "competition", ")", "else", ":", "effective_path", "=", "path", "file_name", "=", "competition", "+", "'.zip'", "outfile", "=", "os", ".", "path", ".", "join", "(", "effective_path", ",", "file_name", ")", "self", ".", "download_file", "(", "response", ",", "outfile", ",", "quiet", ")" ]
Download competition leaderboards Parameters ========= competition: the name of the competition path: a path to download the file to quiet: suppress verbose output (default is True)
[ "Download", "competition", "leaderboards" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L717-L738
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_leaderboard_view
def competition_leaderboard_view(self, competition): """ view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for """ result = self.process_response( self.competition_view_leaderboard_with_http_info(competition)) return [LeaderboardEntry(e) for e in result['submissions']]
python
def competition_leaderboard_view(self, competition): """ view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for """ result = self.process_response( self.competition_view_leaderboard_with_http_info(competition)) return [LeaderboardEntry(e) for e in result['submissions']]
[ "def", "competition_leaderboard_view", "(", "self", ",", "competition", ")", ":", "result", "=", "self", ".", "process_response", "(", "self", ".", "competition_view_leaderboard_with_http_info", "(", "competition", ")", ")", "return", "[", "LeaderboardEntry", "(", "e", ")", "for", "e", "in", "result", "[", "'submissions'", "]", "]" ]
view a leaderboard based on a competition name Parameters ========== competition: the competition name to view leadboard for
[ "view", "a", "leaderboard", "based", "on", "a", "competition", "name" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L740-L749
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.competition_leaderboard_cli
def competition_leaderboard_cli(self, competition, competition_opt=None, path=None, view=False, download=False, csv_display=False, quiet=False): """ a wrapper for competition_leaderbord_view that will print the results as a table or comma separated values Parameters ========== competition: the competition name to view leadboard for competition_opt: an alternative competition option provided by cli path: a path to download to, if download is True view: if True, show the results in the terminal as csv or table download: if True, download the entire leaderboard csv_display: if True, print comma separated values instead of table quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if not view and not download: raise ValueError('Either --show or --download must be specified') if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') if download: self.competition_leaderboard_download(competition, path, quiet) if view: results = self.competition_leaderboard_view(competition) fields = ['teamId', 'teamName', 'submissionDate', 'score'] if results: if csv_display: self.print_csv(results, fields) else: self.print_table(results, fields) else: print('No results found')
python
def competition_leaderboard_cli(self, competition, competition_opt=None, path=None, view=False, download=False, csv_display=False, quiet=False): """ a wrapper for competition_leaderbord_view that will print the results as a table or comma separated values Parameters ========== competition: the competition name to view leadboard for competition_opt: an alternative competition option provided by cli path: a path to download to, if download is True view: if True, show the results in the terminal as csv or table download: if True, download the entire leaderboard csv_display: if True, print comma separated values instead of table quiet: suppress verbose output (default is False) """ competition = competition or competition_opt if not view and not download: raise ValueError('Either --show or --download must be specified') if competition is None: competition = self.get_config_value(self.CONFIG_NAME_COMPETITION) if competition is not None and not quiet: print('Using competition: ' + competition) if competition is None: raise ValueError('No competition specified') if download: self.competition_leaderboard_download(competition, path, quiet) if view: results = self.competition_leaderboard_view(competition) fields = ['teamId', 'teamName', 'submissionDate', 'score'] if results: if csv_display: self.print_csv(results, fields) else: self.print_table(results, fields) else: print('No results found')
[ "def", "competition_leaderboard_cli", "(", "self", ",", "competition", ",", "competition_opt", "=", "None", ",", "path", "=", "None", ",", "view", "=", "False", ",", "download", "=", "False", ",", "csv_display", "=", "False", ",", "quiet", "=", "False", ")", ":", "competition", "=", "competition", "or", "competition_opt", "if", "not", "view", "and", "not", "download", ":", "raise", "ValueError", "(", "'Either --show or --download must be specified'", ")", "if", "competition", "is", "None", ":", "competition", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_COMPETITION", ")", "if", "competition", "is", "not", "None", "and", "not", "quiet", ":", "print", "(", "'Using competition: '", "+", "competition", ")", "if", "competition", "is", "None", ":", "raise", "ValueError", "(", "'No competition specified'", ")", "if", "download", ":", "self", ".", "competition_leaderboard_download", "(", "competition", ",", "path", ",", "quiet", ")", "if", "view", ":", "results", "=", "self", ".", "competition_leaderboard_view", "(", "competition", ")", "fields", "=", "[", "'teamId'", ",", "'teamName'", ",", "'submissionDate'", ",", "'score'", "]", "if", "results", ":", "if", "csv_display", ":", "self", ".", "print_csv", "(", "results", ",", "fields", ")", "else", ":", "self", ".", "print_table", "(", "results", ",", "fields", ")", "else", ":", "print", "(", "'No results found'", ")" ]
a wrapper for competition_leaderbord_view that will print the results as a table or comma separated values Parameters ========== competition: the competition name to view leadboard for competition_opt: an alternative competition option provided by cli path: a path to download to, if download is True view: if True, show the results in the terminal as csv or table download: if True, download the entire leaderboard csv_display: if True, print comma separated values instead of table quiet: suppress verbose output (default is False)
[ "a", "wrapper", "for", "competition_leaderbord_view", "that", "will", "print", "the", "results", "as", "a", "table", "or", "comma", "separated", "values" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L751-L796
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_list
def dataset_list(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, page=1): """ return a list of datasets! Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options license_name: string descriptor for license, see valid_license_names tag_ids: tag identifiers to filter the search search: a search term to use (default is empty string) user: username to filter the search to mine: boolean if True, group is changed to "my" to return personal page: the page to return (default is 1) """ valid_sort_bys = ['hottest', 'votes', 'updated', 'active', 'published'] if sort_by and sort_by not in valid_sort_bys: raise ValueError('Invalid sort by specified. Valid options are ' + str(valid_sort_bys)) valid_sizes = ['all', 'small', 'medium', 'large'] if size and size not in valid_sizes: raise ValueError('Invalid size specified. Valid options are ' + str(valid_sizes)) valid_file_types = ['all', 'csv', 'sqlite', 'json', 'bigQuery'] if file_type and file_type not in valid_file_types: raise ValueError('Invalid file type specified. Valid options are ' + str(valid_file_types)) valid_license_names = ['all', 'cc', 'gpl', 'odb', 'other'] if license_name and license_name not in valid_license_names: raise ValueError('Invalid license specified. Valid options are ' + str(valid_license_names)) if int(page) <= 0: raise ValueError('Page number must be >= 1') group = 'public' if mine: group = 'my' if user: raise ValueError('Cannot specify both mine and a user') if user: group = 'user' datasets_list_result = self.process_response( self.datasets_list_with_http_info( group=group, sort_by=sort_by or 'hottest', size=size or 'all', filetype=file_type or 'all', license=license_name or 'all', tagids=tag_ids or '', search=search or '', user=user or '', page=page)) return [Dataset(d) for d in datasets_list_result]
python
def dataset_list(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, page=1): """ return a list of datasets! Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options license_name: string descriptor for license, see valid_license_names tag_ids: tag identifiers to filter the search search: a search term to use (default is empty string) user: username to filter the search to mine: boolean if True, group is changed to "my" to return personal page: the page to return (default is 1) """ valid_sort_bys = ['hottest', 'votes', 'updated', 'active', 'published'] if sort_by and sort_by not in valid_sort_bys: raise ValueError('Invalid sort by specified. Valid options are ' + str(valid_sort_bys)) valid_sizes = ['all', 'small', 'medium', 'large'] if size and size not in valid_sizes: raise ValueError('Invalid size specified. Valid options are ' + str(valid_sizes)) valid_file_types = ['all', 'csv', 'sqlite', 'json', 'bigQuery'] if file_type and file_type not in valid_file_types: raise ValueError('Invalid file type specified. Valid options are ' + str(valid_file_types)) valid_license_names = ['all', 'cc', 'gpl', 'odb', 'other'] if license_name and license_name not in valid_license_names: raise ValueError('Invalid license specified. Valid options are ' + str(valid_license_names)) if int(page) <= 0: raise ValueError('Page number must be >= 1') group = 'public' if mine: group = 'my' if user: raise ValueError('Cannot specify both mine and a user') if user: group = 'user' datasets_list_result = self.process_response( self.datasets_list_with_http_info( group=group, sort_by=sort_by or 'hottest', size=size or 'all', filetype=file_type or 'all', license=license_name or 'all', tagids=tag_ids or '', search=search or '', user=user or '', page=page)) return [Dataset(d) for d in datasets_list_result]
[ "def", "dataset_list", "(", "self", ",", "sort_by", "=", "None", ",", "size", "=", "None", ",", "file_type", "=", "None", ",", "license_name", "=", "None", ",", "tag_ids", "=", "None", ",", "search", "=", "None", ",", "user", "=", "None", ",", "mine", "=", "False", ",", "page", "=", "1", ")", ":", "valid_sort_bys", "=", "[", "'hottest'", ",", "'votes'", ",", "'updated'", ",", "'active'", ",", "'published'", "]", "if", "sort_by", "and", "sort_by", "not", "in", "valid_sort_bys", ":", "raise", "ValueError", "(", "'Invalid sort by specified. Valid options are '", "+", "str", "(", "valid_sort_bys", ")", ")", "valid_sizes", "=", "[", "'all'", ",", "'small'", ",", "'medium'", ",", "'large'", "]", "if", "size", "and", "size", "not", "in", "valid_sizes", ":", "raise", "ValueError", "(", "'Invalid size specified. Valid options are '", "+", "str", "(", "valid_sizes", ")", ")", "valid_file_types", "=", "[", "'all'", ",", "'csv'", ",", "'sqlite'", ",", "'json'", ",", "'bigQuery'", "]", "if", "file_type", "and", "file_type", "not", "in", "valid_file_types", ":", "raise", "ValueError", "(", "'Invalid file type specified. Valid options are '", "+", "str", "(", "valid_file_types", ")", ")", "valid_license_names", "=", "[", "'all'", ",", "'cc'", ",", "'gpl'", ",", "'odb'", ",", "'other'", "]", "if", "license_name", "and", "license_name", "not", "in", "valid_license_names", ":", "raise", "ValueError", "(", "'Invalid license specified. Valid options are '", "+", "str", "(", "valid_license_names", ")", ")", "if", "int", "(", "page", ")", "<=", "0", ":", "raise", "ValueError", "(", "'Page number must be >= 1'", ")", "group", "=", "'public'", "if", "mine", ":", "group", "=", "'my'", "if", "user", ":", "raise", "ValueError", "(", "'Cannot specify both mine and a user'", ")", "if", "user", ":", "group", "=", "'user'", "datasets_list_result", "=", "self", ".", "process_response", "(", "self", ".", "datasets_list_with_http_info", "(", "group", "=", "group", ",", "sort_by", "=", "sort_by", "or", "'hottest'", ",", "size", "=", "size", "or", "'all'", ",", "filetype", "=", "file_type", "or", "'all'", ",", "license", "=", "license_name", "or", "'all'", ",", "tagids", "=", "tag_ids", "or", "''", ",", "search", "=", "search", "or", "''", ",", "user", "=", "user", "or", "''", ",", "page", "=", "page", ")", ")", "return", "[", "Dataset", "(", "d", ")", "for", "d", "in", "datasets_list_result", "]" ]
return a list of datasets! Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options license_name: string descriptor for license, see valid_license_names tag_ids: tag identifiers to filter the search search: a search term to use (default is empty string) user: username to filter the search to mine: boolean if True, group is changed to "my" to return personal page: the page to return (default is 1)
[ "return", "a", "list", "of", "datasets!" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L798-L864
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_list_cli
def dataset_list_cli(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, page=1, csv_display=False): """ a wrapper to datasets_list for the client. Additional parameters are described here, see dataset_list for others. Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options license_name: string descriptor for license, see valid_license_names tag_ids: tag identifiers to filter the search search: a search term to use (default is empty string) user: username to filter the search to mine: boolean if True, group is changed to "my" to return personal page: the page to return (default is 1) csv_display: if True, print comma separated values instead of table """ datasets = self.dataset_list(sort_by, size, file_type, license_name, tag_ids, search, user, mine, page) fields = ['ref', 'title', 'size', 'lastUpdated', 'downloadCount'] if datasets: if csv_display: self.print_csv(datasets, fields) else: self.print_table(datasets, fields) else: print('No datasets found')
python
def dataset_list_cli(self, sort_by=None, size=None, file_type=None, license_name=None, tag_ids=None, search=None, user=None, mine=False, page=1, csv_display=False): """ a wrapper to datasets_list for the client. Additional parameters are described here, see dataset_list for others. Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options license_name: string descriptor for license, see valid_license_names tag_ids: tag identifiers to filter the search search: a search term to use (default is empty string) user: username to filter the search to mine: boolean if True, group is changed to "my" to return personal page: the page to return (default is 1) csv_display: if True, print comma separated values instead of table """ datasets = self.dataset_list(sort_by, size, file_type, license_name, tag_ids, search, user, mine, page) fields = ['ref', 'title', 'size', 'lastUpdated', 'downloadCount'] if datasets: if csv_display: self.print_csv(datasets, fields) else: self.print_table(datasets, fields) else: print('No datasets found')
[ "def", "dataset_list_cli", "(", "self", ",", "sort_by", "=", "None", ",", "size", "=", "None", ",", "file_type", "=", "None", ",", "license_name", "=", "None", ",", "tag_ids", "=", "None", ",", "search", "=", "None", ",", "user", "=", "None", ",", "mine", "=", "False", ",", "page", "=", "1", ",", "csv_display", "=", "False", ")", ":", "datasets", "=", "self", ".", "dataset_list", "(", "sort_by", ",", "size", ",", "file_type", ",", "license_name", ",", "tag_ids", ",", "search", ",", "user", ",", "mine", ",", "page", ")", "fields", "=", "[", "'ref'", ",", "'title'", ",", "'size'", ",", "'lastUpdated'", ",", "'downloadCount'", "]", "if", "datasets", ":", "if", "csv_display", ":", "self", ".", "print_csv", "(", "datasets", ",", "fields", ")", "else", ":", "self", ".", "print_table", "(", "datasets", ",", "fields", ")", "else", ":", "print", "(", "'No datasets found'", ")" ]
a wrapper to datasets_list for the client. Additional parameters are described here, see dataset_list for others. Parameters ========== sort_by: how to sort the result, see valid_sort_bys for options size: the size of the dataset, see valid_sizes for string options file_type: the format, see valid_file_types for string options license_name: string descriptor for license, see valid_license_names tag_ids: tag identifiers to filter the search search: a search term to use (default is empty string) user: username to filter the search to mine: boolean if True, group is changed to "my" to return personal page: the page to return (default is 1) csv_display: if True, print comma separated values instead of table
[ "a", "wrapper", "to", "datasets_list", "for", "the", "client", ".", "Additional", "parameters", "are", "described", "here", "see", "dataset_list", "for", "others", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L866-L902
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_view
def dataset_view(self, dataset): """ view metadata for a dataset. Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset result = self.process_response( self.datasets_view_with_http_info(owner_slug, dataset_slug)) return Dataset(result)
python
def dataset_view(self, dataset): """ view metadata for a dataset. Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset result = self.process_response( self.datasets_view_with_http_info(owner_slug, dataset_slug)) return Dataset(result)
[ "def", "dataset_view", "(", "self", ",", "dataset", ")", ":", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dataset", ")", "dataset_urls", "=", "dataset", ".", "split", "(", "'/'", ")", "owner_slug", "=", "dataset_urls", "[", "0", "]", "dataset_slug", "=", "dataset_urls", "[", "1", "]", "else", ":", "owner_slug", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_USER", ")", "dataset_slug", "=", "dataset", "result", "=", "self", ".", "process_response", "(", "self", ".", "datasets_view_with_http_info", "(", "owner_slug", ",", "dataset_slug", ")", ")", "return", "Dataset", "(", "result", ")" ]
view metadata for a dataset. Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name]
[ "view", "metadata", "for", "a", "dataset", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L904-L923
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_list_files
def dataset_list_files(self, dataset): """ list files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset dataset_list_files_result = self.process_response( self.datasets_list_files_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug)) return ListFilesResult(dataset_list_files_result)
python
def dataset_list_files(self, dataset): """ list files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset dataset_list_files_result = self.process_response( self.datasets_list_files_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug)) return ListFilesResult(dataset_list_files_result)
[ "def", "dataset_list_files", "(", "self", ",", "dataset", ")", ":", "if", "dataset", "is", "None", ":", "raise", "ValueError", "(", "'A dataset must be specified'", ")", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dataset", ")", "dataset_urls", "=", "dataset", ".", "split", "(", "'/'", ")", "owner_slug", "=", "dataset_urls", "[", "0", "]", "dataset_slug", "=", "dataset_urls", "[", "1", "]", "else", ":", "owner_slug", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_USER", ")", "dataset_slug", "=", "dataset", "dataset_list_files_result", "=", "self", ".", "process_response", "(", "self", ".", "datasets_list_files_with_http_info", "(", "owner_slug", "=", "owner_slug", ",", "dataset_slug", "=", "dataset_slug", ")", ")", "return", "ListFilesResult", "(", "dataset_list_files_result", ")" ]
list files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name]
[ "list", "files", "for", "a", "dataset", "Parameters", "==========", "dataset", ":", "the", "string", "identified", "of", "the", "dataset", "should", "be", "in", "format", "[", "owner", "]", "/", "[", "dataset", "-", "name", "]" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L969-L989
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_list_files_cli
def dataset_list_files_cli(self, dataset, dataset_opt=None, csv_display=False): """ a wrapper to dataset_list_files for the client (list files for a dataset) Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] dataset_opt: an alternative option to providing a dataset csv_display: if True, print comma separated values instead of table """ dataset = dataset or dataset_opt result = self.dataset_list_files(dataset) if result: if result.error_message: print(result.error_message) else: fields = ['name', 'size', 'creationDate'] if csv_display: self.print_csv(result.files, fields) else: self.print_table(result.files, fields) else: print('No files found')
python
def dataset_list_files_cli(self, dataset, dataset_opt=None, csv_display=False): """ a wrapper to dataset_list_files for the client (list files for a dataset) Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] dataset_opt: an alternative option to providing a dataset csv_display: if True, print comma separated values instead of table """ dataset = dataset or dataset_opt result = self.dataset_list_files(dataset) if result: if result.error_message: print(result.error_message) else: fields = ['name', 'size', 'creationDate'] if csv_display: self.print_csv(result.files, fields) else: self.print_table(result.files, fields) else: print('No files found')
[ "def", "dataset_list_files_cli", "(", "self", ",", "dataset", ",", "dataset_opt", "=", "None", ",", "csv_display", "=", "False", ")", ":", "dataset", "=", "dataset", "or", "dataset_opt", "result", "=", "self", ".", "dataset_list_files", "(", "dataset", ")", "if", "result", ":", "if", "result", ".", "error_message", ":", "print", "(", "result", ".", "error_message", ")", "else", ":", "fields", "=", "[", "'name'", ",", "'size'", ",", "'creationDate'", "]", "if", "csv_display", ":", "self", ".", "print_csv", "(", "result", ".", "files", ",", "fields", ")", "else", ":", "self", ".", "print_table", "(", "result", ".", "files", ",", "fields", ")", "else", ":", "print", "(", "'No files found'", ")" ]
a wrapper to dataset_list_files for the client (list files for a dataset) Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] dataset_opt: an alternative option to providing a dataset csv_display: if True, print comma separated values instead of table
[ "a", "wrapper", "to", "dataset_list_files", "for", "the", "client", "(", "list", "files", "for", "a", "dataset", ")", "Parameters", "==========", "dataset", ":", "the", "string", "identified", "of", "the", "dataset", "should", "be", "in", "format", "[", "owner", "]", "/", "[", "dataset", "-", "name", "]", "dataset_opt", ":", "an", "alternative", "option", "to", "providing", "a", "dataset", "csv_display", ":", "if", "True", "print", "comma", "separated", "values", "instead", "of", "table" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L991-L1016
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_status
def dataset_status(self, dataset): """ call to get the status of a dataset from the API Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset dataset_status_result = self.process_response( self.datasets_status_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug)) return dataset_status_result
python
def dataset_status(self, dataset): """ call to get the status of a dataset from the API Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] """ if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset dataset_status_result = self.process_response( self.datasets_status_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug)) return dataset_status_result
[ "def", "dataset_status", "(", "self", ",", "dataset", ")", ":", "if", "dataset", "is", "None", ":", "raise", "ValueError", "(", "'A dataset must be specified'", ")", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dataset", ")", "dataset_urls", "=", "dataset", ".", "split", "(", "'/'", ")", "owner_slug", "=", "dataset_urls", "[", "0", "]", "dataset_slug", "=", "dataset_urls", "[", "1", "]", "else", ":", "owner_slug", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_USER", ")", "dataset_slug", "=", "dataset", "dataset_status_result", "=", "self", ".", "process_response", "(", "self", ".", "datasets_status_with_http_info", "(", "owner_slug", "=", "owner_slug", ",", "dataset_slug", "=", "dataset_slug", ")", ")", "return", "dataset_status_result" ]
call to get the status of a dataset from the API Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name]
[ "call", "to", "get", "the", "status", "of", "a", "dataset", "from", "the", "API", "Parameters", "==========", "dataset", ":", "the", "string", "identified", "of", "the", "dataset", "should", "be", "in", "format", "[", "owner", "]", "/", "[", "dataset", "-", "name", "]" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1018-L1038
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_status_cli
def dataset_status_cli(self, dataset, dataset_opt=None): """ wrapper for client for dataset_status, with additional dataset_opt to get the status of a dataset from the API Parameters ========== dataset_opt: an alternative to dataset """ dataset = dataset or dataset_opt return self.dataset_status(dataset)
python
def dataset_status_cli(self, dataset, dataset_opt=None): """ wrapper for client for dataset_status, with additional dataset_opt to get the status of a dataset from the API Parameters ========== dataset_opt: an alternative to dataset """ dataset = dataset or dataset_opt return self.dataset_status(dataset)
[ "def", "dataset_status_cli", "(", "self", ",", "dataset", ",", "dataset_opt", "=", "None", ")", ":", "dataset", "=", "dataset", "or", "dataset_opt", "return", "self", ".", "dataset_status", "(", "dataset", ")" ]
wrapper for client for dataset_status, with additional dataset_opt to get the status of a dataset from the API Parameters ========== dataset_opt: an alternative to dataset
[ "wrapper", "for", "client", "for", "dataset_status", "with", "additional", "dataset_opt", "to", "get", "the", "status", "of", "a", "dataset", "from", "the", "API", "Parameters", "==========", "dataset_opt", ":", "an", "alternative", "to", "dataset" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1040-L1048
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_download_file
def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): """ download a single file for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] file_name: the dataset configuration file path: if defined, download to this location force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True) """ if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset if path is None: effective_path = self.get_default_download_dir( 'datasets', owner_slug, dataset_slug) else: effective_path = path response = self.process_response( self.datasets_download_file_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug, file_name=file_name, _preload_content=False)) url = response.retries.history[0].redirect_location.split('?')[0] outfile = os.path.join(effective_path, url.split('/')[-1]) if force or self.download_needed(response, outfile, quiet): self.download_file(response, outfile, quiet) return True else: return False
python
def dataset_download_file(self, dataset, file_name, path=None, force=False, quiet=True): """ download a single file for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] file_name: the dataset configuration file path: if defined, download to this location force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True) """ if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset if path is None: effective_path = self.get_default_download_dir( 'datasets', owner_slug, dataset_slug) else: effective_path = path response = self.process_response( self.datasets_download_file_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug, file_name=file_name, _preload_content=False)) url = response.retries.history[0].redirect_location.split('?')[0] outfile = os.path.join(effective_path, url.split('/')[-1]) if force or self.download_needed(response, outfile, quiet): self.download_file(response, outfile, quiet) return True else: return False
[ "def", "dataset_download_file", "(", "self", ",", "dataset", ",", "file_name", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "True", ")", ":", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dataset", ")", "dataset_urls", "=", "dataset", ".", "split", "(", "'/'", ")", "owner_slug", "=", "dataset_urls", "[", "0", "]", "dataset_slug", "=", "dataset_urls", "[", "1", "]", "else", ":", "owner_slug", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_USER", ")", "dataset_slug", "=", "dataset", "if", "path", "is", "None", ":", "effective_path", "=", "self", ".", "get_default_download_dir", "(", "'datasets'", ",", "owner_slug", ",", "dataset_slug", ")", "else", ":", "effective_path", "=", "path", "response", "=", "self", ".", "process_response", "(", "self", ".", "datasets_download_file_with_http_info", "(", "owner_slug", "=", "owner_slug", ",", "dataset_slug", "=", "dataset_slug", ",", "file_name", "=", "file_name", ",", "_preload_content", "=", "False", ")", ")", "url", "=", "response", ".", "retries", ".", "history", "[", "0", "]", ".", "redirect_location", ".", "split", "(", "'?'", ")", "[", "0", "]", "outfile", "=", "os", ".", "path", ".", "join", "(", "effective_path", ",", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "if", "force", "or", "self", ".", "download_needed", "(", "response", ",", "outfile", ",", "quiet", ")", ":", "self", ".", "download_file", "(", "response", ",", "outfile", ",", "quiet", ")", "return", "True", "else", ":", "return", "False" ]
download a single file for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] file_name: the dataset configuration file path: if defined, download to this location force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True)
[ "download", "a", "single", "file", "for", "a", "dataset" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1050-L1094
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_download_files
def dataset_download_files(self, dataset, path=None, force=False, quiet=True, unzip=False): """ download all files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] path: the path to download the dataset to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True) unzip: if True, unzip files upon download (default is False) """ if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset if path is None: effective_path = self.get_default_download_dir( 'datasets', owner_slug, dataset_slug) else: effective_path = path response = self.process_response( self.datasets_download_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug, _preload_content=False)) outfile = os.path.join(effective_path, dataset_slug + '.zip') if force or self.download_needed(response, outfile, quiet): self.download_file(response, outfile, quiet) downloaded = True else: downloaded = False if downloaded: outfile = os.path.join(effective_path, dataset_slug + '.zip') if unzip: try: with zipfile.ZipFile(outfile) as z: z.extractall(effective_path) except zipfile.BadZipFile as e: raise ValueError( 'Bad zip file, please report on ' 'www.github.com/kaggle/kaggle-api', e) try: os.remove(outfile) except OSError as e: print('Could not delete zip file, got %s' % e)
python
def dataset_download_files(self, dataset, path=None, force=False, quiet=True, unzip=False): """ download all files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] path: the path to download the dataset to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True) unzip: if True, unzip files upon download (default is False) """ if dataset is None: raise ValueError('A dataset must be specified') if '/' in dataset: self.validate_dataset_string(dataset) dataset_urls = dataset.split('/') owner_slug = dataset_urls[0] dataset_slug = dataset_urls[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) dataset_slug = dataset if path is None: effective_path = self.get_default_download_dir( 'datasets', owner_slug, dataset_slug) else: effective_path = path response = self.process_response( self.datasets_download_with_http_info( owner_slug=owner_slug, dataset_slug=dataset_slug, _preload_content=False)) outfile = os.path.join(effective_path, dataset_slug + '.zip') if force or self.download_needed(response, outfile, quiet): self.download_file(response, outfile, quiet) downloaded = True else: downloaded = False if downloaded: outfile = os.path.join(effective_path, dataset_slug + '.zip') if unzip: try: with zipfile.ZipFile(outfile) as z: z.extractall(effective_path) except zipfile.BadZipFile as e: raise ValueError( 'Bad zip file, please report on ' 'www.github.com/kaggle/kaggle-api', e) try: os.remove(outfile) except OSError as e: print('Could not delete zip file, got %s' % e)
[ "def", "dataset_download_files", "(", "self", ",", "dataset", ",", "path", "=", "None", ",", "force", "=", "False", ",", "quiet", "=", "True", ",", "unzip", "=", "False", ")", ":", "if", "dataset", "is", "None", ":", "raise", "ValueError", "(", "'A dataset must be specified'", ")", "if", "'/'", "in", "dataset", ":", "self", ".", "validate_dataset_string", "(", "dataset", ")", "dataset_urls", "=", "dataset", ".", "split", "(", "'/'", ")", "owner_slug", "=", "dataset_urls", "[", "0", "]", "dataset_slug", "=", "dataset_urls", "[", "1", "]", "else", ":", "owner_slug", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_USER", ")", "dataset_slug", "=", "dataset", "if", "path", "is", "None", ":", "effective_path", "=", "self", ".", "get_default_download_dir", "(", "'datasets'", ",", "owner_slug", ",", "dataset_slug", ")", "else", ":", "effective_path", "=", "path", "response", "=", "self", ".", "process_response", "(", "self", ".", "datasets_download_with_http_info", "(", "owner_slug", "=", "owner_slug", ",", "dataset_slug", "=", "dataset_slug", ",", "_preload_content", "=", "False", ")", ")", "outfile", "=", "os", ".", "path", ".", "join", "(", "effective_path", ",", "dataset_slug", "+", "'.zip'", ")", "if", "force", "or", "self", ".", "download_needed", "(", "response", ",", "outfile", ",", "quiet", ")", ":", "self", ".", "download_file", "(", "response", ",", "outfile", ",", "quiet", ")", "downloaded", "=", "True", "else", ":", "downloaded", "=", "False", "if", "downloaded", ":", "outfile", "=", "os", ".", "path", ".", "join", "(", "effective_path", ",", "dataset_slug", "+", "'.zip'", ")", "if", "unzip", ":", "try", ":", "with", "zipfile", ".", "ZipFile", "(", "outfile", ")", "as", "z", ":", "z", ".", "extractall", "(", "effective_path", ")", "except", "zipfile", ".", "BadZipFile", "as", "e", ":", "raise", "ValueError", "(", "'Bad zip file, please report on '", "'www.github.com/kaggle/kaggle-api'", ",", "e", ")", "try", ":", "os", ".", "remove", "(", "outfile", ")", "except", "OSError", "as", "e", ":", "print", "(", "'Could not delete zip file, got %s'", "%", "e", ")" ]
download all files for a dataset Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] path: the path to download the dataset to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is True) unzip: if True, unzip files upon download (default is False)
[ "download", "all", "files", "for", "a", "dataset" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1096-L1157
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_download_cli
def dataset_download_cli(self, dataset, dataset_opt=None, file_name=None, path=None, unzip=False, force=False, quiet=False): """ client wrapper for dataset_download_files and download dataset file, either for a specific file (when file_name is provided), or all files for a dataset (plural) Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] dataset_opt: an alternative option to providing a dataset file_name: the dataset configuration file path: the path to download the dataset to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False) unzip: if True, unzip files upon download (default is False) path: the path to download the dataset to """ dataset = dataset or dataset_opt if file_name is None: self.dataset_download_files( dataset, path=path, unzip=unzip, force=force, quiet=quiet) else: self.dataset_download_file( dataset, file_name, path=path, force=force, quiet=quiet)
python
def dataset_download_cli(self, dataset, dataset_opt=None, file_name=None, path=None, unzip=False, force=False, quiet=False): """ client wrapper for dataset_download_files and download dataset file, either for a specific file (when file_name is provided), or all files for a dataset (plural) Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] dataset_opt: an alternative option to providing a dataset file_name: the dataset configuration file path: the path to download the dataset to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False) unzip: if True, unzip files upon download (default is False) path: the path to download the dataset to """ dataset = dataset or dataset_opt if file_name is None: self.dataset_download_files( dataset, path=path, unzip=unzip, force=force, quiet=quiet) else: self.dataset_download_file( dataset, file_name, path=path, force=force, quiet=quiet)
[ "def", "dataset_download_cli", "(", "self", ",", "dataset", ",", "dataset_opt", "=", "None", ",", "file_name", "=", "None", ",", "path", "=", "None", ",", "unzip", "=", "False", ",", "force", "=", "False", ",", "quiet", "=", "False", ")", ":", "dataset", "=", "dataset", "or", "dataset_opt", "if", "file_name", "is", "None", ":", "self", ".", "dataset_download_files", "(", "dataset", ",", "path", "=", "path", ",", "unzip", "=", "unzip", ",", "force", "=", "force", ",", "quiet", "=", "quiet", ")", "else", ":", "self", ".", "dataset_download_file", "(", "dataset", ",", "file_name", ",", "path", "=", "path", ",", "force", "=", "force", ",", "quiet", "=", "quiet", ")" ]
client wrapper for dataset_download_files and download dataset file, either for a specific file (when file_name is provided), or all files for a dataset (plural) Parameters ========== dataset: the string identified of the dataset should be in format [owner]/[dataset-name] dataset_opt: an alternative option to providing a dataset file_name: the dataset configuration file path: the path to download the dataset to force: force the download if the file already exists (default False) quiet: suppress verbose output (default is False) unzip: if True, unzip files upon download (default is False) path: the path to download the dataset to
[ "client", "wrapper", "for", "dataset_download_files", "and", "download", "dataset", "file", "either", "for", "a", "specific", "file", "(", "when", "file_name", "is", "provided", ")", "or", "all", "files", "for", "a", "dataset", "(", "plural", ")" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1159-L1189
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_upload_file
def dataset_upload_file(self, path, quiet): """ upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False) """ file_name = os.path.basename(path) content_length = os.path.getsize(path) last_modified_date_utc = int(os.path.getmtime(path)) result = FileUploadInfo( self.process_response( self.datasets_upload_file_with_http_info( file_name, content_length, last_modified_date_utc))) success = self.upload_complete(path, result.createUrl, quiet) if success: return result.token return None
python
def dataset_upload_file(self, path, quiet): """ upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False) """ file_name = os.path.basename(path) content_length = os.path.getsize(path) last_modified_date_utc = int(os.path.getmtime(path)) result = FileUploadInfo( self.process_response( self.datasets_upload_file_with_http_info( file_name, content_length, last_modified_date_utc))) success = self.upload_complete(path, result.createUrl, quiet) if success: return result.token return None
[ "def", "dataset_upload_file", "(", "self", ",", "path", ",", "quiet", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "content_length", "=", "os", ".", "path", ".", "getsize", "(", "path", ")", "last_modified_date_utc", "=", "int", "(", "os", ".", "path", ".", "getmtime", "(", "path", ")", ")", "result", "=", "FileUploadInfo", "(", "self", ".", "process_response", "(", "self", ".", "datasets_upload_file_with_http_info", "(", "file_name", ",", "content_length", ",", "last_modified_date_utc", ")", ")", ")", "success", "=", "self", ".", "upload_complete", "(", "path", ",", "result", ".", "createUrl", ",", "quiet", ")", "if", "success", ":", "return", "result", ".", "token", "return", "None" ]
upload a dataset file Parameters ========== path: the complete path to upload quiet: suppress verbose output (default is False)
[ "upload", "a", "dataset", "file" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1191-L1211
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_create_version
def dataset_create_version(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'): """ create a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data should be converted to csv delete_old_versions: if True, do that (default False) dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = self.get_dataset_metadata_file(folder) # read json with open(meta_file) as f: meta_data = json.load(f) ref = self.get_or_default(meta_data, 'id', None) id_no = self.get_or_default(meta_data, 'id_no', None) if not ref and not id_no: raise ValueError('ID or slug must be specified in the metadata') subtitle = meta_data.get('subtitle') if subtitle and (len(subtitle) < 20 or len(subtitle) > 80): raise ValueError( 'Subtitle length must be between 20 and 80 characters') resources = meta_data.get('resources') if resources: self.validate_resources(folder, resources) description = meta_data.get('description') keywords = self.get_or_default(meta_data, 'keywords', []) request = DatasetNewVersionRequest( version_notes=version_notes, subtitle=subtitle, description=description, files=[], convert_to_csv=convert_to_csv, category_ids=keywords, delete_old_versions=delete_old_versions) self.upload_files(request, resources, folder, quiet, dir_mode) if id_no: result = DatasetNewVersionResponse( self.process_response( self.datasets_create_version_by_id_with_http_info( id_no, request))) else: if ref == self.config_values[ self.CONFIG_NAME_USER] + '/INSERT_SLUG_HERE': raise ValueError( 'Default slug detected, please change values before ' 'uploading') self.validate_dataset_string(ref) ref_list = ref.split('/') owner_slug = ref_list[0] dataset_slug = ref_list[1] result = DatasetNewVersionResponse( self.process_response( self.datasets_create_version_with_http_info( owner_slug, dataset_slug, request))) return result
python
def dataset_create_version(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'): """ create a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data should be converted to csv delete_old_versions: if True, do that (default False) dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = self.get_dataset_metadata_file(folder) # read json with open(meta_file) as f: meta_data = json.load(f) ref = self.get_or_default(meta_data, 'id', None) id_no = self.get_or_default(meta_data, 'id_no', None) if not ref and not id_no: raise ValueError('ID or slug must be specified in the metadata') subtitle = meta_data.get('subtitle') if subtitle and (len(subtitle) < 20 or len(subtitle) > 80): raise ValueError( 'Subtitle length must be between 20 and 80 characters') resources = meta_data.get('resources') if resources: self.validate_resources(folder, resources) description = meta_data.get('description') keywords = self.get_or_default(meta_data, 'keywords', []) request = DatasetNewVersionRequest( version_notes=version_notes, subtitle=subtitle, description=description, files=[], convert_to_csv=convert_to_csv, category_ids=keywords, delete_old_versions=delete_old_versions) self.upload_files(request, resources, folder, quiet, dir_mode) if id_no: result = DatasetNewVersionResponse( self.process_response( self.datasets_create_version_by_id_with_http_info( id_no, request))) else: if ref == self.config_values[ self.CONFIG_NAME_USER] + '/INSERT_SLUG_HERE': raise ValueError( 'Default slug detected, please change values before ' 'uploading') self.validate_dataset_string(ref) ref_list = ref.split('/') owner_slug = ref_list[0] dataset_slug = ref_list[1] result = DatasetNewVersionResponse( self.process_response( self.datasets_create_version_with_http_info( owner_slug, dataset_slug, request))) return result
[ "def", "dataset_create_version", "(", "self", ",", "folder", ",", "version_notes", ",", "quiet", "=", "False", ",", "convert_to_csv", "=", "True", ",", "delete_old_versions", "=", "False", ",", "dir_mode", "=", "'skip'", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "raise", "ValueError", "(", "'Invalid folder: '", "+", "folder", ")", "meta_file", "=", "self", ".", "get_dataset_metadata_file", "(", "folder", ")", "# read json", "with", "open", "(", "meta_file", ")", "as", "f", ":", "meta_data", "=", "json", ".", "load", "(", "f", ")", "ref", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'id'", ",", "None", ")", "id_no", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'id_no'", ",", "None", ")", "if", "not", "ref", "and", "not", "id_no", ":", "raise", "ValueError", "(", "'ID or slug must be specified in the metadata'", ")", "subtitle", "=", "meta_data", ".", "get", "(", "'subtitle'", ")", "if", "subtitle", "and", "(", "len", "(", "subtitle", ")", "<", "20", "or", "len", "(", "subtitle", ")", ">", "80", ")", ":", "raise", "ValueError", "(", "'Subtitle length must be between 20 and 80 characters'", ")", "resources", "=", "meta_data", ".", "get", "(", "'resources'", ")", "if", "resources", ":", "self", ".", "validate_resources", "(", "folder", ",", "resources", ")", "description", "=", "meta_data", ".", "get", "(", "'description'", ")", "keywords", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'keywords'", ",", "[", "]", ")", "request", "=", "DatasetNewVersionRequest", "(", "version_notes", "=", "version_notes", ",", "subtitle", "=", "subtitle", ",", "description", "=", "description", ",", "files", "=", "[", "]", ",", "convert_to_csv", "=", "convert_to_csv", ",", "category_ids", "=", "keywords", ",", "delete_old_versions", "=", "delete_old_versions", ")", "self", ".", "upload_files", "(", "request", ",", "resources", ",", "folder", ",", "quiet", ",", "dir_mode", ")", "if", "id_no", ":", "result", "=", "DatasetNewVersionResponse", "(", "self", ".", "process_response", "(", "self", ".", "datasets_create_version_by_id_with_http_info", "(", "id_no", ",", "request", ")", ")", ")", "else", ":", "if", "ref", "==", "self", ".", "config_values", "[", "self", ".", "CONFIG_NAME_USER", "]", "+", "'/INSERT_SLUG_HERE'", ":", "raise", "ValueError", "(", "'Default slug detected, please change values before '", "'uploading'", ")", "self", ".", "validate_dataset_string", "(", "ref", ")", "ref_list", "=", "ref", ".", "split", "(", "'/'", ")", "owner_slug", "=", "ref_list", "[", "0", "]", "dataset_slug", "=", "ref_list", "[", "1", "]", "result", "=", "DatasetNewVersionResponse", "(", "self", ".", "process_response", "(", "self", ".", "datasets_create_version_with_http_info", "(", "owner_slug", ",", "dataset_slug", ",", "request", ")", ")", ")", "return", "result" ]
create a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data should be converted to csv delete_old_versions: if True, do that (default False) dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload
[ "create", "a", "version", "of", "a", "dataset" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1213-L1285
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_create_version_cli
def dataset_create_version_cli(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'): """ client wrapper for creating a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data should be converted to csv delete_old_versions: if True, do that (default False) dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ folder = folder or os.getcwd() result = self.dataset_create_version( folder, version_notes, quiet=quiet, convert_to_csv=convert_to_csv, delete_old_versions=delete_old_versions, dir_mode=dir_mode) if result.invalidTags: print( ('The following are not valid tags and could not be added to ' 'the dataset: ') + str(result.invalidTags)) if result is None: print('Dataset version creation error: See previous output') elif result.status.lower() == 'ok': print('Dataset version is being created. Please check progress at ' + result.url) else: print('Dataset version creation error: ' + result.error)
python
def dataset_create_version_cli(self, folder, version_notes, quiet=False, convert_to_csv=True, delete_old_versions=False, dir_mode='skip'): """ client wrapper for creating a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data should be converted to csv delete_old_versions: if True, do that (default False) dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ folder = folder or os.getcwd() result = self.dataset_create_version( folder, version_notes, quiet=quiet, convert_to_csv=convert_to_csv, delete_old_versions=delete_old_versions, dir_mode=dir_mode) if result.invalidTags: print( ('The following are not valid tags and could not be added to ' 'the dataset: ') + str(result.invalidTags)) if result is None: print('Dataset version creation error: See previous output') elif result.status.lower() == 'ok': print('Dataset version is being created. Please check progress at ' + result.url) else: print('Dataset version creation error: ' + result.error)
[ "def", "dataset_create_version_cli", "(", "self", ",", "folder", ",", "version_notes", ",", "quiet", "=", "False", ",", "convert_to_csv", "=", "True", ",", "delete_old_versions", "=", "False", ",", "dir_mode", "=", "'skip'", ")", ":", "folder", "=", "folder", "or", "os", ".", "getcwd", "(", ")", "result", "=", "self", ".", "dataset_create_version", "(", "folder", ",", "version_notes", ",", "quiet", "=", "quiet", ",", "convert_to_csv", "=", "convert_to_csv", ",", "delete_old_versions", "=", "delete_old_versions", ",", "dir_mode", "=", "dir_mode", ")", "if", "result", ".", "invalidTags", ":", "print", "(", "(", "'The following are not valid tags and could not be added to '", "'the dataset: '", ")", "+", "str", "(", "result", ".", "invalidTags", ")", ")", "if", "result", "is", "None", ":", "print", "(", "'Dataset version creation error: See previous output'", ")", "elif", "result", ".", "status", ".", "lower", "(", ")", "==", "'ok'", ":", "print", "(", "'Dataset version is being created. Please check progress at '", "+", "result", ".", "url", ")", "else", ":", "print", "(", "'Dataset version creation error: '", "+", "result", ".", "error", ")" ]
client wrapper for creating a version of a dataset Parameters ========== folder: the folder with the dataset configuration / data files version_notes: notes to add for the version quiet: suppress verbose output (default is False) convert_to_csv: on upload, if data should be converted to csv delete_old_versions: if True, do that (default False) dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload
[ "client", "wrapper", "for", "creating", "a", "version", "of", "a", "dataset", "Parameters", "==========", "folder", ":", "the", "folder", "with", "the", "dataset", "configuration", "/", "data", "files", "version_notes", ":", "notes", "to", "add", "for", "the", "version", "quiet", ":", "suppress", "verbose", "output", "(", "default", "is", "False", ")", "convert_to_csv", ":", "on", "upload", "if", "data", "should", "be", "converted", "to", "csv", "delete_old_versions", ":", "if", "True", "do", "that", "(", "default", "False", ")", "dir_mode", ":", "What", "to", "do", "with", "directories", ":", "skip", "-", "ignore", ";", "zip", "-", "compress", "and", "upload" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1287-L1322
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_initialize
def dataset_initialize(self, folder): """ initialize a folder with a a dataset configuration (metadata) file Parameters ========== folder: the folder to initialize the metadata file in """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) ref = self.config_values[self.CONFIG_NAME_USER] + '/INSERT_SLUG_HERE' licenses = [] default_license = {'name': 'CC0-1.0'} licenses.append(default_license) meta_data = { 'title': 'INSERT_TITLE_HERE', 'id': ref, 'licenses': licenses } meta_file = os.path.join(folder, self.DATASET_METADATA_FILE) with open(meta_file, 'w') as f: json.dump(meta_data, f, indent=2) print('Data package template written to: ' + meta_file) return meta_file
python
def dataset_initialize(self, folder): """ initialize a folder with a a dataset configuration (metadata) file Parameters ========== folder: the folder to initialize the metadata file in """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) ref = self.config_values[self.CONFIG_NAME_USER] + '/INSERT_SLUG_HERE' licenses = [] default_license = {'name': 'CC0-1.0'} licenses.append(default_license) meta_data = { 'title': 'INSERT_TITLE_HERE', 'id': ref, 'licenses': licenses } meta_file = os.path.join(folder, self.DATASET_METADATA_FILE) with open(meta_file, 'w') as f: json.dump(meta_data, f, indent=2) print('Data package template written to: ' + meta_file) return meta_file
[ "def", "dataset_initialize", "(", "self", ",", "folder", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "raise", "ValueError", "(", "'Invalid folder: '", "+", "folder", ")", "ref", "=", "self", ".", "config_values", "[", "self", ".", "CONFIG_NAME_USER", "]", "+", "'/INSERT_SLUG_HERE'", "licenses", "=", "[", "]", "default_license", "=", "{", "'name'", ":", "'CC0-1.0'", "}", "licenses", ".", "append", "(", "default_license", ")", "meta_data", "=", "{", "'title'", ":", "'INSERT_TITLE_HERE'", ",", "'id'", ":", "ref", ",", "'licenses'", ":", "licenses", "}", "meta_file", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "self", ".", "DATASET_METADATA_FILE", ")", "with", "open", "(", "meta_file", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "meta_data", ",", "f", ",", "indent", "=", "2", ")", "print", "(", "'Data package template written to: '", "+", "meta_file", ")", "return", "meta_file" ]
initialize a folder with a a dataset configuration (metadata) file Parameters ========== folder: the folder to initialize the metadata file in
[ "initialize", "a", "folder", "with", "a", "a", "dataset", "configuration", "(", "metadata", ")", "file" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1324-L1349
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_create_new
def dataset_create_new(self, folder, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ create a new dataset, meaning the same as creating a version but with extra metadata like license and user/owner. Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to comma separated value dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = self.get_dataset_metadata_file(folder) # read json with open(meta_file) as f: meta_data = json.load(f) ref = self.get_or_fail(meta_data, 'id') title = self.get_or_fail(meta_data, 'title') licenses = self.get_or_fail(meta_data, 'licenses') ref_list = ref.split('/') owner_slug = ref_list[0] dataset_slug = ref_list[1] # validations if ref == self.config_values[self. CONFIG_NAME_USER] + '/INSERT_SLUG_HERE': raise ValueError( 'Default slug detected, please change values before uploading') if title == 'INSERT_TITLE_HERE': raise ValueError( 'Default title detected, please change values before uploading' ) if len(licenses) != 1: raise ValueError('Please specify exactly one license') if len(dataset_slug) < 6 or len(dataset_slug) > 50: raise ValueError( 'The dataset slug must be between 6 and 50 characters') if len(title) < 6 or len(title) > 50: raise ValueError( 'The dataset title must be between 6 and 50 characters') resources = meta_data.get('resources') if resources: self.validate_resources(folder, resources) license_name = self.get_or_fail(licenses[0], 'name') description = meta_data.get('description') keywords = self.get_or_default(meta_data, 'keywords', []) subtitle = meta_data.get('subtitle') if subtitle and (len(subtitle) < 20 or len(subtitle) > 80): raise ValueError( 'Subtitle length must be between 20 and 80 characters') request = DatasetNewRequest( title=title, slug=dataset_slug, owner_slug=owner_slug, license_name=license_name, subtitle=subtitle, description=description, files=[], is_private=not public, convert_to_csv=convert_to_csv, category_ids=keywords) resources = meta_data.get('resources') self.upload_files(request, resources, folder, quiet, dir_mode) result = DatasetNewResponse( self.process_response( self.datasets_create_new_with_http_info(request))) return result
python
def dataset_create_new(self, folder, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ create a new dataset, meaning the same as creating a version but with extra metadata like license and user/owner. Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to comma separated value dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = self.get_dataset_metadata_file(folder) # read json with open(meta_file) as f: meta_data = json.load(f) ref = self.get_or_fail(meta_data, 'id') title = self.get_or_fail(meta_data, 'title') licenses = self.get_or_fail(meta_data, 'licenses') ref_list = ref.split('/') owner_slug = ref_list[0] dataset_slug = ref_list[1] # validations if ref == self.config_values[self. CONFIG_NAME_USER] + '/INSERT_SLUG_HERE': raise ValueError( 'Default slug detected, please change values before uploading') if title == 'INSERT_TITLE_HERE': raise ValueError( 'Default title detected, please change values before uploading' ) if len(licenses) != 1: raise ValueError('Please specify exactly one license') if len(dataset_slug) < 6 or len(dataset_slug) > 50: raise ValueError( 'The dataset slug must be between 6 and 50 characters') if len(title) < 6 or len(title) > 50: raise ValueError( 'The dataset title must be between 6 and 50 characters') resources = meta_data.get('resources') if resources: self.validate_resources(folder, resources) license_name = self.get_or_fail(licenses[0], 'name') description = meta_data.get('description') keywords = self.get_or_default(meta_data, 'keywords', []) subtitle = meta_data.get('subtitle') if subtitle and (len(subtitle) < 20 or len(subtitle) > 80): raise ValueError( 'Subtitle length must be between 20 and 80 characters') request = DatasetNewRequest( title=title, slug=dataset_slug, owner_slug=owner_slug, license_name=license_name, subtitle=subtitle, description=description, files=[], is_private=not public, convert_to_csv=convert_to_csv, category_ids=keywords) resources = meta_data.get('resources') self.upload_files(request, resources, folder, quiet, dir_mode) result = DatasetNewResponse( self.process_response( self.datasets_create_new_with_http_info(request))) return result
[ "def", "dataset_create_new", "(", "self", ",", "folder", ",", "public", "=", "False", ",", "quiet", "=", "False", ",", "convert_to_csv", "=", "True", ",", "dir_mode", "=", "'skip'", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "raise", "ValueError", "(", "'Invalid folder: '", "+", "folder", ")", "meta_file", "=", "self", ".", "get_dataset_metadata_file", "(", "folder", ")", "# read json", "with", "open", "(", "meta_file", ")", "as", "f", ":", "meta_data", "=", "json", ".", "load", "(", "f", ")", "ref", "=", "self", ".", "get_or_fail", "(", "meta_data", ",", "'id'", ")", "title", "=", "self", ".", "get_or_fail", "(", "meta_data", ",", "'title'", ")", "licenses", "=", "self", ".", "get_or_fail", "(", "meta_data", ",", "'licenses'", ")", "ref_list", "=", "ref", ".", "split", "(", "'/'", ")", "owner_slug", "=", "ref_list", "[", "0", "]", "dataset_slug", "=", "ref_list", "[", "1", "]", "# validations", "if", "ref", "==", "self", ".", "config_values", "[", "self", ".", "CONFIG_NAME_USER", "]", "+", "'/INSERT_SLUG_HERE'", ":", "raise", "ValueError", "(", "'Default slug detected, please change values before uploading'", ")", "if", "title", "==", "'INSERT_TITLE_HERE'", ":", "raise", "ValueError", "(", "'Default title detected, please change values before uploading'", ")", "if", "len", "(", "licenses", ")", "!=", "1", ":", "raise", "ValueError", "(", "'Please specify exactly one license'", ")", "if", "len", "(", "dataset_slug", ")", "<", "6", "or", "len", "(", "dataset_slug", ")", ">", "50", ":", "raise", "ValueError", "(", "'The dataset slug must be between 6 and 50 characters'", ")", "if", "len", "(", "title", ")", "<", "6", "or", "len", "(", "title", ")", ">", "50", ":", "raise", "ValueError", "(", "'The dataset title must be between 6 and 50 characters'", ")", "resources", "=", "meta_data", ".", "get", "(", "'resources'", ")", "if", "resources", ":", "self", ".", "validate_resources", "(", "folder", ",", "resources", ")", "license_name", "=", "self", ".", "get_or_fail", "(", "licenses", "[", "0", "]", ",", "'name'", ")", "description", "=", "meta_data", ".", "get", "(", "'description'", ")", "keywords", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'keywords'", ",", "[", "]", ")", "subtitle", "=", "meta_data", ".", "get", "(", "'subtitle'", ")", "if", "subtitle", "and", "(", "len", "(", "subtitle", ")", "<", "20", "or", "len", "(", "subtitle", ")", ">", "80", ")", ":", "raise", "ValueError", "(", "'Subtitle length must be between 20 and 80 characters'", ")", "request", "=", "DatasetNewRequest", "(", "title", "=", "title", ",", "slug", "=", "dataset_slug", ",", "owner_slug", "=", "owner_slug", ",", "license_name", "=", "license_name", ",", "subtitle", "=", "subtitle", ",", "description", "=", "description", ",", "files", "=", "[", "]", ",", "is_private", "=", "not", "public", ",", "convert_to_csv", "=", "convert_to_csv", ",", "category_ids", "=", "keywords", ")", "resources", "=", "meta_data", ".", "get", "(", "'resources'", ")", "self", ".", "upload_files", "(", "request", ",", "resources", ",", "folder", ",", "quiet", ",", "dir_mode", ")", "result", "=", "DatasetNewResponse", "(", "self", ".", "process_response", "(", "self", ".", "datasets_create_new_with_http_info", "(", "request", ")", ")", ")", "return", "result" ]
create a new dataset, meaning the same as creating a version but with extra metadata like license and user/owner. Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to comma separated value dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload
[ "create", "a", "new", "dataset", "meaning", "the", "same", "as", "creating", "a", "version", "but", "with", "extra", "metadata", "like", "license", "and", "user", "/", "owner", ".", "Parameters", "==========", "folder", ":", "the", "folder", "to", "initialize", "the", "metadata", "file", "in", "public", ":", "should", "the", "dataset", "be", "public?", "quiet", ":", "suppress", "verbose", "output", "(", "default", "is", "False", ")", "convert_to_csv", ":", "if", "True", "convert", "data", "to", "comma", "separated", "value", "dir_mode", ":", "What", "to", "do", "with", "directories", ":", "skip", "-", "ignore", ";", "zip", "-", "compress", "and", "upload" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1355-L1433
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.dataset_create_new_cli
def dataset_create_new_cli(self, folder=None, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ client wrapper for creating a new dataset Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to comma separated value dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ folder = folder or os.getcwd() result = self.dataset_create_new(folder, public, quiet, convert_to_csv, dir_mode) if result.invalidTags: print('The following are not valid tags and could not be added to ' 'the dataset: ' + str(result.invalidTags)) if result.status.lower() == 'ok': if public: print('Your public Dataset is being created. Please check ' 'progress at ' + result.url) else: print('Your private Dataset is being created. Please check ' 'progress at ' + result.url) else: print('Dataset creation error: ' + result.error)
python
def dataset_create_new_cli(self, folder=None, public=False, quiet=False, convert_to_csv=True, dir_mode='skip'): """ client wrapper for creating a new dataset Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to comma separated value dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload """ folder = folder or os.getcwd() result = self.dataset_create_new(folder, public, quiet, convert_to_csv, dir_mode) if result.invalidTags: print('The following are not valid tags and could not be added to ' 'the dataset: ' + str(result.invalidTags)) if result.status.lower() == 'ok': if public: print('Your public Dataset is being created. Please check ' 'progress at ' + result.url) else: print('Your private Dataset is being created. Please check ' 'progress at ' + result.url) else: print('Dataset creation error: ' + result.error)
[ "def", "dataset_create_new_cli", "(", "self", ",", "folder", "=", "None", ",", "public", "=", "False", ",", "quiet", "=", "False", ",", "convert_to_csv", "=", "True", ",", "dir_mode", "=", "'skip'", ")", ":", "folder", "=", "folder", "or", "os", ".", "getcwd", "(", ")", "result", "=", "self", ".", "dataset_create_new", "(", "folder", ",", "public", ",", "quiet", ",", "convert_to_csv", ",", "dir_mode", ")", "if", "result", ".", "invalidTags", ":", "print", "(", "'The following are not valid tags and could not be added to '", "'the dataset: '", "+", "str", "(", "result", ".", "invalidTags", ")", ")", "if", "result", ".", "status", ".", "lower", "(", ")", "==", "'ok'", ":", "if", "public", ":", "print", "(", "'Your public Dataset is being created. Please check '", "'progress at '", "+", "result", ".", "url", ")", "else", ":", "print", "(", "'Your private Dataset is being created. Please check '", "'progress at '", "+", "result", ".", "url", ")", "else", ":", "print", "(", "'Dataset creation error: '", "+", "result", ".", "error", ")" ]
client wrapper for creating a new dataset Parameters ========== folder: the folder to initialize the metadata file in public: should the dataset be public? quiet: suppress verbose output (default is False) convert_to_csv: if True, convert data to comma separated value dir_mode: What to do with directories: "skip" - ignore; "zip" - compress and upload
[ "client", "wrapper", "for", "creating", "a", "new", "dataset", "Parameters", "==========", "folder", ":", "the", "folder", "to", "initialize", "the", "metadata", "file", "in", "public", ":", "should", "the", "dataset", "be", "public?", "quiet", ":", "suppress", "verbose", "output", "(", "default", "is", "False", ")", "convert_to_csv", ":", "if", "True", "convert", "data", "to", "comma", "separated", "value", "dir_mode", ":", "What", "to", "do", "with", "directories", ":", "skip", "-", "ignore", ";", "zip", "-", "compress", "and", "upload" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1435-L1464
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.download_file
def download_file(self, response, outfile, quiet=True, chunk_size=1048576): """ download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress verbose output (default is True) chunk_size: the size of the chunk to stream """ outpath = os.path.dirname(outfile) if not os.path.exists(outpath): os.makedirs(outpath) size = int(response.headers['Content-Length']) size_read = 0 if not quiet: print('Downloading ' + os.path.basename(outfile) + ' to ' + outpath) with tqdm( total=size, unit='B', unit_scale=True, unit_divisor=1024, disable=quiet) as pbar: with open(outfile, 'wb') as out: while True: data = response.read(chunk_size) if not data: break out.write(data) size_read = min(size, size_read + chunk_size) pbar.update(len(data)) if not quiet: print('\n', end='')
python
def download_file(self, response, outfile, quiet=True, chunk_size=1048576): """ download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress verbose output (default is True) chunk_size: the size of the chunk to stream """ outpath = os.path.dirname(outfile) if not os.path.exists(outpath): os.makedirs(outpath) size = int(response.headers['Content-Length']) size_read = 0 if not quiet: print('Downloading ' + os.path.basename(outfile) + ' to ' + outpath) with tqdm( total=size, unit='B', unit_scale=True, unit_divisor=1024, disable=quiet) as pbar: with open(outfile, 'wb') as out: while True: data = response.read(chunk_size) if not data: break out.write(data) size_read = min(size, size_read + chunk_size) pbar.update(len(data)) if not quiet: print('\n', end='')
[ "def", "download_file", "(", "self", ",", "response", ",", "outfile", ",", "quiet", "=", "True", ",", "chunk_size", "=", "1048576", ")", ":", "outpath", "=", "os", ".", "path", ".", "dirname", "(", "outfile", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "outpath", ")", ":", "os", ".", "makedirs", "(", "outpath", ")", "size", "=", "int", "(", "response", ".", "headers", "[", "'Content-Length'", "]", ")", "size_read", "=", "0", "if", "not", "quiet", ":", "print", "(", "'Downloading '", "+", "os", ".", "path", ".", "basename", "(", "outfile", ")", "+", "' to '", "+", "outpath", ")", "with", "tqdm", "(", "total", "=", "size", ",", "unit", "=", "'B'", ",", "unit_scale", "=", "True", ",", "unit_divisor", "=", "1024", ",", "disable", "=", "quiet", ")", "as", "pbar", ":", "with", "open", "(", "outfile", ",", "'wb'", ")", "as", "out", ":", "while", "True", ":", "data", "=", "response", ".", "read", "(", "chunk_size", ")", "if", "not", "data", ":", "break", "out", ".", "write", "(", "data", ")", "size_read", "=", "min", "(", "size", ",", "size_read", "+", "chunk_size", ")", "pbar", ".", "update", "(", "len", "(", "data", ")", ")", "if", "not", "quiet", ":", "print", "(", "'\\n'", ",", "end", "=", "''", ")" ]
download a file to an output file based on a chunk size Parameters ========== response: the response to download outfile: the output file to download to quiet: suppress verbose output (default is True) chunk_size: the size of the chunk to stream
[ "download", "a", "file", "to", "an", "output", "file", "based", "on", "a", "chunk", "size" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1466-L1500
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_list
def kernels_list(self, page=1, page_size=20, dataset=None, competition=None, parent_kernel=None, search=None, mine=False, user=None, language=None, kernel_type=None, output_type=None, sort_by=None): """ list kernels based on a set of search criteria Parameters ========== page: the page of results to return (default is 1) page_size: results per page (default is 20) dataset: if defined, filter to this dataset (default None) competition: if defined, filter to this competition (default None) parent_kernel: if defined, filter to those with specified parent search: a custom search string to pass to the list query mine: if true, group is specified as "my" to return personal kernels user: filter results to a specific user language: the programming language of the kernel kernel_type: the type of kernel, one of valid_kernel_types (str) output_type: the output type, one of valid_output_types (str) sort_by: if defined, sort results by this string (valid_sort_by) """ if int(page) <= 0: raise ValueError('Page number must be >= 1') page_size = int(page_size) if page_size <= 0: raise ValueError('Page size must be >= 1') if page_size > 100: page_size = 100 valid_languages = ['all', 'python', 'r', 'sqlite', 'julia'] if language and language not in valid_languages: raise ValueError('Invalid language specified. Valid options are ' + str(valid_languages)) valid_kernel_types = ['all', 'script', 'notebook'] if kernel_type and kernel_type not in valid_kernel_types: raise ValueError( 'Invalid kernel type specified. Valid options are ' + str(valid_kernel_types)) valid_output_types = ['all', 'visualization', 'data'] if output_type and output_type not in valid_output_types: raise ValueError( 'Invalid output type specified. Valid options are ' + str(valid_output_types)) valid_sort_by = [ 'hotness', 'commentCount', 'dateCreated', 'dateRun', 'relevance', 'scoreAscending', 'scoreDescending', 'viewCount', 'voteCount' ] if sort_by and sort_by not in valid_sort_by: raise ValueError( 'Invalid sort by type specified. Valid options are ' + str(valid_sort_by)) if sort_by == 'relevance' and search == '': raise ValueError('Cannot sort by relevance without a search term.') self.validate_dataset_string(dataset) self.validate_kernel_string(parent_kernel) group = 'everyone' if mine: group = 'profile' kernels_list_result = self.process_response( self.kernels_list_with_http_info( page=page, page_size=page_size, group=group, user=user or '', language=language or 'all', kernel_type=kernel_type or 'all', output_type=output_type or 'all', sort_by=sort_by or 'hotness', dataset=dataset or '', competition=competition or '', parent_kernel=parent_kernel or '', search=search or '')) return [Kernel(k) for k in kernels_list_result]
python
def kernels_list(self, page=1, page_size=20, dataset=None, competition=None, parent_kernel=None, search=None, mine=False, user=None, language=None, kernel_type=None, output_type=None, sort_by=None): """ list kernels based on a set of search criteria Parameters ========== page: the page of results to return (default is 1) page_size: results per page (default is 20) dataset: if defined, filter to this dataset (default None) competition: if defined, filter to this competition (default None) parent_kernel: if defined, filter to those with specified parent search: a custom search string to pass to the list query mine: if true, group is specified as "my" to return personal kernels user: filter results to a specific user language: the programming language of the kernel kernel_type: the type of kernel, one of valid_kernel_types (str) output_type: the output type, one of valid_output_types (str) sort_by: if defined, sort results by this string (valid_sort_by) """ if int(page) <= 0: raise ValueError('Page number must be >= 1') page_size = int(page_size) if page_size <= 0: raise ValueError('Page size must be >= 1') if page_size > 100: page_size = 100 valid_languages = ['all', 'python', 'r', 'sqlite', 'julia'] if language and language not in valid_languages: raise ValueError('Invalid language specified. Valid options are ' + str(valid_languages)) valid_kernel_types = ['all', 'script', 'notebook'] if kernel_type and kernel_type not in valid_kernel_types: raise ValueError( 'Invalid kernel type specified. Valid options are ' + str(valid_kernel_types)) valid_output_types = ['all', 'visualization', 'data'] if output_type and output_type not in valid_output_types: raise ValueError( 'Invalid output type specified. Valid options are ' + str(valid_output_types)) valid_sort_by = [ 'hotness', 'commentCount', 'dateCreated', 'dateRun', 'relevance', 'scoreAscending', 'scoreDescending', 'viewCount', 'voteCount' ] if sort_by and sort_by not in valid_sort_by: raise ValueError( 'Invalid sort by type specified. Valid options are ' + str(valid_sort_by)) if sort_by == 'relevance' and search == '': raise ValueError('Cannot sort by relevance without a search term.') self.validate_dataset_string(dataset) self.validate_kernel_string(parent_kernel) group = 'everyone' if mine: group = 'profile' kernels_list_result = self.process_response( self.kernels_list_with_http_info( page=page, page_size=page_size, group=group, user=user or '', language=language or 'all', kernel_type=kernel_type or 'all', output_type=output_type or 'all', sort_by=sort_by or 'hotness', dataset=dataset or '', competition=competition or '', parent_kernel=parent_kernel or '', search=search or '')) return [Kernel(k) for k in kernels_list_result]
[ "def", "kernels_list", "(", "self", ",", "page", "=", "1", ",", "page_size", "=", "20", ",", "dataset", "=", "None", ",", "competition", "=", "None", ",", "parent_kernel", "=", "None", ",", "search", "=", "None", ",", "mine", "=", "False", ",", "user", "=", "None", ",", "language", "=", "None", ",", "kernel_type", "=", "None", ",", "output_type", "=", "None", ",", "sort_by", "=", "None", ")", ":", "if", "int", "(", "page", ")", "<=", "0", ":", "raise", "ValueError", "(", "'Page number must be >= 1'", ")", "page_size", "=", "int", "(", "page_size", ")", "if", "page_size", "<=", "0", ":", "raise", "ValueError", "(", "'Page size must be >= 1'", ")", "if", "page_size", ">", "100", ":", "page_size", "=", "100", "valid_languages", "=", "[", "'all'", ",", "'python'", ",", "'r'", ",", "'sqlite'", ",", "'julia'", "]", "if", "language", "and", "language", "not", "in", "valid_languages", ":", "raise", "ValueError", "(", "'Invalid language specified. Valid options are '", "+", "str", "(", "valid_languages", ")", ")", "valid_kernel_types", "=", "[", "'all'", ",", "'script'", ",", "'notebook'", "]", "if", "kernel_type", "and", "kernel_type", "not", "in", "valid_kernel_types", ":", "raise", "ValueError", "(", "'Invalid kernel type specified. Valid options are '", "+", "str", "(", "valid_kernel_types", ")", ")", "valid_output_types", "=", "[", "'all'", ",", "'visualization'", ",", "'data'", "]", "if", "output_type", "and", "output_type", "not", "in", "valid_output_types", ":", "raise", "ValueError", "(", "'Invalid output type specified. Valid options are '", "+", "str", "(", "valid_output_types", ")", ")", "valid_sort_by", "=", "[", "'hotness'", ",", "'commentCount'", ",", "'dateCreated'", ",", "'dateRun'", ",", "'relevance'", ",", "'scoreAscending'", ",", "'scoreDescending'", ",", "'viewCount'", ",", "'voteCount'", "]", "if", "sort_by", "and", "sort_by", "not", "in", "valid_sort_by", ":", "raise", "ValueError", "(", "'Invalid sort by type specified. Valid options are '", "+", "str", "(", "valid_sort_by", ")", ")", "if", "sort_by", "==", "'relevance'", "and", "search", "==", "''", ":", "raise", "ValueError", "(", "'Cannot sort by relevance without a search term.'", ")", "self", ".", "validate_dataset_string", "(", "dataset", ")", "self", ".", "validate_kernel_string", "(", "parent_kernel", ")", "group", "=", "'everyone'", "if", "mine", ":", "group", "=", "'profile'", "kernels_list_result", "=", "self", ".", "process_response", "(", "self", ".", "kernels_list_with_http_info", "(", "page", "=", "page", ",", "page_size", "=", "page_size", ",", "group", "=", "group", ",", "user", "=", "user", "or", "''", ",", "language", "=", "language", "or", "'all'", ",", "kernel_type", "=", "kernel_type", "or", "'all'", ",", "output_type", "=", "output_type", "or", "'all'", ",", "sort_by", "=", "sort_by", "or", "'hotness'", ",", "dataset", "=", "dataset", "or", "''", ",", "competition", "=", "competition", "or", "''", ",", "parent_kernel", "=", "parent_kernel", "or", "''", ",", "search", "=", "search", "or", "''", ")", ")", "return", "[", "Kernel", "(", "k", ")", "for", "k", "in", "kernels_list_result", "]" ]
list kernels based on a set of search criteria Parameters ========== page: the page of results to return (default is 1) page_size: results per page (default is 20) dataset: if defined, filter to this dataset (default None) competition: if defined, filter to this competition (default None) parent_kernel: if defined, filter to those with specified parent search: a custom search string to pass to the list query mine: if true, group is specified as "my" to return personal kernels user: filter results to a specific user language: the programming language of the kernel kernel_type: the type of kernel, one of valid_kernel_types (str) output_type: the output type, one of valid_output_types (str) sort_by: if defined, sort results by this string (valid_sort_by)
[ "list", "kernels", "based", "on", "a", "set", "of", "search", "criteria" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1502-L1590
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_list_cli
def kernels_list_cli(self, mine=False, page=1, page_size=20, search=None, csv_display=False, parent=None, competition=None, dataset=None, user=None, language=None, kernel_type=None, output_type=None, sort_by=None): """ client wrapper for kernels_list, see this function for arguments. Additional arguments are provided here. Parameters ========== csv_display: if True, print comma separated values instead of table """ kernels = self.kernels_list( page=page, page_size=page_size, search=search, mine=mine, dataset=dataset, competition=competition, parent_kernel=parent, user=user, language=language, kernel_type=kernel_type, output_type=output_type, sort_by=sort_by) fields = ['ref', 'title', 'author', 'lastRunTime', 'totalVotes'] if kernels: if csv_display: self.print_csv(kernels, fields) else: self.print_table(kernels, fields) else: print('No kernels found')
python
def kernels_list_cli(self, mine=False, page=1, page_size=20, search=None, csv_display=False, parent=None, competition=None, dataset=None, user=None, language=None, kernel_type=None, output_type=None, sort_by=None): """ client wrapper for kernels_list, see this function for arguments. Additional arguments are provided here. Parameters ========== csv_display: if True, print comma separated values instead of table """ kernels = self.kernels_list( page=page, page_size=page_size, search=search, mine=mine, dataset=dataset, competition=competition, parent_kernel=parent, user=user, language=language, kernel_type=kernel_type, output_type=output_type, sort_by=sort_by) fields = ['ref', 'title', 'author', 'lastRunTime', 'totalVotes'] if kernels: if csv_display: self.print_csv(kernels, fields) else: self.print_table(kernels, fields) else: print('No kernels found')
[ "def", "kernels_list_cli", "(", "self", ",", "mine", "=", "False", ",", "page", "=", "1", ",", "page_size", "=", "20", ",", "search", "=", "None", ",", "csv_display", "=", "False", ",", "parent", "=", "None", ",", "competition", "=", "None", ",", "dataset", "=", "None", ",", "user", "=", "None", ",", "language", "=", "None", ",", "kernel_type", "=", "None", ",", "output_type", "=", "None", ",", "sort_by", "=", "None", ")", ":", "kernels", "=", "self", ".", "kernels_list", "(", "page", "=", "page", ",", "page_size", "=", "page_size", ",", "search", "=", "search", ",", "mine", "=", "mine", ",", "dataset", "=", "dataset", ",", "competition", "=", "competition", ",", "parent_kernel", "=", "parent", ",", "user", "=", "user", ",", "language", "=", "language", ",", "kernel_type", "=", "kernel_type", ",", "output_type", "=", "output_type", ",", "sort_by", "=", "sort_by", ")", "fields", "=", "[", "'ref'", ",", "'title'", ",", "'author'", ",", "'lastRunTime'", ",", "'totalVotes'", "]", "if", "kernels", ":", "if", "csv_display", ":", "self", ".", "print_csv", "(", "kernels", ",", "fields", ")", "else", ":", "self", ".", "print_table", "(", "kernels", ",", "fields", ")", "else", ":", "print", "(", "'No kernels found'", ")" ]
client wrapper for kernels_list, see this function for arguments. Additional arguments are provided here. Parameters ========== csv_display: if True, print comma separated values instead of table
[ "client", "wrapper", "for", "kernels_list", "see", "this", "function", "for", "arguments", ".", "Additional", "arguments", "are", "provided", "here", ".", "Parameters", "==========", "csv_display", ":", "if", "True", "print", "comma", "separated", "values", "instead", "of", "table" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1592-L1632
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_initialize
def kernels_initialize(self, folder): """ create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) resources = [] resource = {'path': 'INSERT_SCRIPT_PATH_HERE'} resources.append(resource) username = self.get_config_value(self.CONFIG_NAME_USER) meta_data = { 'id': username + '/INSERT_KERNEL_SLUG_HERE', 'title': 'INSERT_TITLE_HERE', 'code_file': 'INSERT_CODE_FILE_PATH_HERE', 'language': 'INSERT_LANGUAGE_HERE', 'kernel_type': 'INSERT_KERNEL_TYPE_HERE', 'is_private': 'true', 'enable_gpu': 'false', 'enable_internet': 'false', 'dataset_sources': [], 'competition_sources': [], 'kernel_sources': [], } meta_file = os.path.join(folder, self.KERNEL_METADATA_FILE) with open(meta_file, 'w') as f: json.dump(meta_data, f, indent=2) return meta_file
python
def kernels_initialize(self, folder): """ create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) resources = [] resource = {'path': 'INSERT_SCRIPT_PATH_HERE'} resources.append(resource) username = self.get_config_value(self.CONFIG_NAME_USER) meta_data = { 'id': username + '/INSERT_KERNEL_SLUG_HERE', 'title': 'INSERT_TITLE_HERE', 'code_file': 'INSERT_CODE_FILE_PATH_HERE', 'language': 'INSERT_LANGUAGE_HERE', 'kernel_type': 'INSERT_KERNEL_TYPE_HERE', 'is_private': 'true', 'enable_gpu': 'false', 'enable_internet': 'false', 'dataset_sources': [], 'competition_sources': [], 'kernel_sources': [], } meta_file = os.path.join(folder, self.KERNEL_METADATA_FILE) with open(meta_file, 'w') as f: json.dump(meta_data, f, indent=2) return meta_file
[ "def", "kernels_initialize", "(", "self", ",", "folder", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "raise", "ValueError", "(", "'Invalid folder: '", "+", "folder", ")", "resources", "=", "[", "]", "resource", "=", "{", "'path'", ":", "'INSERT_SCRIPT_PATH_HERE'", "}", "resources", ".", "append", "(", "resource", ")", "username", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_USER", ")", "meta_data", "=", "{", "'id'", ":", "username", "+", "'/INSERT_KERNEL_SLUG_HERE'", ",", "'title'", ":", "'INSERT_TITLE_HERE'", ",", "'code_file'", ":", "'INSERT_CODE_FILE_PATH_HERE'", ",", "'language'", ":", "'INSERT_LANGUAGE_HERE'", ",", "'kernel_type'", ":", "'INSERT_KERNEL_TYPE_HERE'", ",", "'is_private'", ":", "'true'", ",", "'enable_gpu'", ":", "'false'", ",", "'enable_internet'", ":", "'false'", ",", "'dataset_sources'", ":", "[", "]", ",", "'competition_sources'", ":", "[", "]", ",", "'kernel_sources'", ":", "[", "]", ",", "}", "meta_file", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "self", ".", "KERNEL_METADATA_FILE", ")", "with", "open", "(", "meta_file", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "meta_data", ",", "f", ",", "indent", "=", "2", ")", "return", "meta_file" ]
create a new kernel in a specified folder from template, including json metadata that grabs values from the configuration. Parameters ========== folder: the path of the folder
[ "create", "a", "new", "kernel", "in", "a", "specified", "folder", "from", "template", "including", "json", "metadata", "that", "grabs", "values", "from", "the", "configuration", ".", "Parameters", "==========", "folder", ":", "the", "path", "of", "the", "folder" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1634-L1666
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_initialize_cli
def kernels_initialize_cli(self, folder=None): """ client wrapper for kernels_initialize, takes same arguments but sets default folder to be None. If None, defaults to present working directory. Parameters ========== folder: the path of the folder (None defaults to ${PWD}) """ folder = folder or os.getcwd() meta_file = self.kernels_initialize(folder) print('Kernel metadata template written to: ' + meta_file)
python
def kernels_initialize_cli(self, folder=None): """ client wrapper for kernels_initialize, takes same arguments but sets default folder to be None. If None, defaults to present working directory. Parameters ========== folder: the path of the folder (None defaults to ${PWD}) """ folder = folder or os.getcwd() meta_file = self.kernels_initialize(folder) print('Kernel metadata template written to: ' + meta_file)
[ "def", "kernels_initialize_cli", "(", "self", ",", "folder", "=", "None", ")", ":", "folder", "=", "folder", "or", "os", ".", "getcwd", "(", ")", "meta_file", "=", "self", ".", "kernels_initialize", "(", "folder", ")", "print", "(", "'Kernel metadata template written to: '", "+", "meta_file", ")" ]
client wrapper for kernels_initialize, takes same arguments but sets default folder to be None. If None, defaults to present working directory. Parameters ========== folder: the path of the folder (None defaults to ${PWD})
[ "client", "wrapper", "for", "kernels_initialize", "takes", "same", "arguments", "but", "sets", "default", "folder", "to", "be", "None", ".", "If", "None", "defaults", "to", "present", "working", "directory", ".", "Parameters", "==========", "folder", ":", "the", "path", "of", "the", "folder", "(", "None", "defaults", "to", "$", "{", "PWD", "}", ")" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1668-L1678
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_push
def kernels_push(self, folder): """ read the metadata file and kernel files from a notebook, validate both, and use Kernel API to push to Kaggle if all is valid. Parameters ========== folder: the path of the folder """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = os.path.join(folder, self.KERNEL_METADATA_FILE) if not os.path.isfile(meta_file): raise ValueError('Metadata file not found: ' + self.KERNEL_METADATA_FILE) with open(meta_file) as f: meta_data = json.load(f) title = self.get_or_default(meta_data, 'title', None) if title and len(title) < 5: raise ValueError('Title must be at least five characters') code_path = self.get_or_default(meta_data, 'code_file', '') if not code_path: raise ValueError('A source file must be specified in the metadata') code_file = os.path.join(folder, code_path) if not os.path.isfile(code_file): raise ValueError('Source file not found: ' + code_file) slug = meta_data.get('id') id_no = meta_data.get('id_no') if not slug and not id_no: raise ValueError('ID or slug must be specified in the metadata') if slug: self.validate_kernel_string(slug) if '/' in slug: kernel_slug = slug.split('/')[1] else: kernel_slug = slug if title: as_slug = slugify(title) if kernel_slug.lower() != as_slug: print( 'Your kernel title does not resolve to the specified ' 'id. This may result in surprising behavior. We ' 'suggest making your title something that resolves to ' 'the specified id. See %s for more information on ' 'how slugs are determined.' % 'https://en.wikipedia.org/wiki/Clean_URL#Slug') valid_languages = ['python', 'r', 'rmarkdown'] language = self.get_or_default(meta_data, 'language', '') if language not in valid_languages: raise ValueError( 'A valid language must be specified in the metadata. Valid ' 'options are ' + str(valid_languages)) valid_kernel_types = ['script', 'notebook'] kernel_type = self.get_or_default(meta_data, 'kernel_type', '') if kernel_type not in valid_kernel_types: raise ValueError( 'A valid kernel type must be specified in the metadata. Valid ' 'options are ' + str(valid_kernel_types)) if kernel_type == 'notebook' and language == 'rmarkdown': language = 'r' dataset_sources = self.get_or_default(meta_data, 'dataset_sources', []) for source in dataset_sources: self.validate_dataset_string(source) kernel_sources = self.get_or_default(meta_data, 'kernel_sources', []) for source in kernel_sources: self.validate_kernel_string(source) with open(code_file) as f: script_body = f.read() if kernel_type == 'notebook': json_body = json.loads(script_body) if 'cells' in json_body: for cell in json_body['cells']: if 'outputs' in cell and cell['cell_type'] == 'code': cell['outputs'] = [] script_body = json.dumps(json_body) kernel_push_request = KernelPushRequest( id=id_no, slug=slug, new_title=self.get_or_default(meta_data, 'title', None), text=script_body, language=language, kernel_type=kernel_type, is_private=self.get_or_default(meta_data, 'is_private', None), enable_gpu=self.get_or_default(meta_data, 'enable_gpu', None), enable_internet=self.get_or_default(meta_data, 'enable_internet', None), dataset_data_sources=dataset_sources, competition_data_sources=self.get_or_default( meta_data, 'competition_sources', []), kernel_data_sources=kernel_sources, category_ids=self.get_or_default(meta_data, 'keywords', [])) result = KernelPushResponse( self.process_response( self.kernel_push_with_http_info( kernel_push_request=kernel_push_request))) return result
python
def kernels_push(self, folder): """ read the metadata file and kernel files from a notebook, validate both, and use Kernel API to push to Kaggle if all is valid. Parameters ========== folder: the path of the folder """ if not os.path.isdir(folder): raise ValueError('Invalid folder: ' + folder) meta_file = os.path.join(folder, self.KERNEL_METADATA_FILE) if not os.path.isfile(meta_file): raise ValueError('Metadata file not found: ' + self.KERNEL_METADATA_FILE) with open(meta_file) as f: meta_data = json.load(f) title = self.get_or_default(meta_data, 'title', None) if title and len(title) < 5: raise ValueError('Title must be at least five characters') code_path = self.get_or_default(meta_data, 'code_file', '') if not code_path: raise ValueError('A source file must be specified in the metadata') code_file = os.path.join(folder, code_path) if not os.path.isfile(code_file): raise ValueError('Source file not found: ' + code_file) slug = meta_data.get('id') id_no = meta_data.get('id_no') if not slug and not id_no: raise ValueError('ID or slug must be specified in the metadata') if slug: self.validate_kernel_string(slug) if '/' in slug: kernel_slug = slug.split('/')[1] else: kernel_slug = slug if title: as_slug = slugify(title) if kernel_slug.lower() != as_slug: print( 'Your kernel title does not resolve to the specified ' 'id. This may result in surprising behavior. We ' 'suggest making your title something that resolves to ' 'the specified id. See %s for more information on ' 'how slugs are determined.' % 'https://en.wikipedia.org/wiki/Clean_URL#Slug') valid_languages = ['python', 'r', 'rmarkdown'] language = self.get_or_default(meta_data, 'language', '') if language not in valid_languages: raise ValueError( 'A valid language must be specified in the metadata. Valid ' 'options are ' + str(valid_languages)) valid_kernel_types = ['script', 'notebook'] kernel_type = self.get_or_default(meta_data, 'kernel_type', '') if kernel_type not in valid_kernel_types: raise ValueError( 'A valid kernel type must be specified in the metadata. Valid ' 'options are ' + str(valid_kernel_types)) if kernel_type == 'notebook' and language == 'rmarkdown': language = 'r' dataset_sources = self.get_or_default(meta_data, 'dataset_sources', []) for source in dataset_sources: self.validate_dataset_string(source) kernel_sources = self.get_or_default(meta_data, 'kernel_sources', []) for source in kernel_sources: self.validate_kernel_string(source) with open(code_file) as f: script_body = f.read() if kernel_type == 'notebook': json_body = json.loads(script_body) if 'cells' in json_body: for cell in json_body['cells']: if 'outputs' in cell and cell['cell_type'] == 'code': cell['outputs'] = [] script_body = json.dumps(json_body) kernel_push_request = KernelPushRequest( id=id_no, slug=slug, new_title=self.get_or_default(meta_data, 'title', None), text=script_body, language=language, kernel_type=kernel_type, is_private=self.get_or_default(meta_data, 'is_private', None), enable_gpu=self.get_or_default(meta_data, 'enable_gpu', None), enable_internet=self.get_or_default(meta_data, 'enable_internet', None), dataset_data_sources=dataset_sources, competition_data_sources=self.get_or_default( meta_data, 'competition_sources', []), kernel_data_sources=kernel_sources, category_ids=self.get_or_default(meta_data, 'keywords', [])) result = KernelPushResponse( self.process_response( self.kernel_push_with_http_info( kernel_push_request=kernel_push_request))) return result
[ "def", "kernels_push", "(", "self", ",", "folder", ")", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "raise", "ValueError", "(", "'Invalid folder: '", "+", "folder", ")", "meta_file", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "self", ".", "KERNEL_METADATA_FILE", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "meta_file", ")", ":", "raise", "ValueError", "(", "'Metadata file not found: '", "+", "self", ".", "KERNEL_METADATA_FILE", ")", "with", "open", "(", "meta_file", ")", "as", "f", ":", "meta_data", "=", "json", ".", "load", "(", "f", ")", "title", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'title'", ",", "None", ")", "if", "title", "and", "len", "(", "title", ")", "<", "5", ":", "raise", "ValueError", "(", "'Title must be at least five characters'", ")", "code_path", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'code_file'", ",", "''", ")", "if", "not", "code_path", ":", "raise", "ValueError", "(", "'A source file must be specified in the metadata'", ")", "code_file", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "code_path", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "code_file", ")", ":", "raise", "ValueError", "(", "'Source file not found: '", "+", "code_file", ")", "slug", "=", "meta_data", ".", "get", "(", "'id'", ")", "id_no", "=", "meta_data", ".", "get", "(", "'id_no'", ")", "if", "not", "slug", "and", "not", "id_no", ":", "raise", "ValueError", "(", "'ID or slug must be specified in the metadata'", ")", "if", "slug", ":", "self", ".", "validate_kernel_string", "(", "slug", ")", "if", "'/'", "in", "slug", ":", "kernel_slug", "=", "slug", ".", "split", "(", "'/'", ")", "[", "1", "]", "else", ":", "kernel_slug", "=", "slug", "if", "title", ":", "as_slug", "=", "slugify", "(", "title", ")", "if", "kernel_slug", ".", "lower", "(", ")", "!=", "as_slug", ":", "print", "(", "'Your kernel title does not resolve to the specified '", "'id. This may result in surprising behavior. We '", "'suggest making your title something that resolves to '", "'the specified id. See %s for more information on '", "'how slugs are determined.'", "%", "'https://en.wikipedia.org/wiki/Clean_URL#Slug'", ")", "valid_languages", "=", "[", "'python'", ",", "'r'", ",", "'rmarkdown'", "]", "language", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'language'", ",", "''", ")", "if", "language", "not", "in", "valid_languages", ":", "raise", "ValueError", "(", "'A valid language must be specified in the metadata. Valid '", "'options are '", "+", "str", "(", "valid_languages", ")", ")", "valid_kernel_types", "=", "[", "'script'", ",", "'notebook'", "]", "kernel_type", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'kernel_type'", ",", "''", ")", "if", "kernel_type", "not", "in", "valid_kernel_types", ":", "raise", "ValueError", "(", "'A valid kernel type must be specified in the metadata. Valid '", "'options are '", "+", "str", "(", "valid_kernel_types", ")", ")", "if", "kernel_type", "==", "'notebook'", "and", "language", "==", "'rmarkdown'", ":", "language", "=", "'r'", "dataset_sources", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'dataset_sources'", ",", "[", "]", ")", "for", "source", "in", "dataset_sources", ":", "self", ".", "validate_dataset_string", "(", "source", ")", "kernel_sources", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'kernel_sources'", ",", "[", "]", ")", "for", "source", "in", "kernel_sources", ":", "self", ".", "validate_kernel_string", "(", "source", ")", "with", "open", "(", "code_file", ")", "as", "f", ":", "script_body", "=", "f", ".", "read", "(", ")", "if", "kernel_type", "==", "'notebook'", ":", "json_body", "=", "json", ".", "loads", "(", "script_body", ")", "if", "'cells'", "in", "json_body", ":", "for", "cell", "in", "json_body", "[", "'cells'", "]", ":", "if", "'outputs'", "in", "cell", "and", "cell", "[", "'cell_type'", "]", "==", "'code'", ":", "cell", "[", "'outputs'", "]", "=", "[", "]", "script_body", "=", "json", ".", "dumps", "(", "json_body", ")", "kernel_push_request", "=", "KernelPushRequest", "(", "id", "=", "id_no", ",", "slug", "=", "slug", ",", "new_title", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'title'", ",", "None", ")", ",", "text", "=", "script_body", ",", "language", "=", "language", ",", "kernel_type", "=", "kernel_type", ",", "is_private", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'is_private'", ",", "None", ")", ",", "enable_gpu", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'enable_gpu'", ",", "None", ")", ",", "enable_internet", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'enable_internet'", ",", "None", ")", ",", "dataset_data_sources", "=", "dataset_sources", ",", "competition_data_sources", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'competition_sources'", ",", "[", "]", ")", ",", "kernel_data_sources", "=", "kernel_sources", ",", "category_ids", "=", "self", ".", "get_or_default", "(", "meta_data", ",", "'keywords'", ",", "[", "]", ")", ")", "result", "=", "KernelPushResponse", "(", "self", ".", "process_response", "(", "self", ".", "kernel_push_with_http_info", "(", "kernel_push_request", "=", "kernel_push_request", ")", ")", ")", "return", "result" ]
read the metadata file and kernel files from a notebook, validate both, and use Kernel API to push to Kaggle if all is valid. Parameters ========== folder: the path of the folder
[ "read", "the", "metadata", "file", "and", "kernel", "files", "from", "a", "notebook", "validate", "both", "and", "use", "Kernel", "API", "to", "push", "to", "Kaggle", "if", "all", "is", "valid", ".", "Parameters", "==========", "folder", ":", "the", "path", "of", "the", "folder" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1680-L1788
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_push_cli
def kernels_push_cli(self, folder): """ client wrapper for kernels_push, with same arguments. """ folder = folder or os.getcwd() result = self.kernels_push(folder) if result is None: print('Kernel push error: see previous output') elif not result.error: if result.invalidTags: print( 'The following are not valid tags and could not be added ' 'to the kernel: ' + str(result.invalidTags)) if result.invalidDatasetSources: print( 'The following are not valid dataset sources and could not ' 'be added to the kernel: ' + str(result.invalidDatasetSources)) if result.invalidCompetitionSources: print( 'The following are not valid competition sources and could ' 'not be added to the kernel: ' + str(result.invalidCompetitionSources)) if result.invalidKernelSources: print( 'The following are not valid kernel sources and could not ' 'be added to the kernel: ' + str(result.invalidKernelSources)) if result.versionNumber: print('Kernel version %s successfully pushed. Please check ' 'progress at %s' % (result.versionNumber, result.url)) else: # Shouldn't happen but didn't test exhaustively print('Kernel version successfully pushed. Please check ' 'progress at %s' % result.url) else: print('Kernel push error: ' + result.error)
python
def kernels_push_cli(self, folder): """ client wrapper for kernels_push, with same arguments. """ folder = folder or os.getcwd() result = self.kernels_push(folder) if result is None: print('Kernel push error: see previous output') elif not result.error: if result.invalidTags: print( 'The following are not valid tags and could not be added ' 'to the kernel: ' + str(result.invalidTags)) if result.invalidDatasetSources: print( 'The following are not valid dataset sources and could not ' 'be added to the kernel: ' + str(result.invalidDatasetSources)) if result.invalidCompetitionSources: print( 'The following are not valid competition sources and could ' 'not be added to the kernel: ' + str(result.invalidCompetitionSources)) if result.invalidKernelSources: print( 'The following are not valid kernel sources and could not ' 'be added to the kernel: ' + str(result.invalidKernelSources)) if result.versionNumber: print('Kernel version %s successfully pushed. Please check ' 'progress at %s' % (result.versionNumber, result.url)) else: # Shouldn't happen but didn't test exhaustively print('Kernel version successfully pushed. Please check ' 'progress at %s' % result.url) else: print('Kernel push error: ' + result.error)
[ "def", "kernels_push_cli", "(", "self", ",", "folder", ")", ":", "folder", "=", "folder", "or", "os", ".", "getcwd", "(", ")", "result", "=", "self", ".", "kernels_push", "(", "folder", ")", "if", "result", "is", "None", ":", "print", "(", "'Kernel push error: see previous output'", ")", "elif", "not", "result", ".", "error", ":", "if", "result", ".", "invalidTags", ":", "print", "(", "'The following are not valid tags and could not be added '", "'to the kernel: '", "+", "str", "(", "result", ".", "invalidTags", ")", ")", "if", "result", ".", "invalidDatasetSources", ":", "print", "(", "'The following are not valid dataset sources and could not '", "'be added to the kernel: '", "+", "str", "(", "result", ".", "invalidDatasetSources", ")", ")", "if", "result", ".", "invalidCompetitionSources", ":", "print", "(", "'The following are not valid competition sources and could '", "'not be added to the kernel: '", "+", "str", "(", "result", ".", "invalidCompetitionSources", ")", ")", "if", "result", ".", "invalidKernelSources", ":", "print", "(", "'The following are not valid kernel sources and could not '", "'be added to the kernel: '", "+", "str", "(", "result", ".", "invalidKernelSources", ")", ")", "if", "result", ".", "versionNumber", ":", "print", "(", "'Kernel version %s successfully pushed. Please check '", "'progress at %s'", "%", "(", "result", ".", "versionNumber", ",", "result", ".", "url", ")", ")", "else", ":", "# Shouldn't happen but didn't test exhaustively", "print", "(", "'Kernel version successfully pushed. Please check '", "'progress at %s'", "%", "result", ".", "url", ")", "else", ":", "print", "(", "'Kernel push error: '", "+", "result", ".", "error", ")" ]
client wrapper for kernels_push, with same arguments.
[ "client", "wrapper", "for", "kernels_push", "with", "same", "arguments", "." ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1790-L1827
train
Kaggle/kaggle-api
kaggle/api/kaggle_api_extended.py
KaggleApi.kernels_pull
def kernels_pull(self, kernel, path, metadata=False, quiet=True): """ pull a kernel, including a metadata file (if metadata is True) and associated files to a specified path. Parameters ========== kernel: the kernel to pull path: the path to pull files to on the filesystem metadata: if True, also pull metadata quiet: suppress verbosity (default is True) """ existing_metadata = None if kernel is None: if path is None: existing_metadata_path = os.path.join( os.getcwd(), self.KERNEL_METADATA_FILE) else: existing_metadata_path = os.path.join( path, self.KERNEL_METADATA_FILE) if os.path.exists(existing_metadata_path): with open(existing_metadata_path) as f: existing_metadata = json.load(f) kernel = existing_metadata['id'] if 'INSERT_KERNEL_SLUG_HERE' in kernel: raise ValueError('A kernel must be specified') else: print('Using kernel ' + kernel) if '/' in kernel: self.validate_kernel_string(kernel) kernel_url_list = kernel.split('/') owner_slug = kernel_url_list[0] kernel_slug = kernel_url_list[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) kernel_slug = kernel if path is None: effective_path = self.get_default_download_dir( 'kernels', owner_slug, kernel_slug) else: effective_path = path if not os.path.exists(effective_path): os.makedirs(effective_path) response = self.process_response( self.kernel_pull_with_http_info(owner_slug, kernel_slug)) blob = response['blob'] if os.path.isfile(effective_path): effective_dir = os.path.dirname(effective_path) else: effective_dir = effective_path metadata_path = os.path.join(effective_dir, self.KERNEL_METADATA_FILE) if not os.path.isfile(effective_path): language = blob['language'].lower() kernel_type = blob['kernelType'].lower() file_name = None if existing_metadata: file_name = existing_metadata['code_file'] elif os.path.isfile(metadata_path): with open(metadata_path) as f: file_name = json.load(f)['code_file'] if not file_name or file_name == "INSERT_CODE_FILE_PATH_HERE": extension = None if kernel_type == 'script': if language == 'python': extension = '.py' elif language == 'r': extension = '.R' elif language == 'rmarkdown': extension = '.Rmd' elif language == 'sqlite': extension = '.sql' elif language == 'julia': extension = '.jl' elif kernel_type == 'notebook': if language == 'python': extension = '.ipynb' elif language == 'r': extension = '.irnb' elif language == 'julia': extension = '.ijlnb' file_name = blob['slug'] + extension if file_name is None: print( 'Unknown language %s + kernel type %s - please report this ' 'on the kaggle-api github issues' % (language, kernel_type)) print( 'Saving as a python file, even though this may not be the ' 'correct language') file_name = 'script.py' script_path = os.path.join(effective_path, file_name) else: script_path = effective_path file_name = os.path.basename(effective_path) with open(script_path, 'w') as f: f.write(blob['source']) if metadata: data = {} server_metadata = response['metadata'] data['id'] = server_metadata['ref'] data['id_no'] = server_metadata['id'] data['title'] = server_metadata['title'] data['code_file'] = file_name data['language'] = server_metadata['language'] data['kernel_type'] = server_metadata['kernelType'] self.set_if_present(server_metadata, 'isPrivate', data, 'is_private') self.set_if_present(server_metadata, 'enableGpu', data, 'enable_gpu') self.set_if_present(server_metadata, 'enableInternet', data, 'enable_internet') self.set_if_present(server_metadata, 'categoryIds', data, 'keywords') self.set_if_present(server_metadata, 'datasetDataSources', data, 'dataset_sources') self.set_if_present(server_metadata, 'kernelDataSources', data, 'kernel_sources') self.set_if_present(server_metadata, 'competitionDataSources', data, 'competition_sources') with open(metadata_path, 'w') as f: json.dump(data, f, indent=2) return effective_dir else: return script_path
python
def kernels_pull(self, kernel, path, metadata=False, quiet=True): """ pull a kernel, including a metadata file (if metadata is True) and associated files to a specified path. Parameters ========== kernel: the kernel to pull path: the path to pull files to on the filesystem metadata: if True, also pull metadata quiet: suppress verbosity (default is True) """ existing_metadata = None if kernel is None: if path is None: existing_metadata_path = os.path.join( os.getcwd(), self.KERNEL_METADATA_FILE) else: existing_metadata_path = os.path.join( path, self.KERNEL_METADATA_FILE) if os.path.exists(existing_metadata_path): with open(existing_metadata_path) as f: existing_metadata = json.load(f) kernel = existing_metadata['id'] if 'INSERT_KERNEL_SLUG_HERE' in kernel: raise ValueError('A kernel must be specified') else: print('Using kernel ' + kernel) if '/' in kernel: self.validate_kernel_string(kernel) kernel_url_list = kernel.split('/') owner_slug = kernel_url_list[0] kernel_slug = kernel_url_list[1] else: owner_slug = self.get_config_value(self.CONFIG_NAME_USER) kernel_slug = kernel if path is None: effective_path = self.get_default_download_dir( 'kernels', owner_slug, kernel_slug) else: effective_path = path if not os.path.exists(effective_path): os.makedirs(effective_path) response = self.process_response( self.kernel_pull_with_http_info(owner_slug, kernel_slug)) blob = response['blob'] if os.path.isfile(effective_path): effective_dir = os.path.dirname(effective_path) else: effective_dir = effective_path metadata_path = os.path.join(effective_dir, self.KERNEL_METADATA_FILE) if not os.path.isfile(effective_path): language = blob['language'].lower() kernel_type = blob['kernelType'].lower() file_name = None if existing_metadata: file_name = existing_metadata['code_file'] elif os.path.isfile(metadata_path): with open(metadata_path) as f: file_name = json.load(f)['code_file'] if not file_name or file_name == "INSERT_CODE_FILE_PATH_HERE": extension = None if kernel_type == 'script': if language == 'python': extension = '.py' elif language == 'r': extension = '.R' elif language == 'rmarkdown': extension = '.Rmd' elif language == 'sqlite': extension = '.sql' elif language == 'julia': extension = '.jl' elif kernel_type == 'notebook': if language == 'python': extension = '.ipynb' elif language == 'r': extension = '.irnb' elif language == 'julia': extension = '.ijlnb' file_name = blob['slug'] + extension if file_name is None: print( 'Unknown language %s + kernel type %s - please report this ' 'on the kaggle-api github issues' % (language, kernel_type)) print( 'Saving as a python file, even though this may not be the ' 'correct language') file_name = 'script.py' script_path = os.path.join(effective_path, file_name) else: script_path = effective_path file_name = os.path.basename(effective_path) with open(script_path, 'w') as f: f.write(blob['source']) if metadata: data = {} server_metadata = response['metadata'] data['id'] = server_metadata['ref'] data['id_no'] = server_metadata['id'] data['title'] = server_metadata['title'] data['code_file'] = file_name data['language'] = server_metadata['language'] data['kernel_type'] = server_metadata['kernelType'] self.set_if_present(server_metadata, 'isPrivate', data, 'is_private') self.set_if_present(server_metadata, 'enableGpu', data, 'enable_gpu') self.set_if_present(server_metadata, 'enableInternet', data, 'enable_internet') self.set_if_present(server_metadata, 'categoryIds', data, 'keywords') self.set_if_present(server_metadata, 'datasetDataSources', data, 'dataset_sources') self.set_if_present(server_metadata, 'kernelDataSources', data, 'kernel_sources') self.set_if_present(server_metadata, 'competitionDataSources', data, 'competition_sources') with open(metadata_path, 'w') as f: json.dump(data, f, indent=2) return effective_dir else: return script_path
[ "def", "kernels_pull", "(", "self", ",", "kernel", ",", "path", ",", "metadata", "=", "False", ",", "quiet", "=", "True", ")", ":", "existing_metadata", "=", "None", "if", "kernel", "is", "None", ":", "if", "path", "is", "None", ":", "existing_metadata_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "self", ".", "KERNEL_METADATA_FILE", ")", "else", ":", "existing_metadata_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "self", ".", "KERNEL_METADATA_FILE", ")", "if", "os", ".", "path", ".", "exists", "(", "existing_metadata_path", ")", ":", "with", "open", "(", "existing_metadata_path", ")", "as", "f", ":", "existing_metadata", "=", "json", ".", "load", "(", "f", ")", "kernel", "=", "existing_metadata", "[", "'id'", "]", "if", "'INSERT_KERNEL_SLUG_HERE'", "in", "kernel", ":", "raise", "ValueError", "(", "'A kernel must be specified'", ")", "else", ":", "print", "(", "'Using kernel '", "+", "kernel", ")", "if", "'/'", "in", "kernel", ":", "self", ".", "validate_kernel_string", "(", "kernel", ")", "kernel_url_list", "=", "kernel", ".", "split", "(", "'/'", ")", "owner_slug", "=", "kernel_url_list", "[", "0", "]", "kernel_slug", "=", "kernel_url_list", "[", "1", "]", "else", ":", "owner_slug", "=", "self", ".", "get_config_value", "(", "self", ".", "CONFIG_NAME_USER", ")", "kernel_slug", "=", "kernel", "if", "path", "is", "None", ":", "effective_path", "=", "self", ".", "get_default_download_dir", "(", "'kernels'", ",", "owner_slug", ",", "kernel_slug", ")", "else", ":", "effective_path", "=", "path", "if", "not", "os", ".", "path", ".", "exists", "(", "effective_path", ")", ":", "os", ".", "makedirs", "(", "effective_path", ")", "response", "=", "self", ".", "process_response", "(", "self", ".", "kernel_pull_with_http_info", "(", "owner_slug", ",", "kernel_slug", ")", ")", "blob", "=", "response", "[", "'blob'", "]", "if", "os", ".", "path", ".", "isfile", "(", "effective_path", ")", ":", "effective_dir", "=", "os", ".", "path", ".", "dirname", "(", "effective_path", ")", "else", ":", "effective_dir", "=", "effective_path", "metadata_path", "=", "os", ".", "path", ".", "join", "(", "effective_dir", ",", "self", ".", "KERNEL_METADATA_FILE", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "effective_path", ")", ":", "language", "=", "blob", "[", "'language'", "]", ".", "lower", "(", ")", "kernel_type", "=", "blob", "[", "'kernelType'", "]", ".", "lower", "(", ")", "file_name", "=", "None", "if", "existing_metadata", ":", "file_name", "=", "existing_metadata", "[", "'code_file'", "]", "elif", "os", ".", "path", ".", "isfile", "(", "metadata_path", ")", ":", "with", "open", "(", "metadata_path", ")", "as", "f", ":", "file_name", "=", "json", ".", "load", "(", "f", ")", "[", "'code_file'", "]", "if", "not", "file_name", "or", "file_name", "==", "\"INSERT_CODE_FILE_PATH_HERE\"", ":", "extension", "=", "None", "if", "kernel_type", "==", "'script'", ":", "if", "language", "==", "'python'", ":", "extension", "=", "'.py'", "elif", "language", "==", "'r'", ":", "extension", "=", "'.R'", "elif", "language", "==", "'rmarkdown'", ":", "extension", "=", "'.Rmd'", "elif", "language", "==", "'sqlite'", ":", "extension", "=", "'.sql'", "elif", "language", "==", "'julia'", ":", "extension", "=", "'.jl'", "elif", "kernel_type", "==", "'notebook'", ":", "if", "language", "==", "'python'", ":", "extension", "=", "'.ipynb'", "elif", "language", "==", "'r'", ":", "extension", "=", "'.irnb'", "elif", "language", "==", "'julia'", ":", "extension", "=", "'.ijlnb'", "file_name", "=", "blob", "[", "'slug'", "]", "+", "extension", "if", "file_name", "is", "None", ":", "print", "(", "'Unknown language %s + kernel type %s - please report this '", "'on the kaggle-api github issues'", "%", "(", "language", ",", "kernel_type", ")", ")", "print", "(", "'Saving as a python file, even though this may not be the '", "'correct language'", ")", "file_name", "=", "'script.py'", "script_path", "=", "os", ".", "path", ".", "join", "(", "effective_path", ",", "file_name", ")", "else", ":", "script_path", "=", "effective_path", "file_name", "=", "os", ".", "path", ".", "basename", "(", "effective_path", ")", "with", "open", "(", "script_path", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "blob", "[", "'source'", "]", ")", "if", "metadata", ":", "data", "=", "{", "}", "server_metadata", "=", "response", "[", "'metadata'", "]", "data", "[", "'id'", "]", "=", "server_metadata", "[", "'ref'", "]", "data", "[", "'id_no'", "]", "=", "server_metadata", "[", "'id'", "]", "data", "[", "'title'", "]", "=", "server_metadata", "[", "'title'", "]", "data", "[", "'code_file'", "]", "=", "file_name", "data", "[", "'language'", "]", "=", "server_metadata", "[", "'language'", "]", "data", "[", "'kernel_type'", "]", "=", "server_metadata", "[", "'kernelType'", "]", "self", ".", "set_if_present", "(", "server_metadata", ",", "'isPrivate'", ",", "data", ",", "'is_private'", ")", "self", ".", "set_if_present", "(", "server_metadata", ",", "'enableGpu'", ",", "data", ",", "'enable_gpu'", ")", "self", ".", "set_if_present", "(", "server_metadata", ",", "'enableInternet'", ",", "data", ",", "'enable_internet'", ")", "self", ".", "set_if_present", "(", "server_metadata", ",", "'categoryIds'", ",", "data", ",", "'keywords'", ")", "self", ".", "set_if_present", "(", "server_metadata", ",", "'datasetDataSources'", ",", "data", ",", "'dataset_sources'", ")", "self", ".", "set_if_present", "(", "server_metadata", ",", "'kernelDataSources'", ",", "data", ",", "'kernel_sources'", ")", "self", ".", "set_if_present", "(", "server_metadata", ",", "'competitionDataSources'", ",", "data", ",", "'competition_sources'", ")", "with", "open", "(", "metadata_path", ",", "'w'", ")", "as", "f", ":", "json", ".", "dump", "(", "data", ",", "f", ",", "indent", "=", "2", ")", "return", "effective_dir", "else", ":", "return", "script_path" ]
pull a kernel, including a metadata file (if metadata is True) and associated files to a specified path. Parameters ========== kernel: the kernel to pull path: the path to pull files to on the filesystem metadata: if True, also pull metadata quiet: suppress verbosity (default is True)
[ "pull", "a", "kernel", "including", "a", "metadata", "file", "(", "if", "metadata", "is", "True", ")", "and", "associated", "files", "to", "a", "specified", "path", ".", "Parameters", "==========", "kernel", ":", "the", "kernel", "to", "pull", "path", ":", "the", "path", "to", "pull", "files", "to", "on", "the", "filesystem", "metadata", ":", "if", "True", "also", "pull", "metadata", "quiet", ":", "suppress", "verbosity", "(", "default", "is", "True", ")" ]
65f14b1386470c5784d4753e491478e7537660d9
https://github.com/Kaggle/kaggle-api/blob/65f14b1386470c5784d4753e491478e7537660d9/kaggle/api/kaggle_api_extended.py#L1829-L1963
train