repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
Yubico/python-pyhsm
pyhsm/ksm/yubikey_ksm.py
YHSM_KSMRequestHandler.decrypt_yubikey_otp
def decrypt_yubikey_otp(self, from_key): """ Try to decrypt a YubiKey OTP. Returns a string starting with either 'OK' or 'ERR' : 'OK counter=ab12 low=dd34 high=2a use=0a' 'ERR Unknown public_id' on YubiHSM errors (or bad OTP), only 'ERR' is returned. """ if not re.match(valid_input_from_key, from_key): self.log_error("IN: %s, Invalid OTP" % (from_key)) if self.stats_url: stats['invalid'] += 1 return "ERR Invalid OTP" public_id, _otp = pyhsm.yubikey.split_id_otp(from_key) try: aead = self.aead_backend.load_aead(public_id) except Exception as e: self.log_error(str(e)) if self.stats_url: stats['no_aead'] += 1 return "ERR Unknown public_id" try: res = pyhsm.yubikey.validate_yubikey_with_aead( self.hsm, from_key, aead, aead.key_handle) # XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded # XXX fix use vs session counter confusion val_res = "OK counter=%04x low=%04x high=%02x use=%02x" % \ (res.use_ctr, res.ts_low, res.ts_high, res.session_ctr) if self.stats_url: stats['ok'] += 1 except pyhsm.exception.YHSM_Error as e: self.log_error ("IN: %s, Validate FAILED: %s" % (from_key, str(e))) val_res = "ERR" if self.stats_url: stats['err'] += 1 self.log_message("SUCCESS OTP %s PT hsm %s", from_key, val_res) return val_res
python
def decrypt_yubikey_otp(self, from_key): """ Try to decrypt a YubiKey OTP. Returns a string starting with either 'OK' or 'ERR' : 'OK counter=ab12 low=dd34 high=2a use=0a' 'ERR Unknown public_id' on YubiHSM errors (or bad OTP), only 'ERR' is returned. """ if not re.match(valid_input_from_key, from_key): self.log_error("IN: %s, Invalid OTP" % (from_key)) if self.stats_url: stats['invalid'] += 1 return "ERR Invalid OTP" public_id, _otp = pyhsm.yubikey.split_id_otp(from_key) try: aead = self.aead_backend.load_aead(public_id) except Exception as e: self.log_error(str(e)) if self.stats_url: stats['no_aead'] += 1 return "ERR Unknown public_id" try: res = pyhsm.yubikey.validate_yubikey_with_aead( self.hsm, from_key, aead, aead.key_handle) # XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded # XXX fix use vs session counter confusion val_res = "OK counter=%04x low=%04x high=%02x use=%02x" % \ (res.use_ctr, res.ts_low, res.ts_high, res.session_ctr) if self.stats_url: stats['ok'] += 1 except pyhsm.exception.YHSM_Error as e: self.log_error ("IN: %s, Validate FAILED: %s" % (from_key, str(e))) val_res = "ERR" if self.stats_url: stats['err'] += 1 self.log_message("SUCCESS OTP %s PT hsm %s", from_key, val_res) return val_res
[ "def", "decrypt_yubikey_otp", "(", "self", ",", "from_key", ")", ":", "if", "not", "re", ".", "match", "(", "valid_input_from_key", ",", "from_key", ")", ":", "self", ".", "log_error", "(", "\"IN: %s, Invalid OTP\"", "%", "(", "from_key", ")", ")", "if", "self", ".", "stats_url", ":", "stats", "[", "'invalid'", "]", "+=", "1", "return", "\"ERR Invalid OTP\"", "public_id", ",", "_otp", "=", "pyhsm", ".", "yubikey", ".", "split_id_otp", "(", "from_key", ")", "try", ":", "aead", "=", "self", ".", "aead_backend", ".", "load_aead", "(", "public_id", ")", "except", "Exception", "as", "e", ":", "self", ".", "log_error", "(", "str", "(", "e", ")", ")", "if", "self", ".", "stats_url", ":", "stats", "[", "'no_aead'", "]", "+=", "1", "return", "\"ERR Unknown public_id\"", "try", ":", "res", "=", "pyhsm", ".", "yubikey", ".", "validate_yubikey_with_aead", "(", "self", ".", "hsm", ",", "from_key", ",", "aead", ",", "aead", ".", "key_handle", ")", "# XXX double-check public_id in res, in case BaseHTTPServer suddenly becomes multi-threaded", "# XXX fix use vs session counter confusion", "val_res", "=", "\"OK counter=%04x low=%04x high=%02x use=%02x\"", "%", "(", "res", ".", "use_ctr", ",", "res", ".", "ts_low", ",", "res", ".", "ts_high", ",", "res", ".", "session_ctr", ")", "if", "self", ".", "stats_url", ":", "stats", "[", "'ok'", "]", "+=", "1", "except", "pyhsm", ".", "exception", ".", "YHSM_Error", "as", "e", ":", "self", ".", "log_error", "(", "\"IN: %s, Validate FAILED: %s\"", "%", "(", "from_key", ",", "str", "(", "e", ")", ")", ")", "val_res", "=", "\"ERR\"", "if", "self", ".", "stats_url", ":", "stats", "[", "'err'", "]", "+=", "1", "self", ".", "log_message", "(", "\"SUCCESS OTP %s PT hsm %s\"", ",", "from_key", ",", "val_res", ")", "return", "val_res" ]
Try to decrypt a YubiKey OTP. Returns a string starting with either 'OK' or 'ERR' : 'OK counter=ab12 low=dd34 high=2a use=0a' 'ERR Unknown public_id' on YubiHSM errors (or bad OTP), only 'ERR' is returned.
[ "Try", "to", "decrypt", "a", "YubiKey", "OTP", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L118-L162
train
Yubico/python-pyhsm
pyhsm/ksm/yubikey_ksm.py
YHSM_KSMRequestHandler.my_address_string
def my_address_string(self): """ For logging client host without resolving. """ addr = getattr(self, 'client_address', ('', None))[0] # If listed in proxy_ips, use the X-Forwarded-For header, if present. if addr in self.proxy_ips: return self.headers.getheader('x-forwarded-for', addr) return addr
python
def my_address_string(self): """ For logging client host without resolving. """ addr = getattr(self, 'client_address', ('', None))[0] # If listed in proxy_ips, use the X-Forwarded-For header, if present. if addr in self.proxy_ips: return self.headers.getheader('x-forwarded-for', addr) return addr
[ "def", "my_address_string", "(", "self", ")", ":", "addr", "=", "getattr", "(", "self", ",", "'client_address'", ",", "(", "''", ",", "None", ")", ")", "[", "0", "]", "# If listed in proxy_ips, use the X-Forwarded-For header, if present.", "if", "addr", "in", "self", ".", "proxy_ips", ":", "return", "self", ".", "headers", ".", "getheader", "(", "'x-forwarded-for'", ",", "addr", ")", "return", "addr" ]
For logging client host without resolving.
[ "For", "logging", "client", "host", "without", "resolving", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L174-L181
train
Yubico/python-pyhsm
pyhsm/ksm/yubikey_ksm.py
SQLBackend.load_aead
def load_aead(self, public_id): """ Loads AEAD from the specified database. """ connection = self.engine.connect() trans = connection.begin() try: s = sqlalchemy.select([self.aead_table]).where( (self.aead_table.c.public_id == public_id) & self.aead_table.c.keyhandle.in_([kh[1] for kh in self.key_handles])) result = connection.execute(s) for row in result: kh_int = row['keyhandle'] aead = pyhsm.aead_cmd.YHSM_GeneratedAEAD(None, kh_int, '') aead.data = row['aead'] aead.nonce = row['nonce'] return aead except Exception as e: trans.rollback() raise Exception("No AEAD in DB for public_id %s (%s)" % (public_id, str(e))) finally: connection.close()
python
def load_aead(self, public_id): """ Loads AEAD from the specified database. """ connection = self.engine.connect() trans = connection.begin() try: s = sqlalchemy.select([self.aead_table]).where( (self.aead_table.c.public_id == public_id) & self.aead_table.c.keyhandle.in_([kh[1] for kh in self.key_handles])) result = connection.execute(s) for row in result: kh_int = row['keyhandle'] aead = pyhsm.aead_cmd.YHSM_GeneratedAEAD(None, kh_int, '') aead.data = row['aead'] aead.nonce = row['nonce'] return aead except Exception as e: trans.rollback() raise Exception("No AEAD in DB for public_id %s (%s)" % (public_id, str(e))) finally: connection.close()
[ "def", "load_aead", "(", "self", ",", "public_id", ")", ":", "connection", "=", "self", ".", "engine", ".", "connect", "(", ")", "trans", "=", "connection", ".", "begin", "(", ")", "try", ":", "s", "=", "sqlalchemy", ".", "select", "(", "[", "self", ".", "aead_table", "]", ")", ".", "where", "(", "(", "self", ".", "aead_table", ".", "c", ".", "public_id", "==", "public_id", ")", "&", "self", ".", "aead_table", ".", "c", ".", "keyhandle", ".", "in_", "(", "[", "kh", "[", "1", "]", "for", "kh", "in", "self", ".", "key_handles", "]", ")", ")", "result", "=", "connection", ".", "execute", "(", "s", ")", "for", "row", "in", "result", ":", "kh_int", "=", "row", "[", "'keyhandle'", "]", "aead", "=", "pyhsm", ".", "aead_cmd", ".", "YHSM_GeneratedAEAD", "(", "None", ",", "kh_int", ",", "''", ")", "aead", ".", "data", "=", "row", "[", "'aead'", "]", "aead", ".", "nonce", "=", "row", "[", "'nonce'", "]", "return", "aead", "except", "Exception", "as", "e", ":", "trans", ".", "rollback", "(", ")", "raise", "Exception", "(", "\"No AEAD in DB for public_id %s (%s)\"", "%", "(", "public_id", ",", "str", "(", "e", ")", ")", ")", "finally", ":", "connection", ".", "close", "(", ")" ]
Loads AEAD from the specified database.
[ "Loads", "AEAD", "from", "the", "specified", "database", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/ksm/yubikey_ksm.py#L215-L236
train
Yubico/python-pyhsm
pyhsm/val/init_oath_token.py
generate_aead
def generate_aead(hsm, args): """ Protect the oath-k in an AEAD. """ key = get_oath_k(args) # Enabled flags 00010000 = YSM_HMAC_SHA1_GENERATE flags = struct.pack("< I", 0x10000) hsm.load_secret(key + flags) nonce = hsm.get_nonce().nonce aead = hsm.generate_aead(nonce, args.key_handle) if args.debug: print "AEAD: %s (%s)" % (aead.data.encode('hex'), aead) return nonce, aead
python
def generate_aead(hsm, args): """ Protect the oath-k in an AEAD. """ key = get_oath_k(args) # Enabled flags 00010000 = YSM_HMAC_SHA1_GENERATE flags = struct.pack("< I", 0x10000) hsm.load_secret(key + flags) nonce = hsm.get_nonce().nonce aead = hsm.generate_aead(nonce, args.key_handle) if args.debug: print "AEAD: %s (%s)" % (aead.data.encode('hex'), aead) return nonce, aead
[ "def", "generate_aead", "(", "hsm", ",", "args", ")", ":", "key", "=", "get_oath_k", "(", "args", ")", "# Enabled flags 00010000 = YSM_HMAC_SHA1_GENERATE", "flags", "=", "struct", ".", "pack", "(", "\"< I\"", ",", "0x10000", ")", "hsm", ".", "load_secret", "(", "key", "+", "flags", ")", "nonce", "=", "hsm", ".", "get_nonce", "(", ")", ".", "nonce", "aead", "=", "hsm", ".", "generate_aead", "(", "nonce", ",", "args", ".", "key_handle", ")", "if", "args", ".", "debug", ":", "print", "\"AEAD: %s (%s)\"", "%", "(", "aead", ".", "data", ".", "encode", "(", "'hex'", ")", ",", "aead", ")", "return", "nonce", ",", "aead" ]
Protect the oath-k in an AEAD.
[ "Protect", "the", "oath", "-", "k", "in", "an", "AEAD", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L105-L115
train
Yubico/python-pyhsm
pyhsm/val/init_oath_token.py
store_oath_entry
def store_oath_entry(args, nonce, aead, oath_c): """ Store the AEAD in the database. """ data = {"key": args.uid, "aead": aead.data.encode('hex'), "nonce": nonce.encode('hex'), "key_handle": args.key_handle, "oath_C": oath_c, "oath_T": None, } entry = ValOathEntry(data) db = ValOathDb(args.db_file) try: if args.force: db.delete(entry) db.add(entry) except sqlite3.IntegrityError, e: sys.stderr.write("ERROR: %s\n" % (e)) return False return True
python
def store_oath_entry(args, nonce, aead, oath_c): """ Store the AEAD in the database. """ data = {"key": args.uid, "aead": aead.data.encode('hex'), "nonce": nonce.encode('hex'), "key_handle": args.key_handle, "oath_C": oath_c, "oath_T": None, } entry = ValOathEntry(data) db = ValOathDb(args.db_file) try: if args.force: db.delete(entry) db.add(entry) except sqlite3.IntegrityError, e: sys.stderr.write("ERROR: %s\n" % (e)) return False return True
[ "def", "store_oath_entry", "(", "args", ",", "nonce", ",", "aead", ",", "oath_c", ")", ":", "data", "=", "{", "\"key\"", ":", "args", ".", "uid", ",", "\"aead\"", ":", "aead", ".", "data", ".", "encode", "(", "'hex'", ")", ",", "\"nonce\"", ":", "nonce", ".", "encode", "(", "'hex'", ")", ",", "\"key_handle\"", ":", "args", ".", "key_handle", ",", "\"oath_C\"", ":", "oath_c", ",", "\"oath_T\"", ":", "None", ",", "}", "entry", "=", "ValOathEntry", "(", "data", ")", "db", "=", "ValOathDb", "(", "args", ".", "db_file", ")", "try", ":", "if", "args", ".", "force", ":", "db", ".", "delete", "(", "entry", ")", "db", ".", "add", "(", "entry", ")", "except", "sqlite3", ".", "IntegrityError", ",", "e", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: %s\\n\"", "%", "(", "e", ")", ")", "return", "False", "return", "True" ]
Store the AEAD in the database.
[ "Store", "the", "AEAD", "in", "the", "database", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L185-L203
train
Yubico/python-pyhsm
pyhsm/val/init_oath_token.py
ValOathDb.add
def add(self, entry): """ Add entry to database. """ c = self.conn.cursor() c.execute("INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)", (entry.data["key"], \ entry.data["aead"], \ entry.data["nonce"], \ entry.data["key_handle"], \ entry.data["oath_C"], \ entry.data["oath_T"],)) self.conn.commit() return c.rowcount == 1
python
def add(self, entry): """ Add entry to database. """ c = self.conn.cursor() c.execute("INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)", (entry.data["key"], \ entry.data["aead"], \ entry.data["nonce"], \ entry.data["key_handle"], \ entry.data["oath_C"], \ entry.data["oath_T"],)) self.conn.commit() return c.rowcount == 1
[ "def", "add", "(", "self", ",", "entry", ")", ":", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "\"INSERT INTO oath (key, aead, nonce, key_handle, oath_C, oath_T) VALUES (?, ?, ?, ?, ?, ?)\"", ",", "(", "entry", ".", "data", "[", "\"key\"", "]", ",", "entry", ".", "data", "[", "\"aead\"", "]", ",", "entry", ".", "data", "[", "\"nonce\"", "]", ",", "entry", ".", "data", "[", "\"key_handle\"", "]", ",", "entry", ".", "data", "[", "\"oath_C\"", "]", ",", "entry", ".", "data", "[", "\"oath_T\"", "]", ",", ")", ")", "self", ".", "conn", ".", "commit", "(", ")", "return", "c", ".", "rowcount", "==", "1" ]
Add entry to database.
[ "Add", "entry", "to", "database", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L161-L172
train
Yubico/python-pyhsm
pyhsm/val/init_oath_token.py
ValOathDb.delete
def delete(self, entry): """ Delete entry from database. """ c = self.conn.cursor() c.execute("DELETE FROM oath WHERE key = ?", (entry.data["key"],))
python
def delete(self, entry): """ Delete entry from database. """ c = self.conn.cursor() c.execute("DELETE FROM oath WHERE key = ?", (entry.data["key"],))
[ "def", "delete", "(", "self", ",", "entry", ")", ":", "c", "=", "self", ".", "conn", ".", "cursor", "(", ")", "c", ".", "execute", "(", "\"DELETE FROM oath WHERE key = ?\"", ",", "(", "entry", ".", "data", "[", "\"key\"", "]", ",", ")", ")" ]
Delete entry from database.
[ "Delete", "entry", "from", "database", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/init_oath_token.py#L174-L177
train
Yubico/python-pyhsm
pyhsm/aead_cmd.py
YHSM_AEAD_Cmd.parse_result
def parse_result(self, data): """ Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed. """ # typedef struct { # uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs) # uint32_t keyHandle; // Key handle # YSM_STATUS status; // Status # uint8_t numBytes; // Number of bytes in AEAD block # uint8_t aead[YSM_AEAD_MAX_SIZE]; // AEAD block # } YSM_AEAD_GENERATE_RESP; nonce, \ key_handle, \ self.status, \ num_bytes = struct.unpack_from("< %is I B B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data, 0) pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle) if self.status == pyhsm.defines.YSM_STATUS_OK: pyhsm.util.validate_cmd_response_nonce(nonce, self.nonce) offset = pyhsm.defines.YSM_AEAD_NONCE_SIZE + 6 aead = data[offset:offset + num_bytes] self.response = YHSM_GeneratedAEAD(nonce, key_handle, aead) return self.response else: raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status)
python
def parse_result(self, data): """ Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed. """ # typedef struct { # uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs) # uint32_t keyHandle; // Key handle # YSM_STATUS status; // Status # uint8_t numBytes; // Number of bytes in AEAD block # uint8_t aead[YSM_AEAD_MAX_SIZE]; // AEAD block # } YSM_AEAD_GENERATE_RESP; nonce, \ key_handle, \ self.status, \ num_bytes = struct.unpack_from("< %is I B B" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE), data, 0) pyhsm.util.validate_cmd_response_hex('key_handle', key_handle, self.key_handle) if self.status == pyhsm.defines.YSM_STATUS_OK: pyhsm.util.validate_cmd_response_nonce(nonce, self.nonce) offset = pyhsm.defines.YSM_AEAD_NONCE_SIZE + 6 aead = data[offset:offset + num_bytes] self.response = YHSM_GeneratedAEAD(nonce, key_handle, aead) return self.response else: raise pyhsm.exception.YHSM_CommandFailed(pyhsm.defines.cmd2str(self.command), self.status)
[ "def", "parse_result", "(", "self", ",", "data", ")", ":", "# typedef struct {", "# uint8_t nonce[YSM_AEAD_NONCE_SIZE]; // Nonce (publicId for Yubikey AEADs)", "# uint32_t keyHandle; // Key handle", "# YSM_STATUS status; // Status", "# uint8_t numBytes; // Number of bytes in AEAD block", "# uint8_t aead[YSM_AEAD_MAX_SIZE]; // AEAD block", "# } YSM_AEAD_GENERATE_RESP;", "nonce", ",", "key_handle", ",", "self", ".", "status", ",", "num_bytes", "=", "struct", ".", "unpack_from", "(", "\"< %is I B B\"", "%", "(", "pyhsm", ".", "defines", ".", "YSM_AEAD_NONCE_SIZE", ")", ",", "data", ",", "0", ")", "pyhsm", ".", "util", ".", "validate_cmd_response_hex", "(", "'key_handle'", ",", "key_handle", ",", "self", ".", "key_handle", ")", "if", "self", ".", "status", "==", "pyhsm", ".", "defines", ".", "YSM_STATUS_OK", ":", "pyhsm", ".", "util", ".", "validate_cmd_response_nonce", "(", "nonce", ",", "self", ".", "nonce", ")", "offset", "=", "pyhsm", ".", "defines", ".", "YSM_AEAD_NONCE_SIZE", "+", "6", "aead", "=", "data", "[", "offset", ":", "offset", "+", "num_bytes", "]", "self", ".", "response", "=", "YHSM_GeneratedAEAD", "(", "nonce", ",", "key_handle", ",", "aead", ")", "return", "self", ".", "response", "else", ":", "raise", "pyhsm", ".", "exception", ".", "YHSM_CommandFailed", "(", "pyhsm", ".", "defines", ".", "cmd2str", "(", "self", ".", "command", ")", ",", "self", ".", "status", ")" ]
Returns a YHSM_GeneratedAEAD instance, or throws pyhsm.exception.YHSM_CommandFailed.
[ "Returns", "a", "YHSM_GeneratedAEAD", "instance", "or", "throws", "pyhsm", ".", "exception", ".", "YHSM_CommandFailed", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L58-L84
train
Yubico/python-pyhsm
pyhsm/aead_cmd.py
YHSM_GeneratedAEAD.save
def save(self, filename): """ Store AEAD in a file. @param filename: File to create/overwrite @type filename: string """ aead_f = open(filename, "wb") fmt = "< B I %is %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE, len(self.data)) version = 1 packed = struct.pack(fmt, version, self.key_handle, self.nonce, self.data) aead_f.write(YHSM_AEAD_File_Marker + packed) aead_f.close()
python
def save(self, filename): """ Store AEAD in a file. @param filename: File to create/overwrite @type filename: string """ aead_f = open(filename, "wb") fmt = "< B I %is %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE, len(self.data)) version = 1 packed = struct.pack(fmt, version, self.key_handle, self.nonce, self.data) aead_f.write(YHSM_AEAD_File_Marker + packed) aead_f.close()
[ "def", "save", "(", "self", ",", "filename", ")", ":", "aead_f", "=", "open", "(", "filename", ",", "\"wb\"", ")", "fmt", "=", "\"< B I %is %is\"", "%", "(", "pyhsm", ".", "defines", ".", "YSM_AEAD_NONCE_SIZE", ",", "len", "(", "self", ".", "data", ")", ")", "version", "=", "1", "packed", "=", "struct", ".", "pack", "(", "fmt", ",", "version", ",", "self", ".", "key_handle", ",", "self", ".", "nonce", ",", "self", ".", "data", ")", "aead_f", ".", "write", "(", "YHSM_AEAD_File_Marker", "+", "packed", ")", "aead_f", ".", "close", "(", ")" ]
Store AEAD in a file. @param filename: File to create/overwrite @type filename: string
[ "Store", "AEAD", "in", "a", "file", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L214-L226
train
Yubico/python-pyhsm
pyhsm/aead_cmd.py
YHSM_GeneratedAEAD.load
def load(self, filename): """ Load AEAD from a file. @param filename: File to read AEAD from @type filename: string """ aead_f = open(filename, "rb") buf = aead_f.read(1024) if buf.startswith(YHSM_AEAD_CRLF_File_Marker): buf = YHSM_AEAD_File_Marker + buf[len(YHSM_AEAD_CRLF_File_Marker):] if buf.startswith(YHSM_AEAD_File_Marker): if buf[len(YHSM_AEAD_File_Marker)] == chr(1): # version 1 format fmt = "< I %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE) self.key_handle, self.nonce = struct.unpack_from(fmt, buf, len(YHSM_AEAD_File_Marker) + 1) self.data = buf[len(YHSM_AEAD_File_Marker) + 1 + struct.calcsize(fmt):] else: raise pyhsm.exception.YHSM_Error('Unknown AEAD file format') else: # version 0 format, just AEAD data self.data = buf[:pyhsm.defines.YSM_MAX_KEY_SIZE + pyhsm.defines.YSM_BLOCK_SIZE] aead_f.close()
python
def load(self, filename): """ Load AEAD from a file. @param filename: File to read AEAD from @type filename: string """ aead_f = open(filename, "rb") buf = aead_f.read(1024) if buf.startswith(YHSM_AEAD_CRLF_File_Marker): buf = YHSM_AEAD_File_Marker + buf[len(YHSM_AEAD_CRLF_File_Marker):] if buf.startswith(YHSM_AEAD_File_Marker): if buf[len(YHSM_AEAD_File_Marker)] == chr(1): # version 1 format fmt = "< I %is" % (pyhsm.defines.YSM_AEAD_NONCE_SIZE) self.key_handle, self.nonce = struct.unpack_from(fmt, buf, len(YHSM_AEAD_File_Marker) + 1) self.data = buf[len(YHSM_AEAD_File_Marker) + 1 + struct.calcsize(fmt):] else: raise pyhsm.exception.YHSM_Error('Unknown AEAD file format') else: # version 0 format, just AEAD data self.data = buf[:pyhsm.defines.YSM_MAX_KEY_SIZE + pyhsm.defines.YSM_BLOCK_SIZE] aead_f.close()
[ "def", "load", "(", "self", ",", "filename", ")", ":", "aead_f", "=", "open", "(", "filename", ",", "\"rb\"", ")", "buf", "=", "aead_f", ".", "read", "(", "1024", ")", "if", "buf", ".", "startswith", "(", "YHSM_AEAD_CRLF_File_Marker", ")", ":", "buf", "=", "YHSM_AEAD_File_Marker", "+", "buf", "[", "len", "(", "YHSM_AEAD_CRLF_File_Marker", ")", ":", "]", "if", "buf", ".", "startswith", "(", "YHSM_AEAD_File_Marker", ")", ":", "if", "buf", "[", "len", "(", "YHSM_AEAD_File_Marker", ")", "]", "==", "chr", "(", "1", ")", ":", "# version 1 format", "fmt", "=", "\"< I %is\"", "%", "(", "pyhsm", ".", "defines", ".", "YSM_AEAD_NONCE_SIZE", ")", "self", ".", "key_handle", ",", "self", ".", "nonce", "=", "struct", ".", "unpack_from", "(", "fmt", ",", "buf", ",", "len", "(", "YHSM_AEAD_File_Marker", ")", "+", "1", ")", "self", ".", "data", "=", "buf", "[", "len", "(", "YHSM_AEAD_File_Marker", ")", "+", "1", "+", "struct", ".", "calcsize", "(", "fmt", ")", ":", "]", "else", ":", "raise", "pyhsm", ".", "exception", ".", "YHSM_Error", "(", "'Unknown AEAD file format'", ")", "else", ":", "# version 0 format, just AEAD data", "self", ".", "data", "=", "buf", "[", ":", "pyhsm", ".", "defines", ".", "YSM_MAX_KEY_SIZE", "+", "pyhsm", ".", "defines", ".", "YSM_BLOCK_SIZE", "]", "aead_f", ".", "close", "(", ")" ]
Load AEAD from a file. @param filename: File to read AEAD from @type filename: string
[ "Load", "AEAD", "from", "a", "file", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L228-L250
train
Yubico/python-pyhsm
pyhsm/aead_cmd.py
YHSM_YubiKeySecret.pack
def pack(self): """ Return key and uid packed for sending in a command to the YubiHSM. """ # # 22-bytes Yubikey secrets block # typedef struct { # uint8_t key[KEY_SIZE]; // AES key # uint8_t uid[UID_SIZE]; // Unique (secret) ID # } YUBIKEY_SECRETS; return self.key + self.uid.ljust(pyhsm.defines.UID_SIZE, chr(0))
python
def pack(self): """ Return key and uid packed for sending in a command to the YubiHSM. """ # # 22-bytes Yubikey secrets block # typedef struct { # uint8_t key[KEY_SIZE]; // AES key # uint8_t uid[UID_SIZE]; // Unique (secret) ID # } YUBIKEY_SECRETS; return self.key + self.uid.ljust(pyhsm.defines.UID_SIZE, chr(0))
[ "def", "pack", "(", "self", ")", ":", "# # 22-bytes Yubikey secrets block", "# typedef struct {", "# uint8_t key[KEY_SIZE]; // AES key", "# uint8_t uid[UID_SIZE]; // Unique (secret) ID", "# } YUBIKEY_SECRETS;", "return", "self", ".", "key", "+", "self", ".", "uid", ".", "ljust", "(", "pyhsm", ".", "defines", ".", "UID_SIZE", ",", "chr", "(", "0", ")", ")" ]
Return key and uid packed for sending in a command to the YubiHSM.
[ "Return", "key", "and", "uid", "packed", "for", "sending", "in", "a", "command", "to", "the", "YubiHSM", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/aead_cmd.py#L258-L265
train
Yubico/python-pyhsm
pyhsm/val/validate_otp.py
validate_otp
def validate_otp(hsm, args): """ Validate an OTP. """ try: res = pyhsm.yubikey.validate_otp(hsm, args.otp) if args.verbose: print "OK counter=%04x low=%04x high=%02x use=%02x" % \ (res.use_ctr, res.ts_low, res.ts_high, res.session_ctr) return 0 except pyhsm.exception.YHSM_CommandFailed, e: if args.verbose: print "%s" % (pyhsm.defines.status2str(e.status)) # figure out numerical response code for r in [pyhsm.defines.YSM_OTP_INVALID, \ pyhsm.defines.YSM_OTP_REPLAY, \ pyhsm.defines.YSM_ID_NOT_FOUND]: if e.status == r: return r - pyhsm.defines.YSM_RESPONSE # not found return 0xff
python
def validate_otp(hsm, args): """ Validate an OTP. """ try: res = pyhsm.yubikey.validate_otp(hsm, args.otp) if args.verbose: print "OK counter=%04x low=%04x high=%02x use=%02x" % \ (res.use_ctr, res.ts_low, res.ts_high, res.session_ctr) return 0 except pyhsm.exception.YHSM_CommandFailed, e: if args.verbose: print "%s" % (pyhsm.defines.status2str(e.status)) # figure out numerical response code for r in [pyhsm.defines.YSM_OTP_INVALID, \ pyhsm.defines.YSM_OTP_REPLAY, \ pyhsm.defines.YSM_ID_NOT_FOUND]: if e.status == r: return r - pyhsm.defines.YSM_RESPONSE # not found return 0xff
[ "def", "validate_otp", "(", "hsm", ",", "args", ")", ":", "try", ":", "res", "=", "pyhsm", ".", "yubikey", ".", "validate_otp", "(", "hsm", ",", "args", ".", "otp", ")", "if", "args", ".", "verbose", ":", "print", "\"OK counter=%04x low=%04x high=%02x use=%02x\"", "%", "(", "res", ".", "use_ctr", ",", "res", ".", "ts_low", ",", "res", ".", "ts_high", ",", "res", ".", "session_ctr", ")", "return", "0", "except", "pyhsm", ".", "exception", ".", "YHSM_CommandFailed", ",", "e", ":", "if", "args", ".", "verbose", ":", "print", "\"%s\"", "%", "(", "pyhsm", ".", "defines", ".", "status2str", "(", "e", ".", "status", ")", ")", "# figure out numerical response code", "for", "r", "in", "[", "pyhsm", ".", "defines", ".", "YSM_OTP_INVALID", ",", "pyhsm", ".", "defines", ".", "YSM_OTP_REPLAY", ",", "pyhsm", ".", "defines", ".", "YSM_ID_NOT_FOUND", "]", ":", "if", "e", ".", "status", "==", "r", ":", "return", "r", "-", "pyhsm", ".", "defines", ".", "YSM_RESPONSE", "# not found", "return", "0xff" ]
Validate an OTP.
[ "Validate", "an", "OTP", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/val/validate_otp.py#L61-L81
train
Yubico/python-pyhsm
pyhsm/oath_totp.py
search_for_oath_code
def search_for_oath_code(hsm, key_handle, nonce, aead, user_code, interval=30, tolerance=0): """ Try to validate an OATH TOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD. The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD. Returns timecounter value on successful auth, and None otherwise. """ # timecounter is the lowest acceptable value based on tolerance timecounter = timecode(datetime.datetime.now(), interval) - tolerance return search_hotp( hsm, key_handle, nonce, aead, timecounter, user_code, 1 + 2*tolerance)
python
def search_for_oath_code(hsm, key_handle, nonce, aead, user_code, interval=30, tolerance=0): """ Try to validate an OATH TOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD. The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD. Returns timecounter value on successful auth, and None otherwise. """ # timecounter is the lowest acceptable value based on tolerance timecounter = timecode(datetime.datetime.now(), interval) - tolerance return search_hotp( hsm, key_handle, nonce, aead, timecounter, user_code, 1 + 2*tolerance)
[ "def", "search_for_oath_code", "(", "hsm", ",", "key_handle", ",", "nonce", ",", "aead", ",", "user_code", ",", "interval", "=", "30", ",", "tolerance", "=", "0", ")", ":", "# timecounter is the lowest acceptable value based on tolerance", "timecounter", "=", "timecode", "(", "datetime", ".", "datetime", ".", "now", "(", ")", ",", "interval", ")", "-", "tolerance", "return", "search_hotp", "(", "hsm", ",", "key_handle", ",", "nonce", ",", "aead", ",", "timecounter", ",", "user_code", ",", "1", "+", "2", "*", "tolerance", ")" ]
Try to validate an OATH TOTP OTP generated by a token whose secret key is available to the YubiHSM through the AEAD. The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD. Returns timecounter value on successful auth, and None otherwise.
[ "Try", "to", "validate", "an", "OATH", "TOTP", "OTP", "generated", "by", "a", "token", "whose", "secret", "key", "is", "available", "to", "the", "YubiHSM", "through", "the", "AEAD", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_totp.py#L21-L36
train
Yubico/python-pyhsm
pyhsm/oath_totp.py
timecode
def timecode(time_now, interval): """ make integer and divide by time interval of valid OTP """ i = time.mktime(time_now.timetuple()) return int(i / interval)
python
def timecode(time_now, interval): """ make integer and divide by time interval of valid OTP """ i = time.mktime(time_now.timetuple()) return int(i / interval)
[ "def", "timecode", "(", "time_now", ",", "interval", ")", ":", "i", "=", "time", ".", "mktime", "(", "time_now", ".", "timetuple", "(", ")", ")", "return", "int", "(", "i", "/", "interval", ")" ]
make integer and divide by time interval of valid OTP
[ "make", "integer", "and", "divide", "by", "time", "interval", "of", "valid", "OTP" ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/oath_totp.py#L39-L42
train
Yubico/python-pyhsm
pyhsm/soft_hsm.py
_xor_block
def _xor_block(a, b): """ XOR two blocks of equal length. """ return ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
python
def _xor_block(a, b): """ XOR two blocks of equal length. """ return ''.join([chr(ord(x) ^ ord(y)) for (x, y) in zip(a, b)])
[ "def", "_xor_block", "(", "a", ",", "b", ")", ":", "return", "''", ".", "join", "(", "[", "chr", "(", "ord", "(", "x", ")", "^", "ord", "(", "y", ")", ")", "for", "(", "x", ",", "y", ")", "in", "zip", "(", "a", ",", "b", ")", "]", ")" ]
XOR two blocks of equal length.
[ "XOR", "two", "blocks", "of", "equal", "length", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L26-L28
train
Yubico/python-pyhsm
pyhsm/soft_hsm.py
crc16
def crc16(data): """ Calculate an ISO13239 CRC checksum of the input buffer. """ m_crc = 0xffff for this in data: m_crc ^= ord(this) for _ in range(8): j = m_crc & 1 m_crc >>= 1 if j: m_crc ^= 0x8408 return m_crc
python
def crc16(data): """ Calculate an ISO13239 CRC checksum of the input buffer. """ m_crc = 0xffff for this in data: m_crc ^= ord(this) for _ in range(8): j = m_crc & 1 m_crc >>= 1 if j: m_crc ^= 0x8408 return m_crc
[ "def", "crc16", "(", "data", ")", ":", "m_crc", "=", "0xffff", "for", "this", "in", "data", ":", "m_crc", "^=", "ord", "(", "this", ")", "for", "_", "in", "range", "(", "8", ")", ":", "j", "=", "m_crc", "&", "1", "m_crc", ">>=", "1", "if", "j", ":", "m_crc", "^=", "0x8408", "return", "m_crc" ]
Calculate an ISO13239 CRC checksum of the input buffer.
[ "Calculate", "an", "ISO13239", "CRC", "checksum", "of", "the", "input", "buffer", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L132-L144
train
Yubico/python-pyhsm
pyhsm/soft_hsm.py
_cbc_mac.finalize
def finalize(self, block): """ The final step of CBC-MAC encrypts before xor. """ t1 = self.mac_aes.encrypt(block) t2 = _xor_block(self.mac, t1) self.mac = t2
python
def finalize(self, block): """ The final step of CBC-MAC encrypts before xor. """ t1 = self.mac_aes.encrypt(block) t2 = _xor_block(self.mac, t1) self.mac = t2
[ "def", "finalize", "(", "self", ",", "block", ")", ":", "t1", "=", "self", ".", "mac_aes", ".", "encrypt", "(", "block", ")", "t2", "=", "_xor_block", "(", "self", ".", "mac", ",", "t1", ")", "self", ".", "mac", "=", "t2" ]
The final step of CBC-MAC encrypts before xor.
[ "The", "final", "step", "of", "CBC", "-", "MAC", "encrypts", "before", "xor", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/soft_hsm.py#L77-L83
train
Yubico/python-pyhsm
pyhsm/yubikey.py
validate_otp
def validate_otp(hsm, from_key): """ Try to validate an OTP from a YubiKey using the internal database on the YubiHSM. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhsm.exception.YHSM_CommandFailed}. @param hsm: The YHSM instance @param from_key: The OTP from a YubiKey (in modhex) @type hsm: L{pyhsm.YHSM} @type from_key: string @returns: validation response, if successful @rtype: L{YHSM_ValidationResult} @see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP.parse_result} """ public_id, otp = split_id_otp(from_key) return hsm.db_validate_yubikey_otp(modhex_decode(public_id).decode('hex'), modhex_decode(otp).decode('hex') )
python
def validate_otp(hsm, from_key): """ Try to validate an OTP from a YubiKey using the internal database on the YubiHSM. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhsm.exception.YHSM_CommandFailed}. @param hsm: The YHSM instance @param from_key: The OTP from a YubiKey (in modhex) @type hsm: L{pyhsm.YHSM} @type from_key: string @returns: validation response, if successful @rtype: L{YHSM_ValidationResult} @see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP.parse_result} """ public_id, otp = split_id_otp(from_key) return hsm.db_validate_yubikey_otp(modhex_decode(public_id).decode('hex'), modhex_decode(otp).decode('hex') )
[ "def", "validate_otp", "(", "hsm", ",", "from_key", ")", ":", "public_id", ",", "otp", "=", "split_id_otp", "(", "from_key", ")", "return", "hsm", ".", "db_validate_yubikey_otp", "(", "modhex_decode", "(", "public_id", ")", ".", "decode", "(", "'hex'", ")", ",", "modhex_decode", "(", "otp", ")", ".", "decode", "(", "'hex'", ")", ")" ]
Try to validate an OTP from a YubiKey using the internal database on the YubiHSM. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhsm.exception.YHSM_CommandFailed}. @param hsm: The YHSM instance @param from_key: The OTP from a YubiKey (in modhex) @type hsm: L{pyhsm.YHSM} @type from_key: string @returns: validation response, if successful @rtype: L{YHSM_ValidationResult} @see: L{pyhsm.db_cmd.YHSM_Cmd_DB_Validate_OTP.parse_result}
[ "Try", "to", "validate", "an", "OTP", "from", "a", "YubiKey", "using", "the", "internal", "database", "on", "the", "YubiHSM", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/yubikey.py#L24-L48
train
Yubico/python-pyhsm
pyhsm/yubikey.py
validate_yubikey_with_aead
def validate_yubikey_with_aead(hsm, from_key, aead, key_handle): """ Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey's internal secret, using the key_handle for the AEAD. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhsm.exception.YHSM_CommandFailed}. @param hsm: The YHSM instance @param from_key: The OTP from a YubiKey (in modhex) @param aead: AEAD containing the cryptographic key and permission flags @param key_handle: The key handle that can decrypt the AEAD @type hsm: L{pyhsm.YHSM} @type from_key: string @type aead: L{YHSM_GeneratedAEAD} or string @type key_handle: integer or string @returns: validation response @rtype: L{YHSM_ValidationResult} @see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP.parse_result} """ from_key = pyhsm.util.input_validate_str(from_key, 'from_key', max_len = 48) nonce = aead.nonce aead = pyhsm.util.input_validate_aead(aead) key_handle = pyhsm.util.input_validate_key_handle(key_handle) public_id, otp = split_id_otp(from_key) public_id = modhex_decode(public_id) otp = modhex_decode(otp) if not nonce: nonce = public_id.decode('hex') return hsm.validate_aead_otp(nonce, otp.decode('hex'), key_handle, aead)
python
def validate_yubikey_with_aead(hsm, from_key, aead, key_handle): """ Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey's internal secret, using the key_handle for the AEAD. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhsm.exception.YHSM_CommandFailed}. @param hsm: The YHSM instance @param from_key: The OTP from a YubiKey (in modhex) @param aead: AEAD containing the cryptographic key and permission flags @param key_handle: The key handle that can decrypt the AEAD @type hsm: L{pyhsm.YHSM} @type from_key: string @type aead: L{YHSM_GeneratedAEAD} or string @type key_handle: integer or string @returns: validation response @rtype: L{YHSM_ValidationResult} @see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP.parse_result} """ from_key = pyhsm.util.input_validate_str(from_key, 'from_key', max_len = 48) nonce = aead.nonce aead = pyhsm.util.input_validate_aead(aead) key_handle = pyhsm.util.input_validate_key_handle(key_handle) public_id, otp = split_id_otp(from_key) public_id = modhex_decode(public_id) otp = modhex_decode(otp) if not nonce: nonce = public_id.decode('hex') return hsm.validate_aead_otp(nonce, otp.decode('hex'), key_handle, aead)
[ "def", "validate_yubikey_with_aead", "(", "hsm", ",", "from_key", ",", "aead", ",", "key_handle", ")", ":", "from_key", "=", "pyhsm", ".", "util", ".", "input_validate_str", "(", "from_key", ",", "'from_key'", ",", "max_len", "=", "48", ")", "nonce", "=", "aead", ".", "nonce", "aead", "=", "pyhsm", ".", "util", ".", "input_validate_aead", "(", "aead", ")", "key_handle", "=", "pyhsm", ".", "util", ".", "input_validate_key_handle", "(", "key_handle", ")", "public_id", ",", "otp", "=", "split_id_otp", "(", "from_key", ")", "public_id", "=", "modhex_decode", "(", "public_id", ")", "otp", "=", "modhex_decode", "(", "otp", ")", "if", "not", "nonce", ":", "nonce", "=", "public_id", ".", "decode", "(", "'hex'", ")", "return", "hsm", ".", "validate_aead_otp", "(", "nonce", ",", "otp", ".", "decode", "(", "'hex'", ")", ",", "key_handle", ",", "aead", ")" ]
Try to validate an OTP from a YubiKey using the AEAD that can decrypt this YubiKey's internal secret, using the key_handle for the AEAD. `from_key' is the modhex encoded string emitted when you press the button on your YubiKey. Will only return on succesfull validation. All failures will result in an L{pyhsm.exception.YHSM_CommandFailed}. @param hsm: The YHSM instance @param from_key: The OTP from a YubiKey (in modhex) @param aead: AEAD containing the cryptographic key and permission flags @param key_handle: The key handle that can decrypt the AEAD @type hsm: L{pyhsm.YHSM} @type from_key: string @type aead: L{YHSM_GeneratedAEAD} or string @type key_handle: integer or string @returns: validation response @rtype: L{YHSM_ValidationResult} @see: L{pyhsm.validate_cmd.YHSM_Cmd_AEAD_Validate_OTP.parse_result}
[ "Try", "to", "validate", "an", "OTP", "from", "a", "YubiKey", "using", "the", "AEAD", "that", "can", "decrypt", "this", "YubiKey", "s", "internal", "secret", "using", "the", "key_handle", "for", "the", "AEAD", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/yubikey.py#L50-L90
train
Yubico/python-pyhsm
pyhsm/yubikey.py
split_id_otp
def split_id_otp(from_key): """ Separate public id from OTP given a YubiKey OTP as input. @param from_key: The OTP from a YubiKey (in modhex) @type from_key: string @returns: public_id and OTP @rtype: tuple of string """ if len(from_key) > 32: public_id, otp = from_key[:-32], from_key[-32:] elif len(from_key) == 32: public_id = '' otp = from_key else: raise pyhsm.exception.YHSM_Error("Bad from_key length %i < 32 : %s" \ % (len(from_key), from_key)) return public_id, otp
python
def split_id_otp(from_key): """ Separate public id from OTP given a YubiKey OTP as input. @param from_key: The OTP from a YubiKey (in modhex) @type from_key: string @returns: public_id and OTP @rtype: tuple of string """ if len(from_key) > 32: public_id, otp = from_key[:-32], from_key[-32:] elif len(from_key) == 32: public_id = '' otp = from_key else: raise pyhsm.exception.YHSM_Error("Bad from_key length %i < 32 : %s" \ % (len(from_key), from_key)) return public_id, otp
[ "def", "split_id_otp", "(", "from_key", ")", ":", "if", "len", "(", "from_key", ")", ">", "32", ":", "public_id", ",", "otp", "=", "from_key", "[", ":", "-", "32", "]", ",", "from_key", "[", "-", "32", ":", "]", "elif", "len", "(", "from_key", ")", "==", "32", ":", "public_id", "=", "''", "otp", "=", "from_key", "else", ":", "raise", "pyhsm", ".", "exception", ".", "YHSM_Error", "(", "\"Bad from_key length %i < 32 : %s\"", "%", "(", "len", "(", "from_key", ")", ",", "from_key", ")", ")", "return", "public_id", ",", "otp" ]
Separate public id from OTP given a YubiKey OTP as input. @param from_key: The OTP from a YubiKey (in modhex) @type from_key: string @returns: public_id and OTP @rtype: tuple of string
[ "Separate", "public", "id", "from", "OTP", "given", "a", "YubiKey", "OTP", "as", "input", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/yubikey.py#L118-L136
train
Yubico/python-pyhsm
pyhsm/tools/keystore_unlock.py
get_password
def get_password(hsm, args): """ Get password of correct length for this YubiHSM version. """ expected_len = 32 name = 'HSM password' if hsm.version.have_key_store_decrypt(): expected_len = 64 name = 'master key' if args.stdin: password = sys.stdin.readline() while password and password[-1] == '\n': password = password[:-1] else: if args.debug: password = raw_input('Enter %s (press enter to skip) (will be echoed) : ' % (name)) else: password = getpass.getpass('Enter %s (press enter to skip) : ' % (name)) if len(password) <= expected_len: password = password.decode('hex') if not password: return None return password else: sys.stderr.write("ERROR: Invalid HSM password (expected max %i chars, got %i)\n" % \ (expected_len, len(password))) return 1
python
def get_password(hsm, args): """ Get password of correct length for this YubiHSM version. """ expected_len = 32 name = 'HSM password' if hsm.version.have_key_store_decrypt(): expected_len = 64 name = 'master key' if args.stdin: password = sys.stdin.readline() while password and password[-1] == '\n': password = password[:-1] else: if args.debug: password = raw_input('Enter %s (press enter to skip) (will be echoed) : ' % (name)) else: password = getpass.getpass('Enter %s (press enter to skip) : ' % (name)) if len(password) <= expected_len: password = password.decode('hex') if not password: return None return password else: sys.stderr.write("ERROR: Invalid HSM password (expected max %i chars, got %i)\n" % \ (expected_len, len(password))) return 1
[ "def", "get_password", "(", "hsm", ",", "args", ")", ":", "expected_len", "=", "32", "name", "=", "'HSM password'", "if", "hsm", ".", "version", ".", "have_key_store_decrypt", "(", ")", ":", "expected_len", "=", "64", "name", "=", "'master key'", "if", "args", ".", "stdin", ":", "password", "=", "sys", ".", "stdin", ".", "readline", "(", ")", "while", "password", "and", "password", "[", "-", "1", "]", "==", "'\\n'", ":", "password", "=", "password", "[", ":", "-", "1", "]", "else", ":", "if", "args", ".", "debug", ":", "password", "=", "raw_input", "(", "'Enter %s (press enter to skip) (will be echoed) : '", "%", "(", "name", ")", ")", "else", ":", "password", "=", "getpass", ".", "getpass", "(", "'Enter %s (press enter to skip) : '", "%", "(", "name", ")", ")", "if", "len", "(", "password", ")", "<=", "expected_len", ":", "password", "=", "password", ".", "decode", "(", "'hex'", ")", "if", "not", "password", ":", "return", "None", "return", "password", "else", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: Invalid HSM password (expected max %i chars, got %i)\\n\"", "%", "(", "expected_len", ",", "len", "(", "password", ")", ")", ")", "return", "1" ]
Get password of correct length for this YubiHSM version.
[ "Get", "password", "of", "correct", "length", "for", "this", "YubiHSM", "version", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/keystore_unlock.py#L56-L82
train
Yubico/python-pyhsm
pyhsm/tools/keystore_unlock.py
get_otp
def get_otp(hsm, args): """ Get OTP from YubiKey. """ if args.no_otp: return None if hsm.version.have_unlock(): if args.stdin: otp = sys.stdin.readline() while otp and otp[-1] == '\n': otp = otp[:-1] else: otp = raw_input('Enter admin YubiKey OTP (press enter to skip) : ') if len(otp) == 44: # YubiHSM admin OTP's always have a public_id length of 6 bytes return otp if otp: sys.stderr.write("ERROR: Invalid YubiKey OTP\n") return None
python
def get_otp(hsm, args): """ Get OTP from YubiKey. """ if args.no_otp: return None if hsm.version.have_unlock(): if args.stdin: otp = sys.stdin.readline() while otp and otp[-1] == '\n': otp = otp[:-1] else: otp = raw_input('Enter admin YubiKey OTP (press enter to skip) : ') if len(otp) == 44: # YubiHSM admin OTP's always have a public_id length of 6 bytes return otp if otp: sys.stderr.write("ERROR: Invalid YubiKey OTP\n") return None
[ "def", "get_otp", "(", "hsm", ",", "args", ")", ":", "if", "args", ".", "no_otp", ":", "return", "None", "if", "hsm", ".", "version", ".", "have_unlock", "(", ")", ":", "if", "args", ".", "stdin", ":", "otp", "=", "sys", ".", "stdin", ".", "readline", "(", ")", "while", "otp", "and", "otp", "[", "-", "1", "]", "==", "'\\n'", ":", "otp", "=", "otp", "[", ":", "-", "1", "]", "else", ":", "otp", "=", "raw_input", "(", "'Enter admin YubiKey OTP (press enter to skip) : '", ")", "if", "len", "(", "otp", ")", "==", "44", ":", "# YubiHSM admin OTP's always have a public_id length of 6 bytes", "return", "otp", "if", "otp", ":", "sys", ".", "stderr", ".", "write", "(", "\"ERROR: Invalid YubiKey OTP\\n\"", ")", "return", "None" ]
Get OTP from YubiKey.
[ "Get", "OTP", "from", "YubiKey", "." ]
b6e2744d1ea15c352a0fc1d6ebc5950026b71311
https://github.com/Yubico/python-pyhsm/blob/b6e2744d1ea15c352a0fc1d6ebc5950026b71311/pyhsm/tools/keystore_unlock.py#L84-L100
train
ResidentMario/geoplot
geoplot/crs.py
Base.load
def load(self, df, centerings): """ A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures. Parameters ---------- proj : geoplot.crs object instance A disguised reference to ``self``. df : GeoDataFrame The GeoDataFrame which has been passed as input to the plotter at the top level. This data is needed to calculate reasonable centering variables in cases in which the user does not already provide them; which is, incidentally, the reason behind all of this funny twice-instantiation loading in the first place. centerings: dct A dictionary containing names and centering methods. Certain projections have certain centering parameters whilst others lack them. For example, the geospatial projection contains both ``central_longitude`` and ``central_latitude`` instance parameter, which together control the center of the plot, while the North Pole Stereo projection has only a ``central_longitude`` instance parameter, implying that latitude is fixed (as indeed it is, as this projection is centered on the North Pole!). A top-level centerings method is provided in each of the ``geoplot`` top-level plot functions; each of the projection wrapper classes defined here in turn selects the functions from this list relevent to this particular instance and passes them to the ``_generic_load`` method here. We then in turn execute these functions to get defaults for our ``df`` and pass them off to our output ``cartopy.crs`` instance. Returns ------- crs : ``cartopy.crs`` object instance Returns a ``cartopy.crs`` object instance whose appropriate instance variables have been set to reasonable defaults wherever not already provided by the user. """ centering_variables = dict() if not df.empty and df.geometry.notna().any(): for key, func in centerings.items(): centering_variables[key] = func(df) return getattr(ccrs, self.__class__.__name__)(**{**centering_variables, **self.args})
python
def load(self, df, centerings): """ A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures. Parameters ---------- proj : geoplot.crs object instance A disguised reference to ``self``. df : GeoDataFrame The GeoDataFrame which has been passed as input to the plotter at the top level. This data is needed to calculate reasonable centering variables in cases in which the user does not already provide them; which is, incidentally, the reason behind all of this funny twice-instantiation loading in the first place. centerings: dct A dictionary containing names and centering methods. Certain projections have certain centering parameters whilst others lack them. For example, the geospatial projection contains both ``central_longitude`` and ``central_latitude`` instance parameter, which together control the center of the plot, while the North Pole Stereo projection has only a ``central_longitude`` instance parameter, implying that latitude is fixed (as indeed it is, as this projection is centered on the North Pole!). A top-level centerings method is provided in each of the ``geoplot`` top-level plot functions; each of the projection wrapper classes defined here in turn selects the functions from this list relevent to this particular instance and passes them to the ``_generic_load`` method here. We then in turn execute these functions to get defaults for our ``df`` and pass them off to our output ``cartopy.crs`` instance. Returns ------- crs : ``cartopy.crs`` object instance Returns a ``cartopy.crs`` object instance whose appropriate instance variables have been set to reasonable defaults wherever not already provided by the user. """ centering_variables = dict() if not df.empty and df.geometry.notna().any(): for key, func in centerings.items(): centering_variables[key] = func(df) return getattr(ccrs, self.__class__.__name__)(**{**centering_variables, **self.args})
[ "def", "load", "(", "self", ",", "df", ",", "centerings", ")", ":", "centering_variables", "=", "dict", "(", ")", "if", "not", "df", ".", "empty", "and", "df", ".", "geometry", ".", "notna", "(", ")", ".", "any", "(", ")", ":", "for", "key", ",", "func", "in", "centerings", ".", "items", "(", ")", ":", "centering_variables", "[", "key", "]", "=", "func", "(", "df", ")", "return", "getattr", "(", "ccrs", ",", "self", ".", "__class__", ".", "__name__", ")", "(", "*", "*", "{", "*", "*", "centering_variables", ",", "*", "*", "self", ".", "args", "}", ")" ]
A moderately mind-bendy meta-method which abstracts the internals of individual projections' load procedures. Parameters ---------- proj : geoplot.crs object instance A disguised reference to ``self``. df : GeoDataFrame The GeoDataFrame which has been passed as input to the plotter at the top level. This data is needed to calculate reasonable centering variables in cases in which the user does not already provide them; which is, incidentally, the reason behind all of this funny twice-instantiation loading in the first place. centerings: dct A dictionary containing names and centering methods. Certain projections have certain centering parameters whilst others lack them. For example, the geospatial projection contains both ``central_longitude`` and ``central_latitude`` instance parameter, which together control the center of the plot, while the North Pole Stereo projection has only a ``central_longitude`` instance parameter, implying that latitude is fixed (as indeed it is, as this projection is centered on the North Pole!). A top-level centerings method is provided in each of the ``geoplot`` top-level plot functions; each of the projection wrapper classes defined here in turn selects the functions from this list relevent to this particular instance and passes them to the ``_generic_load`` method here. We then in turn execute these functions to get defaults for our ``df`` and pass them off to our output ``cartopy.crs`` instance. Returns ------- crs : ``cartopy.crs`` object instance Returns a ``cartopy.crs`` object instance whose appropriate instance variables have been set to reasonable defaults wherever not already provided by the user.
[ "A", "moderately", "mind", "-", "bendy", "meta", "-", "method", "which", "abstracts", "the", "internals", "of", "individual", "projections", "load", "procedures", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/crs.py#L26-L62
train
ResidentMario/geoplot
geoplot/crs.py
Filtering.load
def load(self, df, centerings): """Call `load` method with `centerings` filtered to keys in `self.filter_`.""" return super().load( df, {key: value for key, value in centerings.items() if key in self.filter_} )
python
def load(self, df, centerings): """Call `load` method with `centerings` filtered to keys in `self.filter_`.""" return super().load( df, {key: value for key, value in centerings.items() if key in self.filter_} )
[ "def", "load", "(", "self", ",", "df", ",", "centerings", ")", ":", "return", "super", "(", ")", ".", "load", "(", "df", ",", "{", "key", ":", "value", "for", "key", ",", "value", "in", "centerings", ".", "items", "(", ")", "if", "key", "in", "self", ".", "filter_", "}", ")" ]
Call `load` method with `centerings` filtered to keys in `self.filter_`.
[ "Call", "load", "method", "with", "centerings", "filtered", "to", "keys", "in", "self", ".", "filter_", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/crs.py#L99-L106
train
ResidentMario/geoplot
geoplot/utils.py
gaussian_points
def gaussian_points(loc=(0, 0), scale=(10, 10), n=100): """ Generates and returns `n` normally distributed points centered at `loc` with `scale` x and y directionality. """ arr = np.random.normal(loc, scale, (n, 2)) return gpd.GeoSeries([shapely.geometry.Point(x, y) for (x, y) in arr])
python
def gaussian_points(loc=(0, 0), scale=(10, 10), n=100): """ Generates and returns `n` normally distributed points centered at `loc` with `scale` x and y directionality. """ arr = np.random.normal(loc, scale, (n, 2)) return gpd.GeoSeries([shapely.geometry.Point(x, y) for (x, y) in arr])
[ "def", "gaussian_points", "(", "loc", "=", "(", "0", ",", "0", ")", ",", "scale", "=", "(", "10", ",", "10", ")", ",", "n", "=", "100", ")", ":", "arr", "=", "np", ".", "random", ".", "normal", "(", "loc", ",", "scale", ",", "(", "n", ",", "2", ")", ")", "return", "gpd", ".", "GeoSeries", "(", "[", "shapely", ".", "geometry", ".", "Point", "(", "x", ",", "y", ")", "for", "(", "x", ",", "y", ")", "in", "arr", "]", ")" ]
Generates and returns `n` normally distributed points centered at `loc` with `scale` x and y directionality.
[ "Generates", "and", "returns", "n", "normally", "distributed", "points", "centered", "at", "loc", "with", "scale", "x", "and", "y", "directionality", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L14-L20
train
ResidentMario/geoplot
geoplot/utils.py
classify_clusters
def classify_clusters(points, n=10): """ Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects. """ arr = [[p.x, p.y] for p in points.values] clf = KMeans(n_clusters=n) clf.fit(arr) classes = clf.predict(arr) return classes
python
def classify_clusters(points, n=10): """ Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects. """ arr = [[p.x, p.y] for p in points.values] clf = KMeans(n_clusters=n) clf.fit(arr) classes = clf.predict(arr) return classes
[ "def", "classify_clusters", "(", "points", ",", "n", "=", "10", ")", ":", "arr", "=", "[", "[", "p", ".", "x", ",", "p", ".", "y", "]", "for", "p", "in", "points", ".", "values", "]", "clf", "=", "KMeans", "(", "n_clusters", "=", "n", ")", "clf", ".", "fit", "(", "arr", ")", "classes", "=", "clf", ".", "predict", "(", "arr", ")", "return", "classes" ]
Return an array of K-Means cluster classes for an array of `shapely.geometry.Point` objects.
[ "Return", "an", "array", "of", "K", "-", "Means", "cluster", "classes", "for", "an", "array", "of", "shapely", ".", "geometry", ".", "Point", "objects", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L23-L31
train
ResidentMario/geoplot
geoplot/utils.py
gaussian_polygons
def gaussian_polygons(points, n=10): """ Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point` objects. """ gdf = gpd.GeoDataFrame(data={'cluster_number': classify_clusters(points, n=n)}, geometry=points) polygons = [] for i in range(n): sel_points = gdf[gdf['cluster_number'] == i].geometry polygons.append(shapely.geometry.MultiPoint([(p.x, p.y) for p in sel_points]).convex_hull) polygons = [p for p in polygons if (not isinstance(p, shapely.geometry.Point)) and (not isinstance(p, shapely.geometry.LineString))] return gpd.GeoSeries(polygons)
python
def gaussian_polygons(points, n=10): """ Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point` objects. """ gdf = gpd.GeoDataFrame(data={'cluster_number': classify_clusters(points, n=n)}, geometry=points) polygons = [] for i in range(n): sel_points = gdf[gdf['cluster_number'] == i].geometry polygons.append(shapely.geometry.MultiPoint([(p.x, p.y) for p in sel_points]).convex_hull) polygons = [p for p in polygons if (not isinstance(p, shapely.geometry.Point)) and (not isinstance(p, shapely.geometry.LineString))] return gpd.GeoSeries(polygons)
[ "def", "gaussian_polygons", "(", "points", ",", "n", "=", "10", ")", ":", "gdf", "=", "gpd", ".", "GeoDataFrame", "(", "data", "=", "{", "'cluster_number'", ":", "classify_clusters", "(", "points", ",", "n", "=", "n", ")", "}", ",", "geometry", "=", "points", ")", "polygons", "=", "[", "]", "for", "i", "in", "range", "(", "n", ")", ":", "sel_points", "=", "gdf", "[", "gdf", "[", "'cluster_number'", "]", "==", "i", "]", ".", "geometry", "polygons", ".", "append", "(", "shapely", ".", "geometry", ".", "MultiPoint", "(", "[", "(", "p", ".", "x", ",", "p", ".", "y", ")", "for", "p", "in", "sel_points", "]", ")", ".", "convex_hull", ")", "polygons", "=", "[", "p", "for", "p", "in", "polygons", "if", "(", "not", "isinstance", "(", "p", ",", "shapely", ".", "geometry", ".", "Point", ")", ")", "and", "(", "not", "isinstance", "(", "p", ",", "shapely", ".", "geometry", ".", "LineString", ")", ")", "]", "return", "gpd", ".", "GeoSeries", "(", "polygons", ")" ]
Returns an array of approximately `n` `shapely.geometry.Polygon` objects for an array of `shapely.geometry.Point` objects.
[ "Returns", "an", "array", "of", "approximately", "n", "shapely", ".", "geometry", ".", "Polygon", "objects", "for", "an", "array", "of", "shapely", ".", "geometry", ".", "Point", "objects", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L34-L46
train
ResidentMario/geoplot
geoplot/utils.py
gaussian_multi_polygons
def gaussian_multi_polygons(points, n=10): """ Returns an array of approximately `n` `shapely.geometry.MultiPolygon` objects for an array of `shapely.geometry.Point` objects. """ polygons = gaussian_polygons(points, n*2) # Randomly stitch them together. polygon_pairs = [shapely.geometry.MultiPolygon(list(pair)) for pair in np.array_split(polygons.values, n)] return gpd.GeoSeries(polygon_pairs)
python
def gaussian_multi_polygons(points, n=10): """ Returns an array of approximately `n` `shapely.geometry.MultiPolygon` objects for an array of `shapely.geometry.Point` objects. """ polygons = gaussian_polygons(points, n*2) # Randomly stitch them together. polygon_pairs = [shapely.geometry.MultiPolygon(list(pair)) for pair in np.array_split(polygons.values, n)] return gpd.GeoSeries(polygon_pairs)
[ "def", "gaussian_multi_polygons", "(", "points", ",", "n", "=", "10", ")", ":", "polygons", "=", "gaussian_polygons", "(", "points", ",", "n", "*", "2", ")", "# Randomly stitch them together.", "polygon_pairs", "=", "[", "shapely", ".", "geometry", ".", "MultiPolygon", "(", "list", "(", "pair", ")", ")", "for", "pair", "in", "np", ".", "array_split", "(", "polygons", ".", "values", ",", "n", ")", "]", "return", "gpd", ".", "GeoSeries", "(", "polygon_pairs", ")" ]
Returns an array of approximately `n` `shapely.geometry.MultiPolygon` objects for an array of `shapely.geometry.Point` objects.
[ "Returns", "an", "array", "of", "approximately", "n", "shapely", ".", "geometry", ".", "MultiPolygon", "objects", "for", "an", "array", "of", "shapely", ".", "geometry", ".", "Point", "objects", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L49-L57
train
ResidentMario/geoplot
geoplot/utils.py
uniform_random_global_points
def uniform_random_global_points(n=100): """ Returns an array of `n` uniformally distributed `shapely.geometry.Point` objects. Points are coordinates distributed equivalently across the Earth's surface. """ xs = np.random.uniform(-180, 180, n) ys = np.random.uniform(-90, 90, n) return [shapely.geometry.Point(x, y) for x, y in zip(xs, ys)]
python
def uniform_random_global_points(n=100): """ Returns an array of `n` uniformally distributed `shapely.geometry.Point` objects. Points are coordinates distributed equivalently across the Earth's surface. """ xs = np.random.uniform(-180, 180, n) ys = np.random.uniform(-90, 90, n) return [shapely.geometry.Point(x, y) for x, y in zip(xs, ys)]
[ "def", "uniform_random_global_points", "(", "n", "=", "100", ")", ":", "xs", "=", "np", ".", "random", ".", "uniform", "(", "-", "180", ",", "180", ",", "n", ")", "ys", "=", "np", ".", "random", ".", "uniform", "(", "-", "90", ",", "90", ",", "n", ")", "return", "[", "shapely", ".", "geometry", ".", "Point", "(", "x", ",", "y", ")", "for", "x", ",", "y", "in", "zip", "(", "xs", ",", "ys", ")", "]" ]
Returns an array of `n` uniformally distributed `shapely.geometry.Point` objects. Points are coordinates distributed equivalently across the Earth's surface.
[ "Returns", "an", "array", "of", "n", "uniformally", "distributed", "shapely", ".", "geometry", ".", "Point", "objects", ".", "Points", "are", "coordinates", "distributed", "equivalently", "across", "the", "Earth", "s", "surface", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L60-L67
train
ResidentMario/geoplot
geoplot/utils.py
uniform_random_global_network
def uniform_random_global_network(loc=2000, scale=250, n=100): """ Returns an array of `n` uniformally randomly distributed `shapely.geometry.Point` objects. """ arr = (np.random.normal(loc, scale, n)).astype(int) return pd.DataFrame(data={'mock_variable': arr, 'from': uniform_random_global_points(n), 'to': uniform_random_global_points(n)})
python
def uniform_random_global_network(loc=2000, scale=250, n=100): """ Returns an array of `n` uniformally randomly distributed `shapely.geometry.Point` objects. """ arr = (np.random.normal(loc, scale, n)).astype(int) return pd.DataFrame(data={'mock_variable': arr, 'from': uniform_random_global_points(n), 'to': uniform_random_global_points(n)})
[ "def", "uniform_random_global_network", "(", "loc", "=", "2000", ",", "scale", "=", "250", ",", "n", "=", "100", ")", ":", "arr", "=", "(", "np", ".", "random", ".", "normal", "(", "loc", ",", "scale", ",", "n", ")", ")", ".", "astype", "(", "int", ")", "return", "pd", ".", "DataFrame", "(", "data", "=", "{", "'mock_variable'", ":", "arr", ",", "'from'", ":", "uniform_random_global_points", "(", "n", ")", ",", "'to'", ":", "uniform_random_global_points", "(", "n", ")", "}", ")" ]
Returns an array of `n` uniformally randomly distributed `shapely.geometry.Point` objects.
[ "Returns", "an", "array", "of", "n", "uniformally", "randomly", "distributed", "shapely", ".", "geometry", ".", "Point", "objects", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/utils.py#L70-L77
train
ResidentMario/geoplot
geoplot/quad.py
subpartition
def subpartition(quadtree, nmin, nmax): """ Recursive core of the ``QuadTree.partition`` method. Just five lines of code, amazingly. Parameters ---------- quadtree : QuadTree object instance The QuadTree object instance being partitioned. nmin : int The splitting threshold. If this is not met this method will return a listing containing the root tree alone. Returns ------- A (probably nested) list of QuadTree object instances containing a number of points respecting the threshold parameter. """ subtrees = quadtree.split() if quadtree.n > nmax: return [q.partition(nmin, nmax) for q in subtrees] elif any([t.n < nmin for t in subtrees]): return [quadtree] else: return [q.partition(nmin, nmax) for q in subtrees]
python
def subpartition(quadtree, nmin, nmax): """ Recursive core of the ``QuadTree.partition`` method. Just five lines of code, amazingly. Parameters ---------- quadtree : QuadTree object instance The QuadTree object instance being partitioned. nmin : int The splitting threshold. If this is not met this method will return a listing containing the root tree alone. Returns ------- A (probably nested) list of QuadTree object instances containing a number of points respecting the threshold parameter. """ subtrees = quadtree.split() if quadtree.n > nmax: return [q.partition(nmin, nmax) for q in subtrees] elif any([t.n < nmin for t in subtrees]): return [quadtree] else: return [q.partition(nmin, nmax) for q in subtrees]
[ "def", "subpartition", "(", "quadtree", ",", "nmin", ",", "nmax", ")", ":", "subtrees", "=", "quadtree", ".", "split", "(", ")", "if", "quadtree", ".", "n", ">", "nmax", ":", "return", "[", "q", ".", "partition", "(", "nmin", ",", "nmax", ")", "for", "q", "in", "subtrees", "]", "elif", "any", "(", "[", "t", ".", "n", "<", "nmin", "for", "t", "in", "subtrees", "]", ")", ":", "return", "[", "quadtree", "]", "else", ":", "return", "[", "q", ".", "partition", "(", "nmin", ",", "nmax", ")", "for", "q", "in", "subtrees", "]" ]
Recursive core of the ``QuadTree.partition`` method. Just five lines of code, amazingly. Parameters ---------- quadtree : QuadTree object instance The QuadTree object instance being partitioned. nmin : int The splitting threshold. If this is not met this method will return a listing containing the root tree alone. Returns ------- A (probably nested) list of QuadTree object instances containing a number of points respecting the threshold parameter.
[ "Recursive", "core", "of", "the", "QuadTree", ".", "partition", "method", ".", "Just", "five", "lines", "of", "code", "amazingly", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/quad.py#L116-L138
train
ResidentMario/geoplot
geoplot/quad.py
QuadTree.split
def split(self): """ Splits the current QuadTree instance four ways through the midpoint. Returns ------- A list of four "sub" QuadTree instances, corresponding with the first, second, third, and fourth quartiles, respectively. """ # TODO: Investigate why a small number of entries are lost every time this method is run. min_x, max_x, min_y, max_y = self.bounds mid_x, mid_y = (min_x + max_x) / 2, (min_y + max_y) / 2 q1 = (min_x, mid_x, mid_y, max_y) q2 = (min_x, mid_x, min_y, mid_y) q3 = (mid_x, max_x, mid_y, max_y) q4 = (mid_x, max_x, min_y, mid_y) return [QuadTree(self.data, bounds=q1), QuadTree(self.data, bounds=q2), QuadTree(self.data, bounds=q3), QuadTree(self.data, bounds=q4)]
python
def split(self): """ Splits the current QuadTree instance four ways through the midpoint. Returns ------- A list of four "sub" QuadTree instances, corresponding with the first, second, third, and fourth quartiles, respectively. """ # TODO: Investigate why a small number of entries are lost every time this method is run. min_x, max_x, min_y, max_y = self.bounds mid_x, mid_y = (min_x + max_x) / 2, (min_y + max_y) / 2 q1 = (min_x, mid_x, mid_y, max_y) q2 = (min_x, mid_x, min_y, mid_y) q3 = (mid_x, max_x, mid_y, max_y) q4 = (mid_x, max_x, min_y, mid_y) return [QuadTree(self.data, bounds=q1), QuadTree(self.data, bounds=q2), QuadTree(self.data, bounds=q3), QuadTree(self.data, bounds=q4)]
[ "def", "split", "(", "self", ")", ":", "# TODO: Investigate why a small number of entries are lost every time this method is run.", "min_x", ",", "max_x", ",", "min_y", ",", "max_y", "=", "self", ".", "bounds", "mid_x", ",", "mid_y", "=", "(", "min_x", "+", "max_x", ")", "/", "2", ",", "(", "min_y", "+", "max_y", ")", "/", "2", "q1", "=", "(", "min_x", ",", "mid_x", ",", "mid_y", ",", "max_y", ")", "q2", "=", "(", "min_x", ",", "mid_x", ",", "min_y", ",", "mid_y", ")", "q3", "=", "(", "mid_x", ",", "max_x", ",", "mid_y", ",", "max_y", ")", "q4", "=", "(", "mid_x", ",", "max_x", ",", "min_y", ",", "mid_y", ")", "return", "[", "QuadTree", "(", "self", ".", "data", ",", "bounds", "=", "q1", ")", ",", "QuadTree", "(", "self", ".", "data", ",", "bounds", "=", "q2", ")", ",", "QuadTree", "(", "self", ".", "data", ",", "bounds", "=", "q3", ")", ",", "QuadTree", "(", "self", ".", "data", ",", "bounds", "=", "q4", ")", "]" ]
Splits the current QuadTree instance four ways through the midpoint. Returns ------- A list of four "sub" QuadTree instances, corresponding with the first, second, third, and fourth quartiles, respectively.
[ "Splits", "the", "current", "QuadTree", "instance", "four", "ways", "through", "the", "midpoint", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/quad.py#L71-L88
train
ResidentMario/geoplot
geoplot/quad.py
QuadTree.partition
def partition(self, nmin, nmax): """ This method call decomposes a QuadTree instances into a list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh`` points. Parameters ---------- thresh : int The minimum number of points per partition. Care should be taken not to set this parameter to be too low, as in large datasets a small cluster of highly adjacent points may result in a number of sub-recursive splits possibly in excess of Python's global recursion limit. Returns ------- partitions : list of QuadTree object instances A list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh`` points. """ if self.n < nmin: return [self] else: ret = subpartition(self, nmin, nmax) return flatten(ret)
python
def partition(self, nmin, nmax): """ This method call decomposes a QuadTree instances into a list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh`` points. Parameters ---------- thresh : int The minimum number of points per partition. Care should be taken not to set this parameter to be too low, as in large datasets a small cluster of highly adjacent points may result in a number of sub-recursive splits possibly in excess of Python's global recursion limit. Returns ------- partitions : list of QuadTree object instances A list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh`` points. """ if self.n < nmin: return [self] else: ret = subpartition(self, nmin, nmax) return flatten(ret)
[ "def", "partition", "(", "self", ",", "nmin", ",", "nmax", ")", ":", "if", "self", ".", "n", "<", "nmin", ":", "return", "[", "self", "]", "else", ":", "ret", "=", "subpartition", "(", "self", ",", "nmin", ",", "nmax", ")", "return", "flatten", "(", "ret", ")" ]
This method call decomposes a QuadTree instances into a list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh`` points. Parameters ---------- thresh : int The minimum number of points per partition. Care should be taken not to set this parameter to be too low, as in large datasets a small cluster of highly adjacent points may result in a number of sub-recursive splits possibly in excess of Python's global recursion limit. Returns ------- partitions : list of QuadTree object instances A list of sub- QuadTree instances which are the smallest possible geospatial "buckets", given the current splitting rules, containing at least ``thresh`` points.
[ "This", "method", "call", "decomposes", "a", "QuadTree", "instances", "into", "a", "list", "of", "sub", "-", "QuadTree", "instances", "which", "are", "the", "smallest", "possible", "geospatial", "buckets", "given", "the", "current", "splitting", "rules", "containing", "at", "least", "thresh", "points", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/quad.py#L90-L113
train
ResidentMario/geoplot
docs/examples/nyc-parking-tickets.py
plot_state_to_ax
def plot_state_to_ax(state, ax): """Reusable plotting wrapper.""" gplt.choropleth(tickets.set_index('id').loc[:, [state, 'geometry']], hue=state, projection=gcrs.AlbersEqualArea(), cmap='Blues', linewidth=0.0, ax=ax) gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), edgecolor='black', linewidth=0.5, ax=ax)
python
def plot_state_to_ax(state, ax): """Reusable plotting wrapper.""" gplt.choropleth(tickets.set_index('id').loc[:, [state, 'geometry']], hue=state, projection=gcrs.AlbersEqualArea(), cmap='Blues', linewidth=0.0, ax=ax) gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), edgecolor='black', linewidth=0.5, ax=ax)
[ "def", "plot_state_to_ax", "(", "state", ",", "ax", ")", ":", "gplt", ".", "choropleth", "(", "tickets", ".", "set_index", "(", "'id'", ")", ".", "loc", "[", ":", ",", "[", "state", ",", "'geometry'", "]", "]", ",", "hue", "=", "state", ",", "projection", "=", "gcrs", ".", "AlbersEqualArea", "(", ")", ",", "cmap", "=", "'Blues'", ",", "linewidth", "=", "0.0", ",", "ax", "=", "ax", ")", "gplt", ".", "polyplot", "(", "boroughs", ",", "projection", "=", "gcrs", ".", "AlbersEqualArea", "(", ")", ",", "edgecolor", "=", "'black'", ",", "linewidth", "=", "0.5", ",", "ax", "=", "ax", ")" ]
Reusable plotting wrapper.
[ "Reusable", "plotting", "wrapper", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/docs/examples/nyc-parking-tickets.py#L19-L25
train
ResidentMario/geoplot
geoplot/geoplot.py
polyplot
def polyplot(df, projection=None, extent=None, figsize=(8, 6), ax=None, edgecolor='black', facecolor='None', **kwargs): """ Trivial polygonal plot. Parameters ---------- df : GeoDataFrame The data being plotted. projection : geoplot.crs object instance, optional A geographic projection. For more information refer to `the tutorial page on projections <https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_. extent : None or (minx, maxx, miny, maxy), optional Used to control plot x-axis and y-axis limits manually. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. Defaults to (8, 6), the ``matplotlib`` default global. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. ax : AxesSubplot or GeoAxesSubplot instance, optional A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis. kwargs: dict, optional Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. Returns ------- ``AxesSubplot`` or ``GeoAxesSubplot`` The plot axis Examples -------- The polyplot can be used to draw simple, unembellished polygons. A trivial example can be created with just a geometry and, optionally, a projection. .. code-block:: python import geoplot as gplt import geoplot.crs as gcrs gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) .. image:: ../figures/polyplot/polyplot-initial.png However, note that ``polyplot`` is mainly intended to be used in concert with other plot types. .. code-block:: python ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) gplt.pointplot(collisions[collisions['BOROUGH'].notnull()], projection=gcrs.AlbersEqualArea(), hue='BOROUGH', categorical=True, legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'}, ax=ax) .. image:: ../figures/polyplot/polyplot-stacked.png Additional keyword arguments are passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. .. code-block:: python ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), linewidth=0, facecolor='lightgray') .. image:: ../figures/polyplot/polyplot-kwargs.png """ # Initialize the figure. fig = _init_figure(ax, figsize) if projection: # Properly set up the projection. projection = projection.load(df, { 'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])), 'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid])) }) # Set up the axis. if not ax: ax = plt.subplot(111, projection=projection) else: if not ax: ax = plt.gca() # Clean up patches. _lay_out_axes(ax, projection) # Immediately return if input geometry is empty. if len(df.geometry) == 0: return ax # Set extent. extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior) _set_extent(ax, projection, extent, extrema) # Finally we draw the features. if projection: for geom in df.geometry: features = ShapelyFeature([geom], ccrs.PlateCarree()) ax.add_feature(features, facecolor=facecolor, edgecolor=edgecolor, **kwargs) else: for geom in df.geometry: try: # Duck test for MultiPolygon. for subgeom in geom: feature = descartes.PolygonPatch(subgeom, facecolor=facecolor, edgecolor=edgecolor, **kwargs) ax.add_patch(feature) except (TypeError, AssertionError): # Shapely Polygon. feature = descartes.PolygonPatch(geom, facecolor=facecolor, edgecolor=edgecolor, **kwargs) ax.add_patch(feature) return ax
python
def polyplot(df, projection=None, extent=None, figsize=(8, 6), ax=None, edgecolor='black', facecolor='None', **kwargs): """ Trivial polygonal plot. Parameters ---------- df : GeoDataFrame The data being plotted. projection : geoplot.crs object instance, optional A geographic projection. For more information refer to `the tutorial page on projections <https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_. extent : None or (minx, maxx, miny, maxy), optional Used to control plot x-axis and y-axis limits manually. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. Defaults to (8, 6), the ``matplotlib`` default global. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. ax : AxesSubplot or GeoAxesSubplot instance, optional A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis. kwargs: dict, optional Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. Returns ------- ``AxesSubplot`` or ``GeoAxesSubplot`` The plot axis Examples -------- The polyplot can be used to draw simple, unembellished polygons. A trivial example can be created with just a geometry and, optionally, a projection. .. code-block:: python import geoplot as gplt import geoplot.crs as gcrs gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) .. image:: ../figures/polyplot/polyplot-initial.png However, note that ``polyplot`` is mainly intended to be used in concert with other plot types. .. code-block:: python ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) gplt.pointplot(collisions[collisions['BOROUGH'].notnull()], projection=gcrs.AlbersEqualArea(), hue='BOROUGH', categorical=True, legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'}, ax=ax) .. image:: ../figures/polyplot/polyplot-stacked.png Additional keyword arguments are passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. .. code-block:: python ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), linewidth=0, facecolor='lightgray') .. image:: ../figures/polyplot/polyplot-kwargs.png """ # Initialize the figure. fig = _init_figure(ax, figsize) if projection: # Properly set up the projection. projection = projection.load(df, { 'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])), 'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid])) }) # Set up the axis. if not ax: ax = plt.subplot(111, projection=projection) else: if not ax: ax = plt.gca() # Clean up patches. _lay_out_axes(ax, projection) # Immediately return if input geometry is empty. if len(df.geometry) == 0: return ax # Set extent. extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior) _set_extent(ax, projection, extent, extrema) # Finally we draw the features. if projection: for geom in df.geometry: features = ShapelyFeature([geom], ccrs.PlateCarree()) ax.add_feature(features, facecolor=facecolor, edgecolor=edgecolor, **kwargs) else: for geom in df.geometry: try: # Duck test for MultiPolygon. for subgeom in geom: feature = descartes.PolygonPatch(subgeom, facecolor=facecolor, edgecolor=edgecolor, **kwargs) ax.add_patch(feature) except (TypeError, AssertionError): # Shapely Polygon. feature = descartes.PolygonPatch(geom, facecolor=facecolor, edgecolor=edgecolor, **kwargs) ax.add_patch(feature) return ax
[ "def", "polyplot", "(", "df", ",", "projection", "=", "None", ",", "extent", "=", "None", ",", "figsize", "=", "(", "8", ",", "6", ")", ",", "ax", "=", "None", ",", "edgecolor", "=", "'black'", ",", "facecolor", "=", "'None'", ",", "*", "*", "kwargs", ")", ":", "# Initialize the figure.", "fig", "=", "_init_figure", "(", "ax", ",", "figsize", ")", "if", "projection", ":", "# Properly set up the projection.", "projection", "=", "projection", ".", "load", "(", "df", ",", "{", "'central_longitude'", ":", "lambda", "df", ":", "np", ".", "mean", "(", "np", ".", "array", "(", "[", "p", ".", "x", "for", "p", "in", "df", ".", "geometry", ".", "centroid", "]", ")", ")", ",", "'central_latitude'", ":", "lambda", "df", ":", "np", ".", "mean", "(", "np", ".", "array", "(", "[", "p", ".", "y", "for", "p", "in", "df", ".", "geometry", ".", "centroid", "]", ")", ")", "}", ")", "# Set up the axis.", "if", "not", "ax", ":", "ax", "=", "plt", ".", "subplot", "(", "111", ",", "projection", "=", "projection", ")", "else", ":", "if", "not", "ax", ":", "ax", "=", "plt", ".", "gca", "(", ")", "# Clean up patches.", "_lay_out_axes", "(", "ax", ",", "projection", ")", "# Immediately return if input geometry is empty.", "if", "len", "(", "df", ".", "geometry", ")", "==", "0", ":", "return", "ax", "# Set extent.", "extrema", "=", "_get_envelopes_min_maxes", "(", "df", ".", "geometry", ".", "envelope", ".", "exterior", ")", "_set_extent", "(", "ax", ",", "projection", ",", "extent", ",", "extrema", ")", "# Finally we draw the features.", "if", "projection", ":", "for", "geom", "in", "df", ".", "geometry", ":", "features", "=", "ShapelyFeature", "(", "[", "geom", "]", ",", "ccrs", ".", "PlateCarree", "(", ")", ")", "ax", ".", "add_feature", "(", "features", ",", "facecolor", "=", "facecolor", ",", "edgecolor", "=", "edgecolor", ",", "*", "*", "kwargs", ")", "else", ":", "for", "geom", "in", "df", ".", "geometry", ":", "try", ":", "# Duck test for MultiPolygon.", "for", "subgeom", "in", "geom", ":", "feature", "=", "descartes", ".", "PolygonPatch", "(", "subgeom", ",", "facecolor", "=", "facecolor", ",", "edgecolor", "=", "edgecolor", ",", "*", "*", "kwargs", ")", "ax", ".", "add_patch", "(", "feature", ")", "except", "(", "TypeError", ",", "AssertionError", ")", ":", "# Shapely Polygon.", "feature", "=", "descartes", ".", "PolygonPatch", "(", "geom", ",", "facecolor", "=", "facecolor", ",", "edgecolor", "=", "edgecolor", ",", "*", "*", "kwargs", ")", "ax", ".", "add_patch", "(", "feature", ")", "return", "ax" ]
Trivial polygonal plot. Parameters ---------- df : GeoDataFrame The data being plotted. projection : geoplot.crs object instance, optional A geographic projection. For more information refer to `the tutorial page on projections <https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_. extent : None or (minx, maxx, miny, maxy), optional Used to control plot x-axis and y-axis limits manually. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. Defaults to (8, 6), the ``matplotlib`` default global. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. ax : AxesSubplot or GeoAxesSubplot instance, optional A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis. kwargs: dict, optional Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. Returns ------- ``AxesSubplot`` or ``GeoAxesSubplot`` The plot axis Examples -------- The polyplot can be used to draw simple, unembellished polygons. A trivial example can be created with just a geometry and, optionally, a projection. .. code-block:: python import geoplot as gplt import geoplot.crs as gcrs gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) .. image:: ../figures/polyplot/polyplot-initial.png However, note that ``polyplot`` is mainly intended to be used in concert with other plot types. .. code-block:: python ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea()) gplt.pointplot(collisions[collisions['BOROUGH'].notnull()], projection=gcrs.AlbersEqualArea(), hue='BOROUGH', categorical=True, legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'}, ax=ax) .. image:: ../figures/polyplot/polyplot-stacked.png Additional keyword arguments are passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. .. code-block:: python ax = gplt.polyplot(boroughs, projection=gcrs.AlbersEqualArea(), linewidth=0, facecolor='lightgray') .. image:: ../figures/polyplot/polyplot-kwargs.png
[ "Trivial", "polygonal", "plot", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L346-L462
train
ResidentMario/geoplot
geoplot/geoplot.py
choropleth
def choropleth(df, projection=None, hue=None, scheme=None, k=5, cmap='Set1', categorical=False, vmin=None, vmax=None, legend=False, legend_kwargs=None, legend_labels=None, extent=None, figsize=(8, 6), ax=None, **kwargs): """ Area aggregation plot. Parameters ---------- df : GeoDataFrame The data being plotted. projection : geoplot.crs object instance, optional A geographic projection. For more information refer to `the tutorial page on projections <https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_. hue : None, Series, GeoSeries, iterable, or str, optional Applies a colormap to the output points. categorical : boolean, optional Set to ``True`` if ``hue`` references a categorical variable, and ``False`` (the default) otherwise. Ignored if ``hue`` is left unspecified. scheme : None or {"quantiles"|"equal_interval"|"fisher_Jenks"}, optional Controls how the colormap bin edges are determined. Ignored if ``hue`` is left unspecified. k : int or None, optional Ignored if ``hue`` is left unspecified. Otherwise, if ``categorical`` is False, controls how many colors to use (5 is the default). If set to ``None``, a continuous colormap will be used. cmap : matplotlib color, optional The `matplotlib colormap <http://matplotlib.org/examples/color/colormaps_reference.html>`_ to be used. Ignored if ``hue`` is left unspecified. vmin : float, optional Values below this level will be colored the same threshold value. Defaults to the dataset minimum. Ignored if ``hue`` is left unspecified. vmax : float, optional Values above this level will be colored the same threshold value. Defaults to the dataset maximum. Ignored if ``hue`` is left unspecified. legend : boolean, optional Whether or not to include a legend. Ignored if neither a ``hue`` nor a ``scale`` is specified. legend_values : list, optional The values to use in the legend. Defaults to equal intervals. For more information see `the Gallery demo <https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_. legend_labels : list, optional The names to use in the legend. Defaults to the variable values. For more information see `the Gallery demo <https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_. legend_kwargs : dict, optional Keyword arguments to be passed to `the underlying legend <http://matplotlib.org/users/legend_guide.html>`_. extent : None or (minx, maxx, miny, maxy), optional Used to control plot x-axis and y-axis limits manually. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. ax : AxesSubplot or GeoAxesSubplot instance, optional A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis. kwargs: dict, optional Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. Returns ------- ``AxesSubplot`` or ``GeoAxesSubplot`` The plot axis Examples -------- A choropleth takes observations that have been aggregated on some meaningful polygonal level (e.g. census tract, state, country, or continent) and displays the data to the reader using color. It is a well-known plot type, and likeliest the most general-purpose and well-known of the specifically spatial plot types. It is especially powerful when combined with meaningful or actionable aggregation areas; if no such aggregations exist, or the aggregations you have access to are mostly incidental, its value is more limited. The ``choropleth`` requires a series of enclosed areas consisting of ``shapely`` ``Polygon`` or ``MultiPolygon`` entities, and a set of data about them that you would like to express in color. A basic choropleth requires geometry, a ``hue`` variable, and, optionally, a projection. .. code-block:: python import geoplot as gplt import geoplot.crs as gcrs gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree()) .. image:: ../figures/choropleth/choropleth-initial.png Change the colormap with the ``cmap`` parameter. .. code-block:: python gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree(), cmap='Blues') .. image:: ../figures/choropleth/choropleth-cmap.png If your variable of interest is already `categorical <http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_, you can specify ``categorical=True`` to use the labels in your dataset directly. To add a legend, specify ``legend``. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, legend=True) .. image:: ../figures/choropleth/choropleth-legend.png Keyword arguments can be passed to the legend using the ``legend_kwargs`` argument. These arguments will be passed to the underlying ``matplotlib.legend.Legend`` instance (`ref <http://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend>`_). The ``loc`` and ``bbox_to_anchor`` parameters are particularly useful for positioning the legend. Other additional arguments will be passed to the underlying ``matplotlib`` `scatter plot <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`_. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, legend=True, legend_kwargs={'loc': 'upper left'}) .. image:: ../figures/choropleth/choropleth-legend-kwargs.png Additional arguments not in the method signature will be passed as keyword parameters to the underlying `matplotlib Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, linewidth=0) .. image:: ../figures/choropleth/choropleth-kwargs.png Choropleths default to splitting the data into five buckets with approximately equal numbers of observations in them. Change the number of buckets by specifying ``k``. Or, to use a continuous colormap, specify ``k=None``. In this case a colorbar legend will be used. .. code-block:: python gplt.choropleth(polydata, hue='latdep', cmap='Blues', k=None, legend=True, projection=gcrs.PlateCarree()) .. image:: ../figures/choropleth/choropleth-k-none.png The ``choropleth`` binning methodology is controlled using by `scheme`` parameter. The default is ``quantile``, which bins observations into classes of different sizes but the same numbers of observations. ``equal_interval`` will creates bins that are the same size, but potentially containing different numbers of observations. The more complicated ``fisher_jenks`` scheme is an intermediate between the two. .. code-block:: python gplt.choropleth(census_tracts, hue='mock_data', projection=gcrs.AlbersEqualArea(), legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'}, scheme='equal_interval') .. image:: ../figures/choropleth/choropleth-scheme.png """ # Initialize the figure. fig = _init_figure(ax, figsize) if projection: projection = projection.load(df, { 'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])), 'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid])) }) # Set up the axis. if not ax: ax = plt.subplot(111, projection=projection) else: if not ax: ax = plt.gca() # Clean up patches. _lay_out_axes(ax, projection) # Immediately return if input geometry is empty. if len(df.geometry) == 0: return ax # Set extent. extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior) _set_extent(ax, projection, extent, extrema) # Format the data to be displayed for input. hue = _validate_hue(df, hue) if hue is None: raise ValueError("No 'hue' specified.") # Generate the coloring information, if needed. Follows one of two schemes, categorical or continuous, # based on whether or not ``k`` is specified (``hue`` must be specified for either to work). if k is not None: # Categorical colormap code path. # Validate buckets. categorical, k, scheme = _validate_buckets(categorical, k, scheme) if hue is not None: cmap, categories, hue_values = _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax) colors = [cmap.to_rgba(v) for v in hue_values] # Add a legend, if appropriate. if legend: _paint_hue_legend(ax, categories, cmap, legend_labels, legend_kwargs) else: colors = ['steelblue']*len(df) elif k is None and hue is not None: # Continuous colormap code path. hue_values = hue cmap = _continuous_colormap(hue_values, cmap, vmin, vmax) colors = [cmap.to_rgba(v) for v in hue_values] # Add a legend, if appropriate. if legend: _paint_colorbar_legend(ax, hue_values, cmap, legend_kwargs) # Draw the features. if projection: for color, geom in zip(colors, df.geometry): features = ShapelyFeature([geom], ccrs.PlateCarree()) ax.add_feature(features, facecolor=color, **kwargs) else: for color, geom in zip(colors, df.geometry): try: # Duck test for MultiPolygon. for subgeom in geom: feature = descartes.PolygonPatch(subgeom, facecolor=color, **kwargs) ax.add_patch(feature) except (TypeError, AssertionError): # Shapely Polygon. feature = descartes.PolygonPatch(geom, facecolor=color, **kwargs) ax.add_patch(feature) return ax
python
def choropleth(df, projection=None, hue=None, scheme=None, k=5, cmap='Set1', categorical=False, vmin=None, vmax=None, legend=False, legend_kwargs=None, legend_labels=None, extent=None, figsize=(8, 6), ax=None, **kwargs): """ Area aggregation plot. Parameters ---------- df : GeoDataFrame The data being plotted. projection : geoplot.crs object instance, optional A geographic projection. For more information refer to `the tutorial page on projections <https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_. hue : None, Series, GeoSeries, iterable, or str, optional Applies a colormap to the output points. categorical : boolean, optional Set to ``True`` if ``hue`` references a categorical variable, and ``False`` (the default) otherwise. Ignored if ``hue`` is left unspecified. scheme : None or {"quantiles"|"equal_interval"|"fisher_Jenks"}, optional Controls how the colormap bin edges are determined. Ignored if ``hue`` is left unspecified. k : int or None, optional Ignored if ``hue`` is left unspecified. Otherwise, if ``categorical`` is False, controls how many colors to use (5 is the default). If set to ``None``, a continuous colormap will be used. cmap : matplotlib color, optional The `matplotlib colormap <http://matplotlib.org/examples/color/colormaps_reference.html>`_ to be used. Ignored if ``hue`` is left unspecified. vmin : float, optional Values below this level will be colored the same threshold value. Defaults to the dataset minimum. Ignored if ``hue`` is left unspecified. vmax : float, optional Values above this level will be colored the same threshold value. Defaults to the dataset maximum. Ignored if ``hue`` is left unspecified. legend : boolean, optional Whether or not to include a legend. Ignored if neither a ``hue`` nor a ``scale`` is specified. legend_values : list, optional The values to use in the legend. Defaults to equal intervals. For more information see `the Gallery demo <https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_. legend_labels : list, optional The names to use in the legend. Defaults to the variable values. For more information see `the Gallery demo <https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_. legend_kwargs : dict, optional Keyword arguments to be passed to `the underlying legend <http://matplotlib.org/users/legend_guide.html>`_. extent : None or (minx, maxx, miny, maxy), optional Used to control plot x-axis and y-axis limits manually. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. ax : AxesSubplot or GeoAxesSubplot instance, optional A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis. kwargs: dict, optional Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. Returns ------- ``AxesSubplot`` or ``GeoAxesSubplot`` The plot axis Examples -------- A choropleth takes observations that have been aggregated on some meaningful polygonal level (e.g. census tract, state, country, or continent) and displays the data to the reader using color. It is a well-known plot type, and likeliest the most general-purpose and well-known of the specifically spatial plot types. It is especially powerful when combined with meaningful or actionable aggregation areas; if no such aggregations exist, or the aggregations you have access to are mostly incidental, its value is more limited. The ``choropleth`` requires a series of enclosed areas consisting of ``shapely`` ``Polygon`` or ``MultiPolygon`` entities, and a set of data about them that you would like to express in color. A basic choropleth requires geometry, a ``hue`` variable, and, optionally, a projection. .. code-block:: python import geoplot as gplt import geoplot.crs as gcrs gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree()) .. image:: ../figures/choropleth/choropleth-initial.png Change the colormap with the ``cmap`` parameter. .. code-block:: python gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree(), cmap='Blues') .. image:: ../figures/choropleth/choropleth-cmap.png If your variable of interest is already `categorical <http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_, you can specify ``categorical=True`` to use the labels in your dataset directly. To add a legend, specify ``legend``. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, legend=True) .. image:: ../figures/choropleth/choropleth-legend.png Keyword arguments can be passed to the legend using the ``legend_kwargs`` argument. These arguments will be passed to the underlying ``matplotlib.legend.Legend`` instance (`ref <http://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend>`_). The ``loc`` and ``bbox_to_anchor`` parameters are particularly useful for positioning the legend. Other additional arguments will be passed to the underlying ``matplotlib`` `scatter plot <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`_. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, legend=True, legend_kwargs={'loc': 'upper left'}) .. image:: ../figures/choropleth/choropleth-legend-kwargs.png Additional arguments not in the method signature will be passed as keyword parameters to the underlying `matplotlib Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, linewidth=0) .. image:: ../figures/choropleth/choropleth-kwargs.png Choropleths default to splitting the data into five buckets with approximately equal numbers of observations in them. Change the number of buckets by specifying ``k``. Or, to use a continuous colormap, specify ``k=None``. In this case a colorbar legend will be used. .. code-block:: python gplt.choropleth(polydata, hue='latdep', cmap='Blues', k=None, legend=True, projection=gcrs.PlateCarree()) .. image:: ../figures/choropleth/choropleth-k-none.png The ``choropleth`` binning methodology is controlled using by `scheme`` parameter. The default is ``quantile``, which bins observations into classes of different sizes but the same numbers of observations. ``equal_interval`` will creates bins that are the same size, but potentially containing different numbers of observations. The more complicated ``fisher_jenks`` scheme is an intermediate between the two. .. code-block:: python gplt.choropleth(census_tracts, hue='mock_data', projection=gcrs.AlbersEqualArea(), legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'}, scheme='equal_interval') .. image:: ../figures/choropleth/choropleth-scheme.png """ # Initialize the figure. fig = _init_figure(ax, figsize) if projection: projection = projection.load(df, { 'central_longitude': lambda df: np.mean(np.array([p.x for p in df.geometry.centroid])), 'central_latitude': lambda df: np.mean(np.array([p.y for p in df.geometry.centroid])) }) # Set up the axis. if not ax: ax = plt.subplot(111, projection=projection) else: if not ax: ax = plt.gca() # Clean up patches. _lay_out_axes(ax, projection) # Immediately return if input geometry is empty. if len(df.geometry) == 0: return ax # Set extent. extrema = _get_envelopes_min_maxes(df.geometry.envelope.exterior) _set_extent(ax, projection, extent, extrema) # Format the data to be displayed for input. hue = _validate_hue(df, hue) if hue is None: raise ValueError("No 'hue' specified.") # Generate the coloring information, if needed. Follows one of two schemes, categorical or continuous, # based on whether or not ``k`` is specified (``hue`` must be specified for either to work). if k is not None: # Categorical colormap code path. # Validate buckets. categorical, k, scheme = _validate_buckets(categorical, k, scheme) if hue is not None: cmap, categories, hue_values = _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax) colors = [cmap.to_rgba(v) for v in hue_values] # Add a legend, if appropriate. if legend: _paint_hue_legend(ax, categories, cmap, legend_labels, legend_kwargs) else: colors = ['steelblue']*len(df) elif k is None and hue is not None: # Continuous colormap code path. hue_values = hue cmap = _continuous_colormap(hue_values, cmap, vmin, vmax) colors = [cmap.to_rgba(v) for v in hue_values] # Add a legend, if appropriate. if legend: _paint_colorbar_legend(ax, hue_values, cmap, legend_kwargs) # Draw the features. if projection: for color, geom in zip(colors, df.geometry): features = ShapelyFeature([geom], ccrs.PlateCarree()) ax.add_feature(features, facecolor=color, **kwargs) else: for color, geom in zip(colors, df.geometry): try: # Duck test for MultiPolygon. for subgeom in geom: feature = descartes.PolygonPatch(subgeom, facecolor=color, **kwargs) ax.add_patch(feature) except (TypeError, AssertionError): # Shapely Polygon. feature = descartes.PolygonPatch(geom, facecolor=color, **kwargs) ax.add_patch(feature) return ax
[ "def", "choropleth", "(", "df", ",", "projection", "=", "None", ",", "hue", "=", "None", ",", "scheme", "=", "None", ",", "k", "=", "5", ",", "cmap", "=", "'Set1'", ",", "categorical", "=", "False", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ",", "legend", "=", "False", ",", "legend_kwargs", "=", "None", ",", "legend_labels", "=", "None", ",", "extent", "=", "None", ",", "figsize", "=", "(", "8", ",", "6", ")", ",", "ax", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Initialize the figure.", "fig", "=", "_init_figure", "(", "ax", ",", "figsize", ")", "if", "projection", ":", "projection", "=", "projection", ".", "load", "(", "df", ",", "{", "'central_longitude'", ":", "lambda", "df", ":", "np", ".", "mean", "(", "np", ".", "array", "(", "[", "p", ".", "x", "for", "p", "in", "df", ".", "geometry", ".", "centroid", "]", ")", ")", ",", "'central_latitude'", ":", "lambda", "df", ":", "np", ".", "mean", "(", "np", ".", "array", "(", "[", "p", ".", "y", "for", "p", "in", "df", ".", "geometry", ".", "centroid", "]", ")", ")", "}", ")", "# Set up the axis.", "if", "not", "ax", ":", "ax", "=", "plt", ".", "subplot", "(", "111", ",", "projection", "=", "projection", ")", "else", ":", "if", "not", "ax", ":", "ax", "=", "plt", ".", "gca", "(", ")", "# Clean up patches.", "_lay_out_axes", "(", "ax", ",", "projection", ")", "# Immediately return if input geometry is empty.", "if", "len", "(", "df", ".", "geometry", ")", "==", "0", ":", "return", "ax", "# Set extent.", "extrema", "=", "_get_envelopes_min_maxes", "(", "df", ".", "geometry", ".", "envelope", ".", "exterior", ")", "_set_extent", "(", "ax", ",", "projection", ",", "extent", ",", "extrema", ")", "# Format the data to be displayed for input.", "hue", "=", "_validate_hue", "(", "df", ",", "hue", ")", "if", "hue", "is", "None", ":", "raise", "ValueError", "(", "\"No 'hue' specified.\"", ")", "# Generate the coloring information, if needed. Follows one of two schemes, categorical or continuous,", "# based on whether or not ``k`` is specified (``hue`` must be specified for either to work).", "if", "k", "is", "not", "None", ":", "# Categorical colormap code path.", "# Validate buckets.", "categorical", ",", "k", ",", "scheme", "=", "_validate_buckets", "(", "categorical", ",", "k", ",", "scheme", ")", "if", "hue", "is", "not", "None", ":", "cmap", ",", "categories", ",", "hue_values", "=", "_discrete_colorize", "(", "categorical", ",", "hue", ",", "scheme", ",", "k", ",", "cmap", ",", "vmin", ",", "vmax", ")", "colors", "=", "[", "cmap", ".", "to_rgba", "(", "v", ")", "for", "v", "in", "hue_values", "]", "# Add a legend, if appropriate.", "if", "legend", ":", "_paint_hue_legend", "(", "ax", ",", "categories", ",", "cmap", ",", "legend_labels", ",", "legend_kwargs", ")", "else", ":", "colors", "=", "[", "'steelblue'", "]", "*", "len", "(", "df", ")", "elif", "k", "is", "None", "and", "hue", "is", "not", "None", ":", "# Continuous colormap code path.", "hue_values", "=", "hue", "cmap", "=", "_continuous_colormap", "(", "hue_values", ",", "cmap", ",", "vmin", ",", "vmax", ")", "colors", "=", "[", "cmap", ".", "to_rgba", "(", "v", ")", "for", "v", "in", "hue_values", "]", "# Add a legend, if appropriate.", "if", "legend", ":", "_paint_colorbar_legend", "(", "ax", ",", "hue_values", ",", "cmap", ",", "legend_kwargs", ")", "# Draw the features.", "if", "projection", ":", "for", "color", ",", "geom", "in", "zip", "(", "colors", ",", "df", ".", "geometry", ")", ":", "features", "=", "ShapelyFeature", "(", "[", "geom", "]", ",", "ccrs", ".", "PlateCarree", "(", ")", ")", "ax", ".", "add_feature", "(", "features", ",", "facecolor", "=", "color", ",", "*", "*", "kwargs", ")", "else", ":", "for", "color", ",", "geom", "in", "zip", "(", "colors", ",", "df", ".", "geometry", ")", ":", "try", ":", "# Duck test for MultiPolygon.", "for", "subgeom", "in", "geom", ":", "feature", "=", "descartes", ".", "PolygonPatch", "(", "subgeom", ",", "facecolor", "=", "color", ",", "*", "*", "kwargs", ")", "ax", ".", "add_patch", "(", "feature", ")", "except", "(", "TypeError", ",", "AssertionError", ")", ":", "# Shapely Polygon.", "feature", "=", "descartes", ".", "PolygonPatch", "(", "geom", ",", "facecolor", "=", "color", ",", "*", "*", "kwargs", ")", "ax", ".", "add_patch", "(", "feature", ")", "return", "ax" ]
Area aggregation plot. Parameters ---------- df : GeoDataFrame The data being plotted. projection : geoplot.crs object instance, optional A geographic projection. For more information refer to `the tutorial page on projections <https://nbviewer.jupyter.org/github/ResidentMario/geoplot/blob/master/notebooks/tutorials/Projections.ipynb>`_. hue : None, Series, GeoSeries, iterable, or str, optional Applies a colormap to the output points. categorical : boolean, optional Set to ``True`` if ``hue`` references a categorical variable, and ``False`` (the default) otherwise. Ignored if ``hue`` is left unspecified. scheme : None or {"quantiles"|"equal_interval"|"fisher_Jenks"}, optional Controls how the colormap bin edges are determined. Ignored if ``hue`` is left unspecified. k : int or None, optional Ignored if ``hue`` is left unspecified. Otherwise, if ``categorical`` is False, controls how many colors to use (5 is the default). If set to ``None``, a continuous colormap will be used. cmap : matplotlib color, optional The `matplotlib colormap <http://matplotlib.org/examples/color/colormaps_reference.html>`_ to be used. Ignored if ``hue`` is left unspecified. vmin : float, optional Values below this level will be colored the same threshold value. Defaults to the dataset minimum. Ignored if ``hue`` is left unspecified. vmax : float, optional Values above this level will be colored the same threshold value. Defaults to the dataset maximum. Ignored if ``hue`` is left unspecified. legend : boolean, optional Whether or not to include a legend. Ignored if neither a ``hue`` nor a ``scale`` is specified. legend_values : list, optional The values to use in the legend. Defaults to equal intervals. For more information see `the Gallery demo <https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_. legend_labels : list, optional The names to use in the legend. Defaults to the variable values. For more information see `the Gallery demo <https://residentmario.github.io/geoplot/examples/largest-cities-usa.html>`_. legend_kwargs : dict, optional Keyword arguments to be passed to `the underlying legend <http://matplotlib.org/users/legend_guide.html>`_. extent : None or (minx, maxx, miny, maxy), optional Used to control plot x-axis and y-axis limits manually. figsize : tuple, optional An (x, y) tuple passed to ``matplotlib.figure`` which sets the size, in inches, of the resultant plot. ax : AxesSubplot or GeoAxesSubplot instance, optional A ``matplotlib.axes.AxesSubplot`` or ``cartopy.mpl.geoaxes.GeoAxesSubplot`` instance. Defaults to a new axis. kwargs: dict, optional Keyword arguments to be passed to the underlying ``matplotlib`` `Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. Returns ------- ``AxesSubplot`` or ``GeoAxesSubplot`` The plot axis Examples -------- A choropleth takes observations that have been aggregated on some meaningful polygonal level (e.g. census tract, state, country, or continent) and displays the data to the reader using color. It is a well-known plot type, and likeliest the most general-purpose and well-known of the specifically spatial plot types. It is especially powerful when combined with meaningful or actionable aggregation areas; if no such aggregations exist, or the aggregations you have access to are mostly incidental, its value is more limited. The ``choropleth`` requires a series of enclosed areas consisting of ``shapely`` ``Polygon`` or ``MultiPolygon`` entities, and a set of data about them that you would like to express in color. A basic choropleth requires geometry, a ``hue`` variable, and, optionally, a projection. .. code-block:: python import geoplot as gplt import geoplot.crs as gcrs gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree()) .. image:: ../figures/choropleth/choropleth-initial.png Change the colormap with the ``cmap`` parameter. .. code-block:: python gplt.choropleth(polydata, hue='latdep', projection=gcrs.PlateCarree(), cmap='Blues') .. image:: ../figures/choropleth/choropleth-cmap.png If your variable of interest is already `categorical <http://pandas.pydata.org/pandas-docs/stable/categorical.html>`_, you can specify ``categorical=True`` to use the labels in your dataset directly. To add a legend, specify ``legend``. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, legend=True) .. image:: ../figures/choropleth/choropleth-legend.png Keyword arguments can be passed to the legend using the ``legend_kwargs`` argument. These arguments will be passed to the underlying ``matplotlib.legend.Legend`` instance (`ref <http://matplotlib.org/api/legend_api.html#matplotlib.legend.Legend>`_). The ``loc`` and ``bbox_to_anchor`` parameters are particularly useful for positioning the legend. Other additional arguments will be passed to the underlying ``matplotlib`` `scatter plot <http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter>`_. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, legend=True, legend_kwargs={'loc': 'upper left'}) .. image:: ../figures/choropleth/choropleth-legend-kwargs.png Additional arguments not in the method signature will be passed as keyword parameters to the underlying `matplotlib Polygon patches <http://matplotlib.org/api/patches_api.html#matplotlib.patches.Polygon>`_. .. code-block:: python gplt.choropleth(boroughs, projection=gcrs.AlbersEqualArea(), hue='BoroName', categorical=True, linewidth=0) .. image:: ../figures/choropleth/choropleth-kwargs.png Choropleths default to splitting the data into five buckets with approximately equal numbers of observations in them. Change the number of buckets by specifying ``k``. Or, to use a continuous colormap, specify ``k=None``. In this case a colorbar legend will be used. .. code-block:: python gplt.choropleth(polydata, hue='latdep', cmap='Blues', k=None, legend=True, projection=gcrs.PlateCarree()) .. image:: ../figures/choropleth/choropleth-k-none.png The ``choropleth`` binning methodology is controlled using by `scheme`` parameter. The default is ``quantile``, which bins observations into classes of different sizes but the same numbers of observations. ``equal_interval`` will creates bins that are the same size, but potentially containing different numbers of observations. The more complicated ``fisher_jenks`` scheme is an intermediate between the two. .. code-block:: python gplt.choropleth(census_tracts, hue='mock_data', projection=gcrs.AlbersEqualArea(), legend=True, edgecolor='white', linewidth=0.5, legend_kwargs={'loc': 'upper left'}, scheme='equal_interval') .. image:: ../figures/choropleth/choropleth-scheme.png
[ "Area", "aggregation", "plot", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L465-L687
train
ResidentMario/geoplot
geoplot/geoplot.py
_get_envelopes_min_maxes
def _get_envelopes_min_maxes(envelopes): """ Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note tha the ``Quadtree.bounds`` object property serves a similar role. Parameters ---------- envelopes : GeoSeries The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope.exterior``. Returns ------- (xmin, xmax, ymin, ymax) : tuple The data extrema. """ xmin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][0], linearring.coords[2][0], linearring.coords[3][0], linearring.coords[4][0]]))) xmax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][0], linearring.coords[2][0], linearring.coords[3][0], linearring.coords[4][0]]))) ymin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][1], linearring.coords[2][1], linearring.coords[3][1], linearring.coords[4][1]]))) ymax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][1], linearring.coords[2][1], linearring.coords[3][1], linearring.coords[4][1]]))) return xmin, xmax, ymin, ymax
python
def _get_envelopes_min_maxes(envelopes): """ Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note tha the ``Quadtree.bounds`` object property serves a similar role. Parameters ---------- envelopes : GeoSeries The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope.exterior``. Returns ------- (xmin, xmax, ymin, ymax) : tuple The data extrema. """ xmin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][0], linearring.coords[2][0], linearring.coords[3][0], linearring.coords[4][0]]))) xmax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][0], linearring.coords[2][0], linearring.coords[3][0], linearring.coords[4][0]]))) ymin = np.min(envelopes.map(lambda linearring: np.min([linearring.coords[1][1], linearring.coords[2][1], linearring.coords[3][1], linearring.coords[4][1]]))) ymax = np.max(envelopes.map(lambda linearring: np.max([linearring.coords[1][1], linearring.coords[2][1], linearring.coords[3][1], linearring.coords[4][1]]))) return xmin, xmax, ymin, ymax
[ "def", "_get_envelopes_min_maxes", "(", "envelopes", ")", ":", "xmin", "=", "np", ".", "min", "(", "envelopes", ".", "map", "(", "lambda", "linearring", ":", "np", ".", "min", "(", "[", "linearring", ".", "coords", "[", "1", "]", "[", "0", "]", ",", "linearring", ".", "coords", "[", "2", "]", "[", "0", "]", ",", "linearring", ".", "coords", "[", "3", "]", "[", "0", "]", ",", "linearring", ".", "coords", "[", "4", "]", "[", "0", "]", "]", ")", ")", ")", "xmax", "=", "np", ".", "max", "(", "envelopes", ".", "map", "(", "lambda", "linearring", ":", "np", ".", "max", "(", "[", "linearring", ".", "coords", "[", "1", "]", "[", "0", "]", ",", "linearring", ".", "coords", "[", "2", "]", "[", "0", "]", ",", "linearring", ".", "coords", "[", "3", "]", "[", "0", "]", ",", "linearring", ".", "coords", "[", "4", "]", "[", "0", "]", "]", ")", ")", ")", "ymin", "=", "np", ".", "min", "(", "envelopes", ".", "map", "(", "lambda", "linearring", ":", "np", ".", "min", "(", "[", "linearring", ".", "coords", "[", "1", "]", "[", "1", "]", ",", "linearring", ".", "coords", "[", "2", "]", "[", "1", "]", ",", "linearring", ".", "coords", "[", "3", "]", "[", "1", "]", ",", "linearring", ".", "coords", "[", "4", "]", "[", "1", "]", "]", ")", ")", ")", "ymax", "=", "np", ".", "max", "(", "envelopes", ".", "map", "(", "lambda", "linearring", ":", "np", ".", "max", "(", "[", "linearring", ".", "coords", "[", "1", "]", "[", "1", "]", ",", "linearring", ".", "coords", "[", "2", "]", "[", "1", "]", ",", "linearring", ".", "coords", "[", "3", "]", "[", "1", "]", ",", "linearring", ".", "coords", "[", "4", "]", "[", "1", "]", "]", ")", ")", ")", "return", "xmin", ",", "xmax", ",", "ymin", ",", "ymax" ]
Returns the extrema of the inputted polygonal envelopes. Used for setting chart extent where appropriate. Note tha the ``Quadtree.bounds`` object property serves a similar role. Parameters ---------- envelopes : GeoSeries The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope.exterior``. Returns ------- (xmin, xmax, ymin, ymax) : tuple The data extrema.
[ "Returns", "the", "extrema", "of", "the", "inputted", "polygonal", "envelopes", ".", "Used", "for", "setting", "chart", "extent", "where", "appropriate", ".", "Note", "tha", "the", "Quadtree", ".", "bounds", "object", "property", "serves", "a", "similar", "role", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2192-L2224
train
ResidentMario/geoplot
geoplot/geoplot.py
_get_envelopes_centroid
def _get_envelopes_centroid(envelopes): """ Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``. Parameters ---------- envelopes : GeoSeries The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope``. Returns ------- (mean_x, mean_y) : tuple The data centroid. """ xmin, xmax, ymin, ymax = _get_envelopes_min_maxes(envelopes) return np.mean(xmin, xmax), np.mean(ymin, ymax)
python
def _get_envelopes_centroid(envelopes): """ Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``. Parameters ---------- envelopes : GeoSeries The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope``. Returns ------- (mean_x, mean_y) : tuple The data centroid. """ xmin, xmax, ymin, ymax = _get_envelopes_min_maxes(envelopes) return np.mean(xmin, xmax), np.mean(ymin, ymax)
[ "def", "_get_envelopes_centroid", "(", "envelopes", ")", ":", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "_get_envelopes_min_maxes", "(", "envelopes", ")", "return", "np", ".", "mean", "(", "xmin", ",", "xmax", ")", ",", "np", ".", "mean", "(", "ymin", ",", "ymax", ")" ]
Returns the centroid of an inputted geometry column. Not currently in use, as this is now handled by this library's CRS wrapper directly. Light wrapper over ``_get_envelopes_min_maxes``. Parameters ---------- envelopes : GeoSeries The envelopes of the given geometries, as would be returned by e.g. ``data.geometry.envelope``. Returns ------- (mean_x, mean_y) : tuple The data centroid.
[ "Returns", "the", "centroid", "of", "an", "inputted", "geometry", "column", ".", "Not", "currently", "in", "use", "as", "this", "is", "now", "handled", "by", "this", "library", "s", "CRS", "wrapper", "directly", ".", "Light", "wrapper", "over", "_get_envelopes_min_maxes", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2227-L2243
train
ResidentMario/geoplot
geoplot/geoplot.py
_set_extent
def _set_extent(ax, projection, extent, extrema): """ Sets the plot extent. Parameters ---------- ax : cartopy.GeoAxesSubplot instance The axis whose boundaries are being tweaked. projection : None or geoplot.crs instance The projection, if one is being used. extent : None or (xmin, xmax, ymin, ymax) tuple A copy of the ``extent`` top-level parameter, if the user choses to specify their own extent. These values will be used if ``extent`` is non-``None``. extrema : None or (xmin, xmax, ymin, ymax) tuple Plot-calculated extrema. These values, which are calculated in the plot above and passed to this function (different plots require different calculations), will be used if a user-provided ``extent`` is not provided. Returns ------- None """ if extent: xmin, xmax, ymin, ymax = extent xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90) if projection: # Input ``extent`` into set_extent(). ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree()) else: # Input ``extent`` into set_ylim, set_xlim. ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) else: xmin, xmax, ymin, ymax = extrema xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90) if projection: # Input ``extrema`` into set_extent. ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree()) else: # Input ``extrema`` into set_ylim, set_xlim. ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax))
python
def _set_extent(ax, projection, extent, extrema): """ Sets the plot extent. Parameters ---------- ax : cartopy.GeoAxesSubplot instance The axis whose boundaries are being tweaked. projection : None or geoplot.crs instance The projection, if one is being used. extent : None or (xmin, xmax, ymin, ymax) tuple A copy of the ``extent`` top-level parameter, if the user choses to specify their own extent. These values will be used if ``extent`` is non-``None``. extrema : None or (xmin, xmax, ymin, ymax) tuple Plot-calculated extrema. These values, which are calculated in the plot above and passed to this function (different plots require different calculations), will be used if a user-provided ``extent`` is not provided. Returns ------- None """ if extent: xmin, xmax, ymin, ymax = extent xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90) if projection: # Input ``extent`` into set_extent(). ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree()) else: # Input ``extent`` into set_ylim, set_xlim. ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax)) else: xmin, xmax, ymin, ymax = extrema xmin, xmax, ymin, ymax = max(xmin, -180), min(xmax, 180), max(ymin, -90), min(ymax, 90) if projection: # Input ``extrema`` into set_extent. ax.set_extent((xmin, xmax, ymin, ymax), crs=ccrs.PlateCarree()) else: # Input ``extrema`` into set_ylim, set_xlim. ax.set_xlim((xmin, xmax)) ax.set_ylim((ymin, ymax))
[ "def", "_set_extent", "(", "ax", ",", "projection", ",", "extent", ",", "extrema", ")", ":", "if", "extent", ":", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "extent", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "max", "(", "xmin", ",", "-", "180", ")", ",", "min", "(", "xmax", ",", "180", ")", ",", "max", "(", "ymin", ",", "-", "90", ")", ",", "min", "(", "ymax", ",", "90", ")", "if", "projection", ":", "# Input ``extent`` into set_extent().", "ax", ".", "set_extent", "(", "(", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", ")", ",", "crs", "=", "ccrs", ".", "PlateCarree", "(", ")", ")", "else", ":", "# Input ``extent`` into set_ylim, set_xlim.", "ax", ".", "set_xlim", "(", "(", "xmin", ",", "xmax", ")", ")", "ax", ".", "set_ylim", "(", "(", "ymin", ",", "ymax", ")", ")", "else", ":", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "extrema", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", "=", "max", "(", "xmin", ",", "-", "180", ")", ",", "min", "(", "xmax", ",", "180", ")", ",", "max", "(", "ymin", ",", "-", "90", ")", ",", "min", "(", "ymax", ",", "90", ")", "if", "projection", ":", "# Input ``extrema`` into set_extent.", "ax", ".", "set_extent", "(", "(", "xmin", ",", "xmax", ",", "ymin", ",", "ymax", ")", ",", "crs", "=", "ccrs", ".", "PlateCarree", "(", ")", ")", "else", ":", "# Input ``extrema`` into set_ylim, set_xlim.", "ax", ".", "set_xlim", "(", "(", "xmin", ",", "xmax", ")", ")", "ax", ".", "set_ylim", "(", "(", "ymin", ",", "ymax", ")", ")" ]
Sets the plot extent. Parameters ---------- ax : cartopy.GeoAxesSubplot instance The axis whose boundaries are being tweaked. projection : None or geoplot.crs instance The projection, if one is being used. extent : None or (xmin, xmax, ymin, ymax) tuple A copy of the ``extent`` top-level parameter, if the user choses to specify their own extent. These values will be used if ``extent`` is non-``None``. extrema : None or (xmin, xmax, ymin, ymax) tuple Plot-calculated extrema. These values, which are calculated in the plot above and passed to this function (different plots require different calculations), will be used if a user-provided ``extent`` is not provided. Returns ------- None
[ "Sets", "the", "plot", "extent", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2246-L2285
train
ResidentMario/geoplot
geoplot/geoplot.py
_lay_out_axes
def _lay_out_axes(ax, projection): """ ``cartopy`` enables a a transparent background patch and an "outline" patch by default. This short method simply hides these extraneous visual features. If the plot is a pure ``matplotlib`` one, it does the same thing by removing the axis altogether. Parameters ---------- ax : matplotlib.Axes instance The ``matplotlib.Axes`` instance being manipulated. projection : None or geoplot.crs instance The projection, if one is used. Returns ------- None """ if projection is not None: try: ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) except AttributeError: # Testing... pass else: plt.gca().axison = False
python
def _lay_out_axes(ax, projection): """ ``cartopy`` enables a a transparent background patch and an "outline" patch by default. This short method simply hides these extraneous visual features. If the plot is a pure ``matplotlib`` one, it does the same thing by removing the axis altogether. Parameters ---------- ax : matplotlib.Axes instance The ``matplotlib.Axes`` instance being manipulated. projection : None or geoplot.crs instance The projection, if one is used. Returns ------- None """ if projection is not None: try: ax.background_patch.set_visible(False) ax.outline_patch.set_visible(False) except AttributeError: # Testing... pass else: plt.gca().axison = False
[ "def", "_lay_out_axes", "(", "ax", ",", "projection", ")", ":", "if", "projection", "is", "not", "None", ":", "try", ":", "ax", ".", "background_patch", ".", "set_visible", "(", "False", ")", "ax", ".", "outline_patch", ".", "set_visible", "(", "False", ")", "except", "AttributeError", ":", "# Testing...", "pass", "else", ":", "plt", ".", "gca", "(", ")", ".", "axison", "=", "False" ]
``cartopy`` enables a a transparent background patch and an "outline" patch by default. This short method simply hides these extraneous visual features. If the plot is a pure ``matplotlib`` one, it does the same thing by removing the axis altogether. Parameters ---------- ax : matplotlib.Axes instance The ``matplotlib.Axes`` instance being manipulated. projection : None or geoplot.crs instance The projection, if one is used. Returns ------- None
[ "cartopy", "enables", "a", "a", "transparent", "background", "patch", "and", "an", "outline", "patch", "by", "default", ".", "This", "short", "method", "simply", "hides", "these", "extraneous", "visual", "features", ".", "If", "the", "plot", "is", "a", "pure", "matplotlib", "one", "it", "does", "the", "same", "thing", "by", "removing", "the", "axis", "altogether", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2288-L2312
train
ResidentMario/geoplot
geoplot/geoplot.py
_continuous_colormap
def _continuous_colormap(hue, cmap, vmin, vmax): """ Creates a continuous colormap. Parameters ---------- hue : iterable The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue`` parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized iterables before this method is called. cmap : ``matplotlib.cm`` instance The `matplotlib` colormap instance which will be used to colorize the geometries. vmin : float A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is below this level will all be colored by the same threshold value. The value for this variable is meant to be inherited from the top-level variable of the same name. vmax : float A strict ceiling on the value associated with the "top" of the colormap spectrum. Data column entries whose value is above this level will all be colored by the same threshold value. The value for this variable is meant to be inherited from the top-level variable of the same name. Returns ------- cmap : ``mpl.cm.ScalarMappable`` instance A normalized scalar version of the input ``cmap`` which has been fitted to the data and inputs. """ mn = min(hue) if vmin is None else vmin mx = max(hue) if vmax is None else vmax norm = mpl.colors.Normalize(vmin=mn, vmax=mx) return mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
python
def _continuous_colormap(hue, cmap, vmin, vmax): """ Creates a continuous colormap. Parameters ---------- hue : iterable The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue`` parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized iterables before this method is called. cmap : ``matplotlib.cm`` instance The `matplotlib` colormap instance which will be used to colorize the geometries. vmin : float A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is below this level will all be colored by the same threshold value. The value for this variable is meant to be inherited from the top-level variable of the same name. vmax : float A strict ceiling on the value associated with the "top" of the colormap spectrum. Data column entries whose value is above this level will all be colored by the same threshold value. The value for this variable is meant to be inherited from the top-level variable of the same name. Returns ------- cmap : ``mpl.cm.ScalarMappable`` instance A normalized scalar version of the input ``cmap`` which has been fitted to the data and inputs. """ mn = min(hue) if vmin is None else vmin mx = max(hue) if vmax is None else vmax norm = mpl.colors.Normalize(vmin=mn, vmax=mx) return mpl.cm.ScalarMappable(norm=norm, cmap=cmap)
[ "def", "_continuous_colormap", "(", "hue", ",", "cmap", ",", "vmin", ",", "vmax", ")", ":", "mn", "=", "min", "(", "hue", ")", "if", "vmin", "is", "None", "else", "vmin", "mx", "=", "max", "(", "hue", ")", "if", "vmax", "is", "None", "else", "vmax", "norm", "=", "mpl", ".", "colors", ".", "Normalize", "(", "vmin", "=", "mn", ",", "vmax", "=", "mx", ")", "return", "mpl", ".", "cm", ".", "ScalarMappable", "(", "norm", "=", "norm", ",", "cmap", "=", "cmap", ")" ]
Creates a continuous colormap. Parameters ---------- hue : iterable The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue`` parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized iterables before this method is called. cmap : ``matplotlib.cm`` instance The `matplotlib` colormap instance which will be used to colorize the geometries. vmin : float A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is below this level will all be colored by the same threshold value. The value for this variable is meant to be inherited from the top-level variable of the same name. vmax : float A strict ceiling on the value associated with the "top" of the colormap spectrum. Data column entries whose value is above this level will all be colored by the same threshold value. The value for this variable is meant to be inherited from the top-level variable of the same name. Returns ------- cmap : ``mpl.cm.ScalarMappable`` instance A normalized scalar version of the input ``cmap`` which has been fitted to the data and inputs.
[ "Creates", "a", "continuous", "colormap", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2345-L2374
train
ResidentMario/geoplot
geoplot/geoplot.py
_discrete_colorize
def _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax): """ Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we assume that the input data is categorical. This code makes extensive use of ``geopandas`` choropleth facilities. Parameters ---------- categorical : boolean Whether or not the input variable is already categorical. hue : iterable The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue`` parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized iterables before this method is called. scheme : str The mapclassify binning scheme to be used for splitting data values (or rather, the the string representation thereof). k : int The number of bins which will be used. This parameter will be ignored if ``categorical`` is True. The default value should be 5---this should be set before this method is called. cmap : ``matplotlib.cm`` instance The `matplotlib` colormap instance which will be used to colorize the geometries. This colormap determines the spectrum; our algorithm determines the cuts. vmin : float A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is below this level will all be colored by the same threshold value. vmax : float A strict cealing on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is above this level will all be colored by the same threshold value. Returns ------- (cmap, categories, values) : tuple A tuple meant for assignment containing the values for various properties set by this method call. """ if not categorical: binning = _mapclassify_choro(hue, scheme, k=k) values = binning.yb binedges = [binning.yb.min()] + binning.bins.tolist() categories = ['{0:.2f} - {1:.2f}'.format(binedges[i], binedges[i + 1]) for i in range(len(binedges) - 1)] else: categories = np.unique(hue) if len(categories) > 10: warnings.warn("Generating a colormap using a categorical column with over 10 individual categories. " "This is not recommended!") value_map = {v: i for i, v in enumerate(categories)} values = [value_map[d] for d in hue] cmap = _norm_cmap(values, cmap, mpl.colors.Normalize, mpl.cm, vmin=vmin, vmax=vmax) return cmap, categories, values
python
def _discrete_colorize(categorical, hue, scheme, k, cmap, vmin, vmax): """ Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we assume that the input data is categorical. This code makes extensive use of ``geopandas`` choropleth facilities. Parameters ---------- categorical : boolean Whether or not the input variable is already categorical. hue : iterable The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue`` parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized iterables before this method is called. scheme : str The mapclassify binning scheme to be used for splitting data values (or rather, the the string representation thereof). k : int The number of bins which will be used. This parameter will be ignored if ``categorical`` is True. The default value should be 5---this should be set before this method is called. cmap : ``matplotlib.cm`` instance The `matplotlib` colormap instance which will be used to colorize the geometries. This colormap determines the spectrum; our algorithm determines the cuts. vmin : float A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is below this level will all be colored by the same threshold value. vmax : float A strict cealing on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is above this level will all be colored by the same threshold value. Returns ------- (cmap, categories, values) : tuple A tuple meant for assignment containing the values for various properties set by this method call. """ if not categorical: binning = _mapclassify_choro(hue, scheme, k=k) values = binning.yb binedges = [binning.yb.min()] + binning.bins.tolist() categories = ['{0:.2f} - {1:.2f}'.format(binedges[i], binedges[i + 1]) for i in range(len(binedges) - 1)] else: categories = np.unique(hue) if len(categories) > 10: warnings.warn("Generating a colormap using a categorical column with over 10 individual categories. " "This is not recommended!") value_map = {v: i for i, v in enumerate(categories)} values = [value_map[d] for d in hue] cmap = _norm_cmap(values, cmap, mpl.colors.Normalize, mpl.cm, vmin=vmin, vmax=vmax) return cmap, categories, values
[ "def", "_discrete_colorize", "(", "categorical", ",", "hue", ",", "scheme", ",", "k", ",", "cmap", ",", "vmin", ",", "vmax", ")", ":", "if", "not", "categorical", ":", "binning", "=", "_mapclassify_choro", "(", "hue", ",", "scheme", ",", "k", "=", "k", ")", "values", "=", "binning", ".", "yb", "binedges", "=", "[", "binning", ".", "yb", ".", "min", "(", ")", "]", "+", "binning", ".", "bins", ".", "tolist", "(", ")", "categories", "=", "[", "'{0:.2f} - {1:.2f}'", ".", "format", "(", "binedges", "[", "i", "]", ",", "binedges", "[", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "len", "(", "binedges", ")", "-", "1", ")", "]", "else", ":", "categories", "=", "np", ".", "unique", "(", "hue", ")", "if", "len", "(", "categories", ")", ">", "10", ":", "warnings", ".", "warn", "(", "\"Generating a colormap using a categorical column with over 10 individual categories. \"", "\"This is not recommended!\"", ")", "value_map", "=", "{", "v", ":", "i", "for", "i", ",", "v", "in", "enumerate", "(", "categories", ")", "}", "values", "=", "[", "value_map", "[", "d", "]", "for", "d", "in", "hue", "]", "cmap", "=", "_norm_cmap", "(", "values", ",", "cmap", ",", "mpl", ".", "colors", ".", "Normalize", ",", "mpl", ".", "cm", ",", "vmin", "=", "vmin", ",", "vmax", "=", "vmax", ")", "return", "cmap", ",", "categories", ",", "values" ]
Creates a discrete colormap, either using an already-categorical data variable or by bucketing a non-categorical ordinal one. If a scheme is provided we compute a distribution for the given data. If one is not provided we assume that the input data is categorical. This code makes extensive use of ``geopandas`` choropleth facilities. Parameters ---------- categorical : boolean Whether or not the input variable is already categorical. hue : iterable The data column whose entries are being discretely colorized. Note that although top-level plotter ``hue`` parameters ingest many argument signatures, not just iterables, they are all preprocessed to standardized iterables before this method is called. scheme : str The mapclassify binning scheme to be used for splitting data values (or rather, the the string representation thereof). k : int The number of bins which will be used. This parameter will be ignored if ``categorical`` is True. The default value should be 5---this should be set before this method is called. cmap : ``matplotlib.cm`` instance The `matplotlib` colormap instance which will be used to colorize the geometries. This colormap determines the spectrum; our algorithm determines the cuts. vmin : float A strict floor on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is below this level will all be colored by the same threshold value. vmax : float A strict cealing on the value associated with the "bottom" of the colormap spectrum. Data column entries whose value is above this level will all be colored by the same threshold value. Returns ------- (cmap, categories, values) : tuple A tuple meant for assignment containing the values for various properties set by this method call.
[ "Creates", "a", "discrete", "colormap", "either", "using", "an", "already", "-", "categorical", "data", "variable", "or", "by", "bucketing", "a", "non", "-", "categorical", "ordinal", "one", ".", "If", "a", "scheme", "is", "provided", "we", "compute", "a", "distribution", "for", "the", "given", "data", ".", "If", "one", "is", "not", "provided", "we", "assume", "that", "the", "input", "data", "is", "categorical", "." ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2377-L2428
train
ResidentMario/geoplot
geoplot/geoplot.py
_norm_cmap
def _norm_cmap(values, cmap, normalize, cm, vmin=None, vmax=None): """ Normalize and set colormap. Taken from [email protected] codebase, removed in [email protected]. """ mn = min(values) if vmin is None else vmin mx = max(values) if vmax is None else vmax norm = normalize(vmin=mn, vmax=mx) n_cmap = cm.ScalarMappable(norm=norm, cmap=cmap) return n_cmap
python
def _norm_cmap(values, cmap, normalize, cm, vmin=None, vmax=None): """ Normalize and set colormap. Taken from [email protected] codebase, removed in [email protected]. """ mn = min(values) if vmin is None else vmin mx = max(values) if vmax is None else vmax norm = normalize(vmin=mn, vmax=mx) n_cmap = cm.ScalarMappable(norm=norm, cmap=cmap) return n_cmap
[ "def", "_norm_cmap", "(", "values", ",", "cmap", ",", "normalize", ",", "cm", ",", "vmin", "=", "None", ",", "vmax", "=", "None", ")", ":", "mn", "=", "min", "(", "values", ")", "if", "vmin", "is", "None", "else", "vmin", "mx", "=", "max", "(", "values", ")", "if", "vmax", "is", "None", "else", "vmax", "norm", "=", "normalize", "(", "vmin", "=", "mn", ",", "vmax", "=", "mx", ")", "n_cmap", "=", "cm", ".", "ScalarMappable", "(", "norm", "=", "norm", ",", "cmap", "=", "cmap", ")", "return", "n_cmap" ]
Normalize and set colormap. Taken from [email protected] codebase, removed in [email protected].
[ "Normalize", "and", "set", "colormap", ".", "Taken", "from", "geopandas" ]
942b474878187a87a95a27fbe41285dfdc1d20ca
https://github.com/ResidentMario/geoplot/blob/942b474878187a87a95a27fbe41285dfdc1d20ca/geoplot/geoplot.py#L2733-L2742
train
tmux-python/libtmux
libtmux/common.py
get_version
def get_version(): """ Return tmux version. If tmux is built from git master, the version returned will be the latest version appended with -master, e.g. ``2.4-master``. If using OpenBSD's base system tmux, the version will have ``-openbsd`` appended to the latest version, e.g. ``2.4-openbsd``. Returns ------- :class:`distutils.version.LooseVersion` tmux version according to :func:`libtmux.common.which`'s tmux """ proc = tmux_cmd('-V') if proc.stderr: if proc.stderr[0] == 'tmux: unknown option -- V': if sys.platform.startswith("openbsd"): # openbsd has no tmux -V return LooseVersion('%s-openbsd' % TMUX_MAX_VERSION) raise exc.LibTmuxException( 'libtmux supports tmux %s and greater. This system' ' is running tmux 1.3 or earlier.' % TMUX_MIN_VERSION ) raise exc.VersionTooLow(proc.stderr) version = proc.stdout[0].split('tmux ')[1] # Allow latest tmux HEAD if version == 'master': return LooseVersion('%s-master' % TMUX_MAX_VERSION) version = re.sub(r'[a-z-]', '', version) return LooseVersion(version)
python
def get_version(): """ Return tmux version. If tmux is built from git master, the version returned will be the latest version appended with -master, e.g. ``2.4-master``. If using OpenBSD's base system tmux, the version will have ``-openbsd`` appended to the latest version, e.g. ``2.4-openbsd``. Returns ------- :class:`distutils.version.LooseVersion` tmux version according to :func:`libtmux.common.which`'s tmux """ proc = tmux_cmd('-V') if proc.stderr: if proc.stderr[0] == 'tmux: unknown option -- V': if sys.platform.startswith("openbsd"): # openbsd has no tmux -V return LooseVersion('%s-openbsd' % TMUX_MAX_VERSION) raise exc.LibTmuxException( 'libtmux supports tmux %s and greater. This system' ' is running tmux 1.3 or earlier.' % TMUX_MIN_VERSION ) raise exc.VersionTooLow(proc.stderr) version = proc.stdout[0].split('tmux ')[1] # Allow latest tmux HEAD if version == 'master': return LooseVersion('%s-master' % TMUX_MAX_VERSION) version = re.sub(r'[a-z-]', '', version) return LooseVersion(version)
[ "def", "get_version", "(", ")", ":", "proc", "=", "tmux_cmd", "(", "'-V'", ")", "if", "proc", ".", "stderr", ":", "if", "proc", ".", "stderr", "[", "0", "]", "==", "'tmux: unknown option -- V'", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "\"openbsd\"", ")", ":", "# openbsd has no tmux -V", "return", "LooseVersion", "(", "'%s-openbsd'", "%", "TMUX_MAX_VERSION", ")", "raise", "exc", ".", "LibTmuxException", "(", "'libtmux supports tmux %s and greater. This system'", "' is running tmux 1.3 or earlier.'", "%", "TMUX_MIN_VERSION", ")", "raise", "exc", ".", "VersionTooLow", "(", "proc", ".", "stderr", ")", "version", "=", "proc", ".", "stdout", "[", "0", "]", ".", "split", "(", "'tmux '", ")", "[", "1", "]", "# Allow latest tmux HEAD", "if", "version", "==", "'master'", ":", "return", "LooseVersion", "(", "'%s-master'", "%", "TMUX_MAX_VERSION", ")", "version", "=", "re", ".", "sub", "(", "r'[a-z-]'", ",", "''", ",", "version", ")", "return", "LooseVersion", "(", "version", ")" ]
Return tmux version. If tmux is built from git master, the version returned will be the latest version appended with -master, e.g. ``2.4-master``. If using OpenBSD's base system tmux, the version will have ``-openbsd`` appended to the latest version, e.g. ``2.4-openbsd``. Returns ------- :class:`distutils.version.LooseVersion` tmux version according to :func:`libtmux.common.which`'s tmux
[ "Return", "tmux", "version", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L442-L476
train
tmux-python/libtmux
libtmux/common.py
has_minimum_version
def has_minimum_version(raises=True): """ Return if tmux meets version requirement. Version >1.8 or above. Parameters ---------- raises : bool raise exception if below minimum version requirement Returns ------- bool True if tmux meets minimum required version. Raises ------ libtmux.exc.VersionTooLow tmux version below minimum required for libtmux Notes ----- .. versionchanged:: 0.7.0 No longer returns version, returns True or False .. versionchanged:: 0.1.7 Versions will now remove trailing letters per `Issue 55`_. .. _Issue 55: https://github.com/tmux-python/tmuxp/issues/55. """ if get_version() < LooseVersion(TMUX_MIN_VERSION): if raises: raise exc.VersionTooLow( 'libtmux only supports tmux %s and greater. This system' ' has %s installed. Upgrade your tmux to use libtmux.' % (TMUX_MIN_VERSION, get_version()) ) else: return False return True
python
def has_minimum_version(raises=True): """ Return if tmux meets version requirement. Version >1.8 or above. Parameters ---------- raises : bool raise exception if below minimum version requirement Returns ------- bool True if tmux meets minimum required version. Raises ------ libtmux.exc.VersionTooLow tmux version below minimum required for libtmux Notes ----- .. versionchanged:: 0.7.0 No longer returns version, returns True or False .. versionchanged:: 0.1.7 Versions will now remove trailing letters per `Issue 55`_. .. _Issue 55: https://github.com/tmux-python/tmuxp/issues/55. """ if get_version() < LooseVersion(TMUX_MIN_VERSION): if raises: raise exc.VersionTooLow( 'libtmux only supports tmux %s and greater. This system' ' has %s installed. Upgrade your tmux to use libtmux.' % (TMUX_MIN_VERSION, get_version()) ) else: return False return True
[ "def", "has_minimum_version", "(", "raises", "=", "True", ")", ":", "if", "get_version", "(", ")", "<", "LooseVersion", "(", "TMUX_MIN_VERSION", ")", ":", "if", "raises", ":", "raise", "exc", ".", "VersionTooLow", "(", "'libtmux only supports tmux %s and greater. This system'", "' has %s installed. Upgrade your tmux to use libtmux.'", "%", "(", "TMUX_MIN_VERSION", ",", "get_version", "(", ")", ")", ")", "else", ":", "return", "False", "return", "True" ]
Return if tmux meets version requirement. Version >1.8 or above. Parameters ---------- raises : bool raise exception if below minimum version requirement Returns ------- bool True if tmux meets minimum required version. Raises ------ libtmux.exc.VersionTooLow tmux version below minimum required for libtmux Notes ----- .. versionchanged:: 0.7.0 No longer returns version, returns True or False .. versionchanged:: 0.1.7 Versions will now remove trailing letters per `Issue 55`_. .. _Issue 55: https://github.com/tmux-python/tmuxp/issues/55.
[ "Return", "if", "tmux", "meets", "version", "requirement", ".", "Version", ">", "1", ".", "8", "or", "above", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L564-L603
train
tmux-python/libtmux
libtmux/common.py
session_check_name
def session_check_name(session_name): """ Raises exception session name invalid, modeled after tmux function. tmux(1) session names may not be empty, or include periods or colons. These delimiters are reserved for noting session, window and pane. Parameters ---------- session_name : str Name of session. Raises ------ :exc:`exc.BadSessionName` Invalid session name. """ if not session_name or len(session_name) == 0: raise exc.BadSessionName("tmux session names may not be empty.") elif '.' in session_name: raise exc.BadSessionName( "tmux session name \"%s\" may not contain periods.", session_name ) elif ':' in session_name: raise exc.BadSessionName( "tmux session name \"%s\" may not contain colons.", session_name )
python
def session_check_name(session_name): """ Raises exception session name invalid, modeled after tmux function. tmux(1) session names may not be empty, or include periods or colons. These delimiters are reserved for noting session, window and pane. Parameters ---------- session_name : str Name of session. Raises ------ :exc:`exc.BadSessionName` Invalid session name. """ if not session_name or len(session_name) == 0: raise exc.BadSessionName("tmux session names may not be empty.") elif '.' in session_name: raise exc.BadSessionName( "tmux session name \"%s\" may not contain periods.", session_name ) elif ':' in session_name: raise exc.BadSessionName( "tmux session name \"%s\" may not contain colons.", session_name )
[ "def", "session_check_name", "(", "session_name", ")", ":", "if", "not", "session_name", "or", "len", "(", "session_name", ")", "==", "0", ":", "raise", "exc", ".", "BadSessionName", "(", "\"tmux session names may not be empty.\"", ")", "elif", "'.'", "in", "session_name", ":", "raise", "exc", ".", "BadSessionName", "(", "\"tmux session name \\\"%s\\\" may not contain periods.\"", ",", "session_name", ")", "elif", "':'", "in", "session_name", ":", "raise", "exc", ".", "BadSessionName", "(", "\"tmux session name \\\"%s\\\" may not contain colons.\"", ",", "session_name", ")" ]
Raises exception session name invalid, modeled after tmux function. tmux(1) session names may not be empty, or include periods or colons. These delimiters are reserved for noting session, window and pane. Parameters ---------- session_name : str Name of session. Raises ------ :exc:`exc.BadSessionName` Invalid session name.
[ "Raises", "exception", "session", "name", "invalid", "modeled", "after", "tmux", "function", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L606-L632
train
tmux-python/libtmux
libtmux/common.py
handle_option_error
def handle_option_error(error): """Raises exception if error in option command found. Purpose: As of tmux 2.4, there are now 3 different types of option errors: - unknown option - invalid option - ambiguous option Before 2.4, unknown option was the user. All errors raised will have the base error of :exc:`exc.OptionError`. So to catch any option error, use ``except exc.OptionError``. Parameters ---------- error : str Error response from subprocess call. Raises ------ :exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption` """ if 'unknown option' in error: raise exc.UnknownOption(error) elif 'invalid option' in error: raise exc.InvalidOption(error) elif 'ambiguous option' in error: raise exc.AmbiguousOption(error) else: raise exc.OptionError(error)
python
def handle_option_error(error): """Raises exception if error in option command found. Purpose: As of tmux 2.4, there are now 3 different types of option errors: - unknown option - invalid option - ambiguous option Before 2.4, unknown option was the user. All errors raised will have the base error of :exc:`exc.OptionError`. So to catch any option error, use ``except exc.OptionError``. Parameters ---------- error : str Error response from subprocess call. Raises ------ :exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption` """ if 'unknown option' in error: raise exc.UnknownOption(error) elif 'invalid option' in error: raise exc.InvalidOption(error) elif 'ambiguous option' in error: raise exc.AmbiguousOption(error) else: raise exc.OptionError(error)
[ "def", "handle_option_error", "(", "error", ")", ":", "if", "'unknown option'", "in", "error", ":", "raise", "exc", ".", "UnknownOption", "(", "error", ")", "elif", "'invalid option'", "in", "error", ":", "raise", "exc", ".", "InvalidOption", "(", "error", ")", "elif", "'ambiguous option'", "in", "error", ":", "raise", "exc", ".", "AmbiguousOption", "(", "error", ")", "else", ":", "raise", "exc", ".", "OptionError", "(", "error", ")" ]
Raises exception if error in option command found. Purpose: As of tmux 2.4, there are now 3 different types of option errors: - unknown option - invalid option - ambiguous option Before 2.4, unknown option was the user. All errors raised will have the base error of :exc:`exc.OptionError`. So to catch any option error, use ``except exc.OptionError``. Parameters ---------- error : str Error response from subprocess call. Raises ------ :exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`, :exc:`exc.AmbiguousOption`
[ "Raises", "exception", "if", "error", "in", "option", "command", "found", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L635-L666
train
tmux-python/libtmux
libtmux/common.py
TmuxRelationalObject.where
def where(self, attrs, first=False): """ Return objects matching child objects properties. Parameters ---------- attrs : dict tmux properties to match values of Returns ------- list """ # from https://github.com/serkanyersen/underscore.py def by(val, *args): for key, value in attrs.items(): try: if attrs[key] != val[key]: return False except KeyError: return False return True if first: return list(filter(by, self.children))[0] else: return list(filter(by, self.children))
python
def where(self, attrs, first=False): """ Return objects matching child objects properties. Parameters ---------- attrs : dict tmux properties to match values of Returns ------- list """ # from https://github.com/serkanyersen/underscore.py def by(val, *args): for key, value in attrs.items(): try: if attrs[key] != val[key]: return False except KeyError: return False return True if first: return list(filter(by, self.children))[0] else: return list(filter(by, self.children))
[ "def", "where", "(", "self", ",", "attrs", ",", "first", "=", "False", ")", ":", "# from https://github.com/serkanyersen/underscore.py", "def", "by", "(", "val", ",", "*", "args", ")", ":", "for", "key", ",", "value", "in", "attrs", ".", "items", "(", ")", ":", "try", ":", "if", "attrs", "[", "key", "]", "!=", "val", "[", "key", "]", ":", "return", "False", "except", "KeyError", ":", "return", "False", "return", "True", "if", "first", ":", "return", "list", "(", "filter", "(", "by", ",", "self", ".", "children", ")", ")", "[", "0", "]", "else", ":", "return", "list", "(", "filter", "(", "by", ",", "self", ".", "children", ")", ")" ]
Return objects matching child objects properties. Parameters ---------- attrs : dict tmux properties to match values of Returns ------- list
[ "Return", "objects", "matching", "child", "objects", "properties", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L324-L351
train
tmux-python/libtmux
libtmux/common.py
TmuxRelationalObject.get_by_id
def get_by_id(self, id): """ Return object based on ``child_id_attribute``. Parameters ---------- val : str Returns ------- object Notes ----- Based on `.get()`_ from `backbone.js`_. .. _backbone.js: http://backbonejs.org/ .. _.get(): http://backbonejs.org/#Collection-get """ for child in self.children: if child[self.child_id_attribute] == id: return child else: continue return None
python
def get_by_id(self, id): """ Return object based on ``child_id_attribute``. Parameters ---------- val : str Returns ------- object Notes ----- Based on `.get()`_ from `backbone.js`_. .. _backbone.js: http://backbonejs.org/ .. _.get(): http://backbonejs.org/#Collection-get """ for child in self.children: if child[self.child_id_attribute] == id: return child else: continue return None
[ "def", "get_by_id", "(", "self", ",", "id", ")", ":", "for", "child", "in", "self", ".", "children", ":", "if", "child", "[", "self", ".", "child_id_attribute", "]", "==", "id", ":", "return", "child", "else", ":", "continue", "return", "None" ]
Return object based on ``child_id_attribute``. Parameters ---------- val : str Returns ------- object Notes ----- Based on `.get()`_ from `backbone.js`_. .. _backbone.js: http://backbonejs.org/ .. _.get(): http://backbonejs.org/#Collection-get
[ "Return", "object", "based", "on", "child_id_attribute", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/common.py#L353-L378
train
tmux-python/libtmux
libtmux/window.py
Window.select_window
def select_window(self): """ Select window. Return ``self``. To select a window object asynchrously. If a ``window`` object exists and is no longer longer the current window, ``w.select_window()`` will make ``w`` the current window. Returns ------- :class:`Window` """ target = ('%s:%s' % (self.get('session_id'), self.index),) return self.session.select_window(target)
python
def select_window(self): """ Select window. Return ``self``. To select a window object asynchrously. If a ``window`` object exists and is no longer longer the current window, ``w.select_window()`` will make ``w`` the current window. Returns ------- :class:`Window` """ target = ('%s:%s' % (self.get('session_id'), self.index),) return self.session.select_window(target)
[ "def", "select_window", "(", "self", ")", ":", "target", "=", "(", "'%s:%s'", "%", "(", "self", ".", "get", "(", "'session_id'", ")", ",", "self", ".", "index", ")", ",", ")", "return", "self", ".", "session", ".", "select_window", "(", "target", ")" ]
Select window. Return ``self``. To select a window object asynchrously. If a ``window`` object exists and is no longer longer the current window, ``w.select_window()`` will make ``w`` the current window. Returns ------- :class:`Window`
[ "Select", "window", ".", "Return", "self", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/window.py#L341-L354
train
tmux-python/libtmux
libtmux/server.py
Server.cmd
def cmd(self, *args, **kwargs): """ Execute tmux command and return output. Returns ------- :class:`common.tmux_cmd` Notes ----- .. versionchanged:: 0.8 Renamed from ``.tmux`` to ``.cmd``. """ args = list(args) if self.socket_name: args.insert(0, '-L{0}'.format(self.socket_name)) if self.socket_path: args.insert(0, '-S{0}'.format(self.socket_path)) if self.config_file: args.insert(0, '-f{0}'.format(self.config_file)) if self.colors: if self.colors == 256: args.insert(0, '-2') elif self.colors == 88: args.insert(0, '-8') else: raise ValueError('Server.colors must equal 88 or 256') return tmux_cmd(*args, **kwargs)
python
def cmd(self, *args, **kwargs): """ Execute tmux command and return output. Returns ------- :class:`common.tmux_cmd` Notes ----- .. versionchanged:: 0.8 Renamed from ``.tmux`` to ``.cmd``. """ args = list(args) if self.socket_name: args.insert(0, '-L{0}'.format(self.socket_name)) if self.socket_path: args.insert(0, '-S{0}'.format(self.socket_path)) if self.config_file: args.insert(0, '-f{0}'.format(self.config_file)) if self.colors: if self.colors == 256: args.insert(0, '-2') elif self.colors == 88: args.insert(0, '-8') else: raise ValueError('Server.colors must equal 88 or 256') return tmux_cmd(*args, **kwargs)
[ "def", "cmd", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "if", "self", ".", "socket_name", ":", "args", ".", "insert", "(", "0", ",", "'-L{0}'", ".", "format", "(", "self", ".", "socket_name", ")", ")", "if", "self", ".", "socket_path", ":", "args", ".", "insert", "(", "0", ",", "'-S{0}'", ".", "format", "(", "self", ".", "socket_path", ")", ")", "if", "self", ".", "config_file", ":", "args", ".", "insert", "(", "0", ",", "'-f{0}'", ".", "format", "(", "self", ".", "config_file", ")", ")", "if", "self", ".", "colors", ":", "if", "self", ".", "colors", "==", "256", ":", "args", ".", "insert", "(", "0", ",", "'-2'", ")", "elif", "self", ".", "colors", "==", "88", ":", "args", ".", "insert", "(", "0", ",", "'-8'", ")", "else", ":", "raise", "ValueError", "(", "'Server.colors must equal 88 or 256'", ")", "return", "tmux_cmd", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
Execute tmux command and return output. Returns ------- :class:`common.tmux_cmd` Notes ----- .. versionchanged:: 0.8 Renamed from ``.tmux`` to ``.cmd``.
[ "Execute", "tmux", "command", "and", "return", "output", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/server.py#L99-L129
train
tmux-python/libtmux
libtmux/session.py
Session.switch_client
def switch_client(self): """ Switch client to this session. Raises ------ :exc:`exc.LibTmuxException` """ proc = self.cmd('switch-client', '-t%s' % self.id) if proc.stderr: raise exc.LibTmuxException(proc.stderr)
python
def switch_client(self): """ Switch client to this session. Raises ------ :exc:`exc.LibTmuxException` """ proc = self.cmd('switch-client', '-t%s' % self.id) if proc.stderr: raise exc.LibTmuxException(proc.stderr)
[ "def", "switch_client", "(", "self", ")", ":", "proc", "=", "self", ".", "cmd", "(", "'switch-client'", ",", "'-t%s'", "%", "self", ".", "id", ")", "if", "proc", ".", "stderr", ":", "raise", "exc", ".", "LibTmuxException", "(", "proc", ".", "stderr", ")" ]
Switch client to this session. Raises ------ :exc:`exc.LibTmuxException`
[ "Switch", "client", "to", "this", "session", "." ]
8eb2f8bbea3a025c1567b1516653414dbc24e1fc
https://github.com/tmux-python/libtmux/blob/8eb2f8bbea3a025c1567b1516653414dbc24e1fc/libtmux/session.py#L122-L134
train
Yubico/yubikey-manager
ykman/cli/opgp.py
openpgp
def openpgp(ctx): """ Manage OpenPGP Application. Examples: \b Set the retries for PIN, Reset Code and Admin PIN to 10: $ ykman openpgp set-retries 10 10 10 \b Require touch to use the authentication key: $ ykman openpgp touch aut on """ try: ctx.obj['controller'] = OpgpController(ctx.obj['dev'].driver) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The OpenPGP application can't be found on this " 'YubiKey.') logger.debug('Failed to load OpenPGP Application', exc_info=e) ctx.fail('Failed to load OpenPGP Application')
python
def openpgp(ctx): """ Manage OpenPGP Application. Examples: \b Set the retries for PIN, Reset Code and Admin PIN to 10: $ ykman openpgp set-retries 10 10 10 \b Require touch to use the authentication key: $ ykman openpgp touch aut on """ try: ctx.obj['controller'] = OpgpController(ctx.obj['dev'].driver) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The OpenPGP application can't be found on this " 'YubiKey.') logger.debug('Failed to load OpenPGP Application', exc_info=e) ctx.fail('Failed to load OpenPGP Application')
[ "def", "openpgp", "(", "ctx", ")", ":", "try", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "OpgpController", "(", "ctx", ".", "obj", "[", "'dev'", "]", ".", "driver", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "\"The OpenPGP application can't be found on this \"", "'YubiKey.'", ")", "logger", ".", "debug", "(", "'Failed to load OpenPGP Application'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to load OpenPGP Application'", ")" ]
Manage OpenPGP Application. Examples: \b Set the retries for PIN, Reset Code and Admin PIN to 10: $ ykman openpgp set-retries 10 10 10 \b Require touch to use the authentication key: $ ykman openpgp touch aut on
[ "Manage", "OpenPGP", "Application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L83-L104
train
Yubico/yubikey-manager
ykman/cli/opgp.py
info
def info(ctx): """ Display status of OpenPGP application. """ controller = ctx.obj['controller'] click.echo('OpenPGP version: %d.%d.%d' % controller.version) retries = controller.get_remaining_pin_tries() click.echo('PIN tries remaining: {}'.format(retries.pin)) click.echo('Reset code tries remaining: {}'.format(retries.reset)) click.echo('Admin PIN tries remaining: {}'.format(retries.admin)) click.echo() click.echo('Touch policies') click.echo( 'Signature key {.name}'.format( controller.get_touch(KEY_SLOT.SIGNATURE))) click.echo( 'Encryption key {.name}'.format( controller.get_touch(KEY_SLOT.ENCRYPTION))) click.echo( 'Authentication key {.name}'.format( controller.get_touch(KEY_SLOT.AUTHENTICATION)))
python
def info(ctx): """ Display status of OpenPGP application. """ controller = ctx.obj['controller'] click.echo('OpenPGP version: %d.%d.%d' % controller.version) retries = controller.get_remaining_pin_tries() click.echo('PIN tries remaining: {}'.format(retries.pin)) click.echo('Reset code tries remaining: {}'.format(retries.reset)) click.echo('Admin PIN tries remaining: {}'.format(retries.admin)) click.echo() click.echo('Touch policies') click.echo( 'Signature key {.name}'.format( controller.get_touch(KEY_SLOT.SIGNATURE))) click.echo( 'Encryption key {.name}'.format( controller.get_touch(KEY_SLOT.ENCRYPTION))) click.echo( 'Authentication key {.name}'.format( controller.get_touch(KEY_SLOT.AUTHENTICATION)))
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "click", ".", "echo", "(", "'OpenPGP version: %d.%d.%d'", "%", "controller", ".", "version", ")", "retries", "=", "controller", ".", "get_remaining_pin_tries", "(", ")", "click", ".", "echo", "(", "'PIN tries remaining: {}'", ".", "format", "(", "retries", ".", "pin", ")", ")", "click", ".", "echo", "(", "'Reset code tries remaining: {}'", ".", "format", "(", "retries", ".", "reset", ")", ")", "click", ".", "echo", "(", "'Admin PIN tries remaining: {}'", ".", "format", "(", "retries", ".", "admin", ")", ")", "click", ".", "echo", "(", ")", "click", ".", "echo", "(", "'Touch policies'", ")", "click", ".", "echo", "(", "'Signature key {.name}'", ".", "format", "(", "controller", ".", "get_touch", "(", "KEY_SLOT", ".", "SIGNATURE", ")", ")", ")", "click", ".", "echo", "(", "'Encryption key {.name}'", ".", "format", "(", "controller", ".", "get_touch", "(", "KEY_SLOT", ".", "ENCRYPTION", ")", ")", ")", "click", ".", "echo", "(", "'Authentication key {.name}'", ".", "format", "(", "controller", ".", "get_touch", "(", "KEY_SLOT", ".", "AUTHENTICATION", ")", ")", ")" ]
Display status of OpenPGP application.
[ "Display", "status", "of", "OpenPGP", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L109-L129
train
Yubico/yubikey-manager
ykman/cli/opgp.py
reset
def reset(ctx): """ Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values. """ click.echo("Resetting OpenPGP data, don't remove your YubiKey...") ctx.obj['controller'].reset() click.echo('Success! All data has been cleared and default PINs are set.') echo_default_pins()
python
def reset(ctx): """ Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values. """ click.echo("Resetting OpenPGP data, don't remove your YubiKey...") ctx.obj['controller'].reset() click.echo('Success! All data has been cleared and default PINs are set.') echo_default_pins()
[ "def", "reset", "(", "ctx", ")", ":", "click", ".", "echo", "(", "\"Resetting OpenPGP data, don't remove your YubiKey...\"", ")", "ctx", ".", "obj", "[", "'controller'", "]", ".", "reset", "(", ")", "click", ".", "echo", "(", "'Success! All data has been cleared and default PINs are set.'", ")", "echo_default_pins", "(", ")" ]
Reset OpenPGP application. This action will wipe all OpenPGP data, and set all PINs to their default values.
[ "Reset", "OpenPGP", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L137-L147
train
Yubico/yubikey-manager
ykman/cli/opgp.py
touch
def touch(ctx, key, policy, admin_pin, force): """ Manage touch policy for OpenPGP keys. \b KEY Key slot to set (sig, enc or aut). POLICY Touch policy to set (on, off or fixed). """ controller = ctx.obj['controller'] old_policy = controller.get_touch(key) if old_policy == TOUCH_MODE.FIXED: ctx.fail('A FIXED policy cannot be changed!') force or click.confirm('Set touch policy of {.name} key to {.name}?'.format( key, policy), abort=True, err=True) if admin_pin is None: admin_pin = click.prompt('Enter admin PIN', hide_input=True, err=True) controller.set_touch(key, policy, admin_pin.encode('utf8'))
python
def touch(ctx, key, policy, admin_pin, force): """ Manage touch policy for OpenPGP keys. \b KEY Key slot to set (sig, enc or aut). POLICY Touch policy to set (on, off or fixed). """ controller = ctx.obj['controller'] old_policy = controller.get_touch(key) if old_policy == TOUCH_MODE.FIXED: ctx.fail('A FIXED policy cannot be changed!') force or click.confirm('Set touch policy of {.name} key to {.name}?'.format( key, policy), abort=True, err=True) if admin_pin is None: admin_pin = click.prompt('Enter admin PIN', hide_input=True, err=True) controller.set_touch(key, policy, admin_pin.encode('utf8'))
[ "def", "touch", "(", "ctx", ",", "key", ",", "policy", ",", "admin_pin", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "old_policy", "=", "controller", ".", "get_touch", "(", "key", ")", "if", "old_policy", "==", "TOUCH_MODE", ".", "FIXED", ":", "ctx", ".", "fail", "(", "'A FIXED policy cannot be changed!'", ")", "force", "or", "click", ".", "confirm", "(", "'Set touch policy of {.name} key to {.name}?'", ".", "format", "(", "key", ",", "policy", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "if", "admin_pin", "is", "None", ":", "admin_pin", "=", "click", ".", "prompt", "(", "'Enter admin PIN'", ",", "hide_input", "=", "True", ",", "err", "=", "True", ")", "controller", ".", "set_touch", "(", "key", ",", "policy", ",", "admin_pin", ".", "encode", "(", "'utf8'", ")", ")" ]
Manage touch policy for OpenPGP keys. \b KEY Key slot to set (sig, enc or aut). POLICY Touch policy to set (on, off or fixed).
[ "Manage", "touch", "policy", "for", "OpenPGP", "keys", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L165-L183
train
Yubico/yubikey-manager
ykman/cli/opgp.py
set_pin_retries
def set_pin_retries(ctx, pw_attempts, admin_pin, force): """ Manage pin-retries. Sets the number of attempts available before locking for each PIN. PW_ATTEMPTS should be three integer values corresponding to the number of attempts for the PIN, Reset Code, and Admin PIN, respectively. """ controller = ctx.obj['controller'] resets_pins = controller.version < (4, 0, 0) if resets_pins: click.echo('WARNING: Setting PIN retries will reset the values for all ' '3 PINs!') force or click.confirm('Set PIN retry counters to: {} {} {}?'.format( *pw_attempts), abort=True, err=True) controller.set_pin_retries(*(pw_attempts + (admin_pin.encode('utf8'),))) click.echo('PIN retries successfully set.') if resets_pins: click.echo('Default PINs are set.') echo_default_pins()
python
def set_pin_retries(ctx, pw_attempts, admin_pin, force): """ Manage pin-retries. Sets the number of attempts available before locking for each PIN. PW_ATTEMPTS should be three integer values corresponding to the number of attempts for the PIN, Reset Code, and Admin PIN, respectively. """ controller = ctx.obj['controller'] resets_pins = controller.version < (4, 0, 0) if resets_pins: click.echo('WARNING: Setting PIN retries will reset the values for all ' '3 PINs!') force or click.confirm('Set PIN retry counters to: {} {} {}?'.format( *pw_attempts), abort=True, err=True) controller.set_pin_retries(*(pw_attempts + (admin_pin.encode('utf8'),))) click.echo('PIN retries successfully set.') if resets_pins: click.echo('Default PINs are set.') echo_default_pins()
[ "def", "set_pin_retries", "(", "ctx", ",", "pw_attempts", ",", "admin_pin", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "resets_pins", "=", "controller", ".", "version", "<", "(", "4", ",", "0", ",", "0", ")", "if", "resets_pins", ":", "click", ".", "echo", "(", "'WARNING: Setting PIN retries will reset the values for all '", "'3 PINs!'", ")", "force", "or", "click", ".", "confirm", "(", "'Set PIN retry counters to: {} {} {}?'", ".", "format", "(", "*", "pw_attempts", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "controller", ".", "set_pin_retries", "(", "*", "(", "pw_attempts", "+", "(", "admin_pin", ".", "encode", "(", "'utf8'", ")", ",", ")", ")", ")", "click", ".", "echo", "(", "'PIN retries successfully set.'", ")", "if", "resets_pins", ":", "click", ".", "echo", "(", "'Default PINs are set.'", ")", "echo_default_pins", "(", ")" ]
Manage pin-retries. Sets the number of attempts available before locking for each PIN. PW_ATTEMPTS should be three integer values corresponding to the number of attempts for the PIN, Reset Code, and Admin PIN, respectively.
[ "Manage", "pin", "-", "retries", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/opgp.py#L192-L212
train
Yubico/yubikey-manager
ykman/cli/piv.py
piv
def piv(ctx): """ Manage PIV Application. Examples: \b Generate an ECC P-256 private key and a self-signed certificate in slot 9a: $ ykman piv generate-key --algorithm ECCP256 9a pubkey.pem $ ykman piv generate-certificate --subject "yubico" 9a pubkey.pem \b Change the PIN from 123456 to 654321: $ ykman piv change-pin --pin 123456 --new-pin 654321 \b Reset all PIV data and restore default settings: $ ykman piv reset """ try: ctx.obj['controller'] = PivController(ctx.obj['dev'].driver) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The PIV application can't be found on this YubiKey.") raise
python
def piv(ctx): """ Manage PIV Application. Examples: \b Generate an ECC P-256 private key and a self-signed certificate in slot 9a: $ ykman piv generate-key --algorithm ECCP256 9a pubkey.pem $ ykman piv generate-certificate --subject "yubico" 9a pubkey.pem \b Change the PIN from 123456 to 654321: $ ykman piv change-pin --pin 123456 --new-pin 654321 \b Reset all PIV data and restore default settings: $ ykman piv reset """ try: ctx.obj['controller'] = PivController(ctx.obj['dev'].driver) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The PIV application can't be found on this YubiKey.") raise
[ "def", "piv", "(", "ctx", ")", ":", "try", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "PivController", "(", "ctx", ".", "obj", "[", "'dev'", "]", ".", "driver", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "\"The PIV application can't be found on this YubiKey.\"", ")", "raise" ]
Manage PIV Application. Examples: \b Generate an ECC P-256 private key and a self-signed certificate in slot 9a: $ ykman piv generate-key --algorithm ECCP256 9a pubkey.pem $ ykman piv generate-certificate --subject "yubico" 9a pubkey.pem \b Change the PIN from 123456 to 654321: $ ykman piv change-pin --pin 123456 --new-pin 654321 \b Reset all PIV data and restore default settings: $ ykman piv reset
[ "Manage", "PIV", "Application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L95-L120
train
Yubico/yubikey-manager
ykman/cli/piv.py
info
def info(ctx): """ Display status of PIV application. """ controller = ctx.obj['controller'] click.echo('PIV version: %d.%d.%d' % controller.version) # Largest possible number of PIN tries to get back is 15 tries = controller.get_pin_tries() tries = '15 or more.' if tries == 15 else tries click.echo('PIN tries remaining: %s' % tries) if controller.puk_blocked: click.echo('PUK blocked.') if controller.has_derived_key: click.echo('Management key is derived from PIN.') if controller.has_stored_key: click.echo('Management key is stored on the YubiKey, protected by PIN.') try: chuid = b2a_hex(controller.get_data(OBJ.CHUID)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: chuid = 'No data available.' click.echo('CHUID:\t' + chuid) try: ccc = b2a_hex(controller.get_data(OBJ.CAPABILITY)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: ccc = 'No data available.' click.echo('CCC: \t' + ccc) for (slot, cert) in controller.list_certificates().items(): click.echo('Slot %02x:' % slot) try: # Try to read out full DN, fallback to only CN. # Support for DN was added in crytography 2.5 subject_dn = cert.subject.rfc4514_string() issuer_dn = cert.issuer.rfc4514_string() print_dn = True except AttributeError: print_dn = False logger.debug('Failed to read DN, falling back to only CNs') subject_cn = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) subject_cn = subject_cn[0].value if subject_cn else 'None' issuer_cn = cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) issuer_cn = issuer_cn[0].value if issuer_cn else 'None' except ValueError as e: # Malformed certificates may throw ValueError logger.debug('Failed parsing certificate', exc_info=e) click.echo('\tMalformed certificate: {}'.format(e)) continue fingerprint = b2a_hex(cert.fingerprint(hashes.SHA256())).decode('ascii') algo = ALGO.from_public_key(cert.public_key()) serial = cert.serial_number not_before = cert.not_valid_before not_after = cert.not_valid_after # Print out everything click.echo('\tAlgorithm:\t%s' % algo.name) if print_dn: click.echo('\tSubject DN:\t%s' % subject_dn) click.echo('\tIssuer DN:\t%s' % issuer_dn) else: click.echo('\tSubject CN:\t%s' % subject_cn) click.echo('\tIssuer CN:\t%s' % issuer_cn) click.echo('\tSerial:\t\t%s' % serial) click.echo('\tFingerprint:\t%s' % fingerprint) click.echo('\tNot before:\t%s' % not_before) click.echo('\tNot after:\t%s' % not_after)
python
def info(ctx): """ Display status of PIV application. """ controller = ctx.obj['controller'] click.echo('PIV version: %d.%d.%d' % controller.version) # Largest possible number of PIN tries to get back is 15 tries = controller.get_pin_tries() tries = '15 or more.' if tries == 15 else tries click.echo('PIN tries remaining: %s' % tries) if controller.puk_blocked: click.echo('PUK blocked.') if controller.has_derived_key: click.echo('Management key is derived from PIN.') if controller.has_stored_key: click.echo('Management key is stored on the YubiKey, protected by PIN.') try: chuid = b2a_hex(controller.get_data(OBJ.CHUID)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: chuid = 'No data available.' click.echo('CHUID:\t' + chuid) try: ccc = b2a_hex(controller.get_data(OBJ.CAPABILITY)).decode() except APDUError as e: if e.sw == SW.NOT_FOUND: ccc = 'No data available.' click.echo('CCC: \t' + ccc) for (slot, cert) in controller.list_certificates().items(): click.echo('Slot %02x:' % slot) try: # Try to read out full DN, fallback to only CN. # Support for DN was added in crytography 2.5 subject_dn = cert.subject.rfc4514_string() issuer_dn = cert.issuer.rfc4514_string() print_dn = True except AttributeError: print_dn = False logger.debug('Failed to read DN, falling back to only CNs') subject_cn = cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) subject_cn = subject_cn[0].value if subject_cn else 'None' issuer_cn = cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) issuer_cn = issuer_cn[0].value if issuer_cn else 'None' except ValueError as e: # Malformed certificates may throw ValueError logger.debug('Failed parsing certificate', exc_info=e) click.echo('\tMalformed certificate: {}'.format(e)) continue fingerprint = b2a_hex(cert.fingerprint(hashes.SHA256())).decode('ascii') algo = ALGO.from_public_key(cert.public_key()) serial = cert.serial_number not_before = cert.not_valid_before not_after = cert.not_valid_after # Print out everything click.echo('\tAlgorithm:\t%s' % algo.name) if print_dn: click.echo('\tSubject DN:\t%s' % subject_dn) click.echo('\tIssuer DN:\t%s' % issuer_dn) else: click.echo('\tSubject CN:\t%s' % subject_cn) click.echo('\tIssuer CN:\t%s' % issuer_cn) click.echo('\tSerial:\t\t%s' % serial) click.echo('\tFingerprint:\t%s' % fingerprint) click.echo('\tNot before:\t%s' % not_before) click.echo('\tNot after:\t%s' % not_after)
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "click", ".", "echo", "(", "'PIV version: %d.%d.%d'", "%", "controller", ".", "version", ")", "# Largest possible number of PIN tries to get back is 15", "tries", "=", "controller", ".", "get_pin_tries", "(", ")", "tries", "=", "'15 or more.'", "if", "tries", "==", "15", "else", "tries", "click", ".", "echo", "(", "'PIN tries remaining: %s'", "%", "tries", ")", "if", "controller", ".", "puk_blocked", ":", "click", ".", "echo", "(", "'PUK blocked.'", ")", "if", "controller", ".", "has_derived_key", ":", "click", ".", "echo", "(", "'Management key is derived from PIN.'", ")", "if", "controller", ".", "has_stored_key", ":", "click", ".", "echo", "(", "'Management key is stored on the YubiKey, protected by PIN.'", ")", "try", ":", "chuid", "=", "b2a_hex", "(", "controller", ".", "get_data", "(", "OBJ", ".", "CHUID", ")", ")", ".", "decode", "(", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "chuid", "=", "'No data available.'", "click", ".", "echo", "(", "'CHUID:\\t'", "+", "chuid", ")", "try", ":", "ccc", "=", "b2a_hex", "(", "controller", ".", "get_data", "(", "OBJ", ".", "CAPABILITY", ")", ")", ".", "decode", "(", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ccc", "=", "'No data available.'", "click", ".", "echo", "(", "'CCC: \\t'", "+", "ccc", ")", "for", "(", "slot", ",", "cert", ")", "in", "controller", ".", "list_certificates", "(", ")", ".", "items", "(", ")", ":", "click", ".", "echo", "(", "'Slot %02x:'", "%", "slot", ")", "try", ":", "# Try to read out full DN, fallback to only CN.", "# Support for DN was added in crytography 2.5", "subject_dn", "=", "cert", ".", "subject", ".", "rfc4514_string", "(", ")", "issuer_dn", "=", "cert", ".", "issuer", ".", "rfc4514_string", "(", ")", "print_dn", "=", "True", "except", "AttributeError", ":", "print_dn", "=", "False", "logger", ".", "debug", "(", "'Failed to read DN, falling back to only CNs'", ")", "subject_cn", "=", "cert", ".", "subject", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "subject_cn", "=", "subject_cn", "[", "0", "]", ".", "value", "if", "subject_cn", "else", "'None'", "issuer_cn", "=", "cert", ".", "issuer", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "issuer_cn", "=", "issuer_cn", "[", "0", "]", ".", "value", "if", "issuer_cn", "else", "'None'", "except", "ValueError", "as", "e", ":", "# Malformed certificates may throw ValueError", "logger", ".", "debug", "(", "'Failed parsing certificate'", ",", "exc_info", "=", "e", ")", "click", ".", "echo", "(", "'\\tMalformed certificate: {}'", ".", "format", "(", "e", ")", ")", "continue", "fingerprint", "=", "b2a_hex", "(", "cert", ".", "fingerprint", "(", "hashes", ".", "SHA256", "(", ")", ")", ")", ".", "decode", "(", "'ascii'", ")", "algo", "=", "ALGO", ".", "from_public_key", "(", "cert", ".", "public_key", "(", ")", ")", "serial", "=", "cert", ".", "serial_number", "not_before", "=", "cert", ".", "not_valid_before", "not_after", "=", "cert", ".", "not_valid_after", "# Print out everything", "click", ".", "echo", "(", "'\\tAlgorithm:\\t%s'", "%", "algo", ".", "name", ")", "if", "print_dn", ":", "click", ".", "echo", "(", "'\\tSubject DN:\\t%s'", "%", "subject_dn", ")", "click", ".", "echo", "(", "'\\tIssuer DN:\\t%s'", "%", "issuer_dn", ")", "else", ":", "click", ".", "echo", "(", "'\\tSubject CN:\\t%s'", "%", "subject_cn", ")", "click", ".", "echo", "(", "'\\tIssuer CN:\\t%s'", "%", "issuer_cn", ")", "click", ".", "echo", "(", "'\\tSerial:\\t\\t%s'", "%", "serial", ")", "click", ".", "echo", "(", "'\\tFingerprint:\\t%s'", "%", "fingerprint", ")", "click", ".", "echo", "(", "'\\tNot before:\\t%s'", "%", "not_before", ")", "click", ".", "echo", "(", "'\\tNot after:\\t%s'", "%", "not_after", ")" ]
Display status of PIV application.
[ "Display", "status", "of", "PIV", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L125-L195
train
Yubico/yubikey-manager
ykman/cli/piv.py
reset
def reset(ctx): """ Reset all PIV data. This action will wipe all data and restore factory settings for the PIV application on your YubiKey. """ click.echo('Resetting PIV data...') ctx.obj['controller'].reset() click.echo( 'Success! All PIV data have been cleared from your YubiKey.') click.echo('Your YubiKey now has the default PIN, PUK and Management Key:') click.echo('\tPIN:\t123456') click.echo('\tPUK:\t12345678') click.echo( '\tManagement Key:\t010203040506070801020304050607080102030405060708')
python
def reset(ctx): """ Reset all PIV data. This action will wipe all data and restore factory settings for the PIV application on your YubiKey. """ click.echo('Resetting PIV data...') ctx.obj['controller'].reset() click.echo( 'Success! All PIV data have been cleared from your YubiKey.') click.echo('Your YubiKey now has the default PIN, PUK and Management Key:') click.echo('\tPIN:\t123456') click.echo('\tPUK:\t12345678') click.echo( '\tManagement Key:\t010203040506070801020304050607080102030405060708')
[ "def", "reset", "(", "ctx", ")", ":", "click", ".", "echo", "(", "'Resetting PIV data...'", ")", "ctx", ".", "obj", "[", "'controller'", "]", ".", "reset", "(", ")", "click", ".", "echo", "(", "'Success! All PIV data have been cleared from your YubiKey.'", ")", "click", ".", "echo", "(", "'Your YubiKey now has the default PIN, PUK and Management Key:'", ")", "click", ".", "echo", "(", "'\\tPIN:\\t123456'", ")", "click", ".", "echo", "(", "'\\tPUK:\\t12345678'", ")", "click", ".", "echo", "(", "'\\tManagement Key:\\t010203040506070801020304050607080102030405060708'", ")" ]
Reset all PIV data. This action will wipe all data and restore factory settings for the PIV application on your YubiKey.
[ "Reset", "all", "PIV", "data", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L203-L219
train
Yubico/yubikey-manager
ykman/cli/piv.py
generate_key
def generate_key( ctx, slot, public_key_output, management_key, pin, algorithm, format, pin_policy, touch_policy): """ Generate an asymmetric key pair. The private key is generated on the YubiKey, and written to one of the slots. \b SLOT PIV slot where private key should be stored. PUBLIC-KEY File containing the generated public key. Use '-' to use stdout. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) algorithm_id = ALGO.from_string(algorithm) if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) try: public_key = controller.generate_key( slot, algorithm_id, pin_policy, touch_policy) except UnsupportedAlgorithm: ctx.fail('Algorithm {} is not supported by this ' 'YubiKey.'.format(algorithm)) key_encoding = format public_key_output.write(public_key.public_bytes( encoding=key_encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo))
python
def generate_key( ctx, slot, public_key_output, management_key, pin, algorithm, format, pin_policy, touch_policy): """ Generate an asymmetric key pair. The private key is generated on the YubiKey, and written to one of the slots. \b SLOT PIV slot where private key should be stored. PUBLIC-KEY File containing the generated public key. Use '-' to use stdout. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) algorithm_id = ALGO.from_string(algorithm) if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) try: public_key = controller.generate_key( slot, algorithm_id, pin_policy, touch_policy) except UnsupportedAlgorithm: ctx.fail('Algorithm {} is not supported by this ' 'YubiKey.'.format(algorithm)) key_encoding = format public_key_output.write(public_key.public_bytes( encoding=key_encoding, format=serialization.PublicFormat.SubjectPublicKeyInfo))
[ "def", "generate_key", "(", "ctx", ",", "slot", ",", "public_key_output", ",", "management_key", ",", "pin", ",", "algorithm", ",", "format", ",", "pin_policy", ",", "touch_policy", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "algorithm_id", "=", "ALGO", ".", "from_string", "(", "algorithm", ")", "if", "pin_policy", ":", "pin_policy", "=", "PIN_POLICY", ".", "from_string", "(", "pin_policy", ")", "if", "touch_policy", ":", "touch_policy", "=", "TOUCH_POLICY", ".", "from_string", "(", "touch_policy", ")", "_check_pin_policy", "(", "ctx", ",", "dev", ",", "controller", ",", "pin_policy", ")", "_check_touch_policy", "(", "ctx", ",", "controller", ",", "touch_policy", ")", "try", ":", "public_key", "=", "controller", ".", "generate_key", "(", "slot", ",", "algorithm_id", ",", "pin_policy", ",", "touch_policy", ")", "except", "UnsupportedAlgorithm", ":", "ctx", ".", "fail", "(", "'Algorithm {} is not supported by this '", "'YubiKey.'", ".", "format", "(", "algorithm", ")", ")", "key_encoding", "=", "format", "public_key_output", ".", "write", "(", "public_key", ".", "public_bytes", "(", "encoding", "=", "key_encoding", ",", "format", "=", "serialization", ".", "PublicFormat", ".", "SubjectPublicKeyInfo", ")", ")" ]
Generate an asymmetric key pair. The private key is generated on the YubiKey, and written to one of the slots. \b SLOT PIV slot where private key should be stored. PUBLIC-KEY File containing the generated public key. Use '-' to use stdout.
[ "Generate", "an", "asymmetric", "key", "pair", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L237-L279
train
Yubico/yubikey-manager
ykman/cli/piv.py
import_certificate
def import_certificate( ctx, slot, management_key, pin, cert, password, verify): """ Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = cert.read() while True: if password is not None: password = password.encode() try: certs = parse_certificates(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt certificate', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if len(certs) > 1: # If multiple certs, only import leaf. # Leaf is the cert with a subject that is not an issuer in the chain. leafs = get_leaf_certificates(certs) cert_to_import = leafs[0] else: cert_to_import = certs[0] def do_import(retry=True): try: controller.import_certificate( slot, cert_to_import, verify=verify, touch_callback=prompt_for_touch) except KeypairMismatch: ctx.fail('This certificate is not tied to the private key in the ' '{} slot.'.format(slot.name)) except APDUError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED and retry: _verify_pin(ctx, controller, pin) do_import(retry=False) else: raise do_import()
python
def import_certificate( ctx, slot, management_key, pin, cert, password, verify): """ Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = cert.read() while True: if password is not None: password = password.encode() try: certs = parse_certificates(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt certificate', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if len(certs) > 1: # If multiple certs, only import leaf. # Leaf is the cert with a subject that is not an issuer in the chain. leafs = get_leaf_certificates(certs) cert_to_import = leafs[0] else: cert_to_import = certs[0] def do_import(retry=True): try: controller.import_certificate( slot, cert_to_import, verify=verify, touch_callback=prompt_for_touch) except KeypairMismatch: ctx.fail('This certificate is not tied to the private key in the ' '{} slot.'.format(slot.name)) except APDUError as e: if e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED and retry: _verify_pin(ctx, controller, pin) do_import(retry=False) else: raise do_import()
[ "def", "import_certificate", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "cert", ",", "password", ",", "verify", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "data", "=", "cert", ".", "read", "(", ")", "while", "True", ":", "if", "password", "is", "not", "None", ":", "password", "=", "password", ".", "encode", "(", ")", "try", ":", "certs", "=", "parse_certificates", "(", "data", ",", "password", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "if", "password", "is", "None", ":", "password", "=", "click", ".", "prompt", "(", "'Enter password to decrypt certificate'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "continue", "else", ":", "password", "=", "None", "click", ".", "echo", "(", "'Wrong password.'", ")", "continue", "break", "if", "len", "(", "certs", ")", ">", "1", ":", "# If multiple certs, only import leaf.", "# Leaf is the cert with a subject that is not an issuer in the chain.", "leafs", "=", "get_leaf_certificates", "(", "certs", ")", "cert_to_import", "=", "leafs", "[", "0", "]", "else", ":", "cert_to_import", "=", "certs", "[", "0", "]", "def", "do_import", "(", "retry", "=", "True", ")", ":", "try", ":", "controller", ".", "import_certificate", "(", "slot", ",", "cert_to_import", ",", "verify", "=", "verify", ",", "touch_callback", "=", "prompt_for_touch", ")", "except", "KeypairMismatch", ":", "ctx", ".", "fail", "(", "'This certificate is not tied to the private key in the '", "'{} slot.'", ".", "format", "(", "slot", ".", "name", ")", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "SECURITY_CONDITION_NOT_SATISFIED", "and", "retry", ":", "_verify_pin", "(", "ctx", ",", "controller", ",", "pin", ")", "do_import", "(", "retry", "=", "False", ")", "else", ":", "raise", "do_import", "(", ")" ]
Import a X.509 certificate. Write a certificate to one of the slots on the YubiKey. \b SLOT PIV slot to import the certificate to. CERTIFICATE File containing the certificate. Use '-' to use stdin.
[ "Import", "a", "X", ".", "509", "certificate", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L293-L353
train
Yubico/yubikey-manager
ykman/cli/piv.py
import_key
def import_key( ctx, slot, management_key, pin, private_key, pin_policy, touch_policy, password): """ Import a private key. Write a private key to one of the slots on the YubiKey. \b SLOT PIV slot to import the private key to. PRIVATE-KEY File containing the private key. Use '-' to use stdin. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = private_key.read() while True: if password is not None: password = password.encode() try: private_key = parse_private_key(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt key', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) _check_key_size(ctx, controller, private_key) controller.import_key( slot, private_key, pin_policy, touch_policy)
python
def import_key( ctx, slot, management_key, pin, private_key, pin_policy, touch_policy, password): """ Import a private key. Write a private key to one of the slots on the YubiKey. \b SLOT PIV slot to import the private key to. PRIVATE-KEY File containing the private key. Use '-' to use stdin. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) data = private_key.read() while True: if password is not None: password = password.encode() try: private_key = parse_private_key(data, password) except (ValueError, TypeError): if password is None: password = click.prompt( 'Enter password to decrypt key', default='', hide_input=True, show_default=False, err=True) continue else: password = None click.echo('Wrong password.') continue break if pin_policy: pin_policy = PIN_POLICY.from_string(pin_policy) if touch_policy: touch_policy = TOUCH_POLICY.from_string(touch_policy) _check_pin_policy(ctx, dev, controller, pin_policy) _check_touch_policy(ctx, controller, touch_policy) _check_key_size(ctx, controller, private_key) controller.import_key( slot, private_key, pin_policy, touch_policy)
[ "def", "import_key", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "private_key", ",", "pin_policy", ",", "touch_policy", ",", "password", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "data", "=", "private_key", ".", "read", "(", ")", "while", "True", ":", "if", "password", "is", "not", "None", ":", "password", "=", "password", ".", "encode", "(", ")", "try", ":", "private_key", "=", "parse_private_key", "(", "data", ",", "password", ")", "except", "(", "ValueError", ",", "TypeError", ")", ":", "if", "password", "is", "None", ":", "password", "=", "click", ".", "prompt", "(", "'Enter password to decrypt key'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "continue", "else", ":", "password", "=", "None", "click", ".", "echo", "(", "'Wrong password.'", ")", "continue", "break", "if", "pin_policy", ":", "pin_policy", "=", "PIN_POLICY", ".", "from_string", "(", "pin_policy", ")", "if", "touch_policy", ":", "touch_policy", "=", "TOUCH_POLICY", ".", "from_string", "(", "touch_policy", ")", "_check_pin_policy", "(", "ctx", ",", "dev", ",", "controller", ",", "pin_policy", ")", "_check_touch_policy", "(", "ctx", ",", "controller", ",", "touch_policy", ")", "_check_key_size", "(", "ctx", ",", "controller", ",", "private_key", ")", "controller", ".", "import_key", "(", "slot", ",", "private_key", ",", "pin_policy", ",", "touch_policy", ")" ]
Import a private key. Write a private key to one of the slots on the YubiKey. \b SLOT PIV slot to import the private key to. PRIVATE-KEY File containing the private key. Use '-' to use stdin.
[ "Import", "a", "private", "key", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L366-L416
train
Yubico/yubikey-manager
ykman/cli/piv.py
export_certificate
def export_certificate(ctx, slot, format, certificate): """ Export a X.509 certificate. Reads a certificate from one of the slots on the YubiKey. \b SLOT PIV slot to read certificate from. CERTIFICATE File to write certificate to. Use '-' to use stdout. """ controller = ctx.obj['controller'] try: cert = controller.read_certificate(slot) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No certificate found.') else: logger.error('Failed to read certificate from slot %s', slot, exc_info=e) certificate.write(cert.public_bytes(encoding=format))
python
def export_certificate(ctx, slot, format, certificate): """ Export a X.509 certificate. Reads a certificate from one of the slots on the YubiKey. \b SLOT PIV slot to read certificate from. CERTIFICATE File to write certificate to. Use '-' to use stdout. """ controller = ctx.obj['controller'] try: cert = controller.read_certificate(slot) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No certificate found.') else: logger.error('Failed to read certificate from slot %s', slot, exc_info=e) certificate.write(cert.public_bytes(encoding=format))
[ "def", "export_certificate", "(", "ctx", ",", "slot", ",", "format", ",", "certificate", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "try", ":", "cert", "=", "controller", ".", "read_certificate", "(", "slot", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "'No certificate found.'", ")", "else", ":", "logger", ".", "error", "(", "'Failed to read certificate from slot %s'", ",", "slot", ",", "exc_info", "=", "e", ")", "certificate", ".", "write", "(", "cert", ".", "public_bytes", "(", "encoding", "=", "format", ")", ")" ]
Export a X.509 certificate. Reads a certificate from one of the slots on the YubiKey. \b SLOT PIV slot to read certificate from. CERTIFICATE File to write certificate to. Use '-' to use stdout.
[ "Export", "a", "X", ".", "509", "certificate", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L449-L468
train
Yubico/yubikey-manager
ykman/cli/piv.py
set_chuid
def set_chuid(ctx, management_key, pin): """ Generate and set a CHUID on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_chuid()
python
def set_chuid(ctx, management_key, pin): """ Generate and set a CHUID on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_chuid()
[ "def", "set_chuid", "(", "ctx", ",", "management_key", ",", "pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "controller", ".", "update_chuid", "(", ")" ]
Generate and set a CHUID on the YubiKey.
[ "Generate", "and", "set", "a", "CHUID", "on", "the", "YubiKey", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L475-L481
train
Yubico/yubikey-manager
ykman/cli/piv.py
set_ccc
def set_ccc(ctx, management_key, pin): """ Generate and set a CCC on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_ccc()
python
def set_ccc(ctx, management_key, pin): """ Generate and set a CCC on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.update_ccc()
[ "def", "set_ccc", "(", "ctx", ",", "management_key", ",", "pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "controller", ".", "update_ccc", "(", ")" ]
Generate and set a CCC on the YubiKey.
[ "Generate", "and", "set", "a", "CCC", "on", "the", "YubiKey", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L488-L494
train
Yubico/yubikey-manager
ykman/cli/piv.py
generate_certificate
def generate_certificate( ctx, slot, management_key, pin, public_key, subject, valid_days): """ Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT PIV slot where private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=True) data = public_key.read() public_key = serialization.load_pem_public_key( data, default_backend()) now = datetime.datetime.now() valid_to = now + datetime.timedelta(days=valid_days) try: controller.generate_self_signed_certificate( slot, public_key, subject, now, valid_to, touch_callback=prompt_for_touch) except APDUError as e: logger.error('Failed to generate certificate for slot %s', slot, exc_info=e) ctx.fail('Certificate generation failed.')
python
def generate_certificate( ctx, slot, management_key, pin, public_key, subject, valid_days): """ Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT PIV slot where private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=True) data = public_key.read() public_key = serialization.load_pem_public_key( data, default_backend()) now = datetime.datetime.now() valid_to = now + datetime.timedelta(days=valid_days) try: controller.generate_self_signed_certificate( slot, public_key, subject, now, valid_to, touch_callback=prompt_for_touch) except APDUError as e: logger.error('Failed to generate certificate for slot %s', slot, exc_info=e) ctx.fail('Certificate generation failed.')
[ "def", "generate_certificate", "(", "ctx", ",", "slot", ",", "management_key", ",", "pin", ",", "public_key", ",", "subject", ",", "valid_days", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ",", "require_pin_and_key", "=", "True", ")", "data", "=", "public_key", ".", "read", "(", ")", "public_key", "=", "serialization", ".", "load_pem_public_key", "(", "data", ",", "default_backend", "(", ")", ")", "now", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "valid_to", "=", "now", "+", "datetime", ".", "timedelta", "(", "days", "=", "valid_days", ")", "try", ":", "controller", ".", "generate_self_signed_certificate", "(", "slot", ",", "public_key", ",", "subject", ",", "now", ",", "valid_to", ",", "touch_callback", "=", "prompt_for_touch", ")", "except", "APDUError", "as", "e", ":", "logger", ".", "error", "(", "'Failed to generate certificate for slot %s'", ",", "slot", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Certificate generation failed.'", ")" ]
Generate a self-signed X.509 certificate. A self-signed certificate is generated and written to one of the slots on the YubiKey. A private key need to exist in the slot. \b SLOT PIV slot where private key is stored. PUBLIC-KEY File containing a public key. Use '-' to use stdin.
[ "Generate", "a", "self", "-", "signed", "X", ".", "509", "certificate", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L542-L573
train
Yubico/yubikey-manager
ykman/cli/piv.py
change_pin
def change_pin(ctx, pin, new_pin): """ Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric digits are recommended. """ controller = ctx.obj['controller'] if not pin: pin = _prompt_pin(ctx, prompt='Enter your current PIN') if not new_pin: new_pin = click.prompt( 'Enter your new PIN', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(pin): ctx.fail('Current PIN must be between 6 and 8 characters long.') if not _valid_pin_length(new_pin): ctx.fail('New PIN must be between 6 and 8 characters long.') try: controller.change_pin(pin, new_pin) click.echo('New PIN set.') except AuthenticationBlocked as e: logger.debug('PIN is blocked.', exc_info=e) ctx.fail('PIN is blocked.') except WrongPin as e: logger.debug( 'Failed to change PIN, %d tries left', e.tries_left, exc_info=e) ctx.fail('PIN change failed - %d tries left.' % e.tries_left)
python
def change_pin(ctx, pin, new_pin): """ Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric digits are recommended. """ controller = ctx.obj['controller'] if not pin: pin = _prompt_pin(ctx, prompt='Enter your current PIN') if not new_pin: new_pin = click.prompt( 'Enter your new PIN', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(pin): ctx.fail('Current PIN must be between 6 and 8 characters long.') if not _valid_pin_length(new_pin): ctx.fail('New PIN must be between 6 and 8 characters long.') try: controller.change_pin(pin, new_pin) click.echo('New PIN set.') except AuthenticationBlocked as e: logger.debug('PIN is blocked.', exc_info=e) ctx.fail('PIN is blocked.') except WrongPin as e: logger.debug( 'Failed to change PIN, %d tries left', e.tries_left, exc_info=e) ctx.fail('PIN change failed - %d tries left.' % e.tries_left)
[ "def", "change_pin", "(", "ctx", ",", "pin", ",", "new_pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "pin", ":", "pin", "=", "_prompt_pin", "(", "ctx", ",", "prompt", "=", "'Enter your current PIN'", ")", "if", "not", "new_pin", ":", "new_pin", "=", "click", ".", "prompt", "(", "'Enter your new PIN'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "confirmation_prompt", "=", "True", ",", "err", "=", "True", ")", "if", "not", "_valid_pin_length", "(", "pin", ")", ":", "ctx", ".", "fail", "(", "'Current PIN must be between 6 and 8 characters long.'", ")", "if", "not", "_valid_pin_length", "(", "new_pin", ")", ":", "ctx", ".", "fail", "(", "'New PIN must be between 6 and 8 characters long.'", ")", "try", ":", "controller", ".", "change_pin", "(", "pin", ",", "new_pin", ")", "click", ".", "echo", "(", "'New PIN set.'", ")", "except", "AuthenticationBlocked", "as", "e", ":", "logger", ".", "debug", "(", "'PIN is blocked.'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PIN is blocked.'", ")", "except", "WrongPin", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to change PIN, %d tries left'", ",", "e", ".", "tries_left", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PIN change failed - %d tries left.'", "%", "e", ".", "tries_left", ")" ]
Change the PIN code. The PIN must be between 6 and 8 characters long, and supports any type of alphanumeric characters. For cross-platform compatibility, numeric digits are recommended.
[ "Change", "the", "PIN", "code", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L635-L670
train
Yubico/yubikey-manager
ykman/cli/piv.py
change_puk
def change_puk(ctx, puk, new_puk): """ Change the PUK code. If the PIN is lost or blocked it can be reset using a PUK. The PUK must be between 6 and 8 characters long, and supports any type of alphanumeric characters. """ controller = ctx.obj['controller'] if not puk: puk = _prompt_pin(ctx, prompt='Enter your current PUK') if not new_puk: new_puk = click.prompt( 'Enter your new PUK', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(puk): ctx.fail('Current PUK must be between 6 and 8 characters long.') if not _valid_pin_length(new_puk): ctx.fail('New PUK must be between 6 and 8 characters long.') try: controller.change_puk(puk, new_puk) click.echo('New PUK set.') except AuthenticationBlocked as e: logger.debug('PUK is blocked.', exc_info=e) ctx.fail('PUK is blocked.') except WrongPuk as e: logger.debug( 'Failed to change PUK, %d tries left', e.tries_left, exc_info=e) ctx.fail('PUK change failed - %d tries left.' % e.tries_left)
python
def change_puk(ctx, puk, new_puk): """ Change the PUK code. If the PIN is lost or blocked it can be reset using a PUK. The PUK must be between 6 and 8 characters long, and supports any type of alphanumeric characters. """ controller = ctx.obj['controller'] if not puk: puk = _prompt_pin(ctx, prompt='Enter your current PUK') if not new_puk: new_puk = click.prompt( 'Enter your new PUK', default='', hide_input=True, show_default=False, confirmation_prompt=True, err=True) if not _valid_pin_length(puk): ctx.fail('Current PUK must be between 6 and 8 characters long.') if not _valid_pin_length(new_puk): ctx.fail('New PUK must be between 6 and 8 characters long.') try: controller.change_puk(puk, new_puk) click.echo('New PUK set.') except AuthenticationBlocked as e: logger.debug('PUK is blocked.', exc_info=e) ctx.fail('PUK is blocked.') except WrongPuk as e: logger.debug( 'Failed to change PUK, %d tries left', e.tries_left, exc_info=e) ctx.fail('PUK change failed - %d tries left.' % e.tries_left)
[ "def", "change_puk", "(", "ctx", ",", "puk", ",", "new_puk", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "puk", ":", "puk", "=", "_prompt_pin", "(", "ctx", ",", "prompt", "=", "'Enter your current PUK'", ")", "if", "not", "new_puk", ":", "new_puk", "=", "click", ".", "prompt", "(", "'Enter your new PUK'", ",", "default", "=", "''", ",", "hide_input", "=", "True", ",", "show_default", "=", "False", ",", "confirmation_prompt", "=", "True", ",", "err", "=", "True", ")", "if", "not", "_valid_pin_length", "(", "puk", ")", ":", "ctx", ".", "fail", "(", "'Current PUK must be between 6 and 8 characters long.'", ")", "if", "not", "_valid_pin_length", "(", "new_puk", ")", ":", "ctx", ".", "fail", "(", "'New PUK must be between 6 and 8 characters long.'", ")", "try", ":", "controller", ".", "change_puk", "(", "puk", ",", "new_puk", ")", "click", ".", "echo", "(", "'New PUK set.'", ")", "except", "AuthenticationBlocked", "as", "e", ":", "logger", ".", "debug", "(", "'PUK is blocked.'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PUK is blocked.'", ")", "except", "WrongPuk", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to change PUK, %d tries left'", ",", "e", ".", "tries_left", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PUK change failed - %d tries left.'", "%", "e", ".", "tries_left", ")" ]
Change the PUK code. If the PIN is lost or blocked it can be reset using a PUK. The PUK must be between 6 and 8 characters long, and supports any type of alphanumeric characters.
[ "Change", "the", "PUK", "code", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L677-L711
train
Yubico/yubikey-manager
ykman/cli/piv.py
change_management_key
def change_management_key( ctx, management_key, pin, new_management_key, touch, protect, generate, force): """ Change the management key. Management functionality is guarded by a 24 byte management key. This key is required for administrative tasks, such as generating key pairs. A random key may be generated and stored on the YubiKey, protected by PIN. """ controller = ctx.obj['controller'] pin_verified = _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=protect, mgm_key_prompt='Enter your current management key ' '[blank to use default key]', no_prompt=force) if new_management_key and generate: ctx.fail('Invalid options: --new-management-key conflicts with ' '--generate') # Touch not supported on NEO. if touch and controller.version < (4, 0, 0): ctx.fail('Require touch not supported on this YubiKey.') # If an old stored key needs to be cleared, the PIN is needed. if not pin_verified and controller.has_stored_key: if pin: _verify_pin(ctx, controller, pin, no_prompt=force) elif not force: click.confirm( 'The current management key is stored on the YubiKey' ' and will not be cleared if no PIN is provided. Continue?', abort=True, err=True) if not new_management_key and not protect: if generate: new_management_key = generate_random_management_key() if not protect: click.echo( 'Generated management key: {}'.format( b2a_hex(new_management_key).decode('utf-8'))) elif force: ctx.fail('New management key not given. Please remove the --force ' 'flag, or set the --generate flag or the ' '--new-management-key option.') else: new_management_key = click.prompt( 'Enter your new management key', hide_input=True, confirmation_prompt=True, err=True) if new_management_key and type(new_management_key) is not bytes: try: new_management_key = a2b_hex(new_management_key) except Exception: ctx.fail('New management key has the wrong format.') try: controller.set_mgm_key( new_management_key, touch=touch, store_on_device=protect) except APDUError as e: logger.error('Failed to change management key', exc_info=e) ctx.fail('Changing the management key failed.')
python
def change_management_key( ctx, management_key, pin, new_management_key, touch, protect, generate, force): """ Change the management key. Management functionality is guarded by a 24 byte management key. This key is required for administrative tasks, such as generating key pairs. A random key may be generated and stored on the YubiKey, protected by PIN. """ controller = ctx.obj['controller'] pin_verified = _ensure_authenticated( ctx, controller, pin, management_key, require_pin_and_key=protect, mgm_key_prompt='Enter your current management key ' '[blank to use default key]', no_prompt=force) if new_management_key and generate: ctx.fail('Invalid options: --new-management-key conflicts with ' '--generate') # Touch not supported on NEO. if touch and controller.version < (4, 0, 0): ctx.fail('Require touch not supported on this YubiKey.') # If an old stored key needs to be cleared, the PIN is needed. if not pin_verified and controller.has_stored_key: if pin: _verify_pin(ctx, controller, pin, no_prompt=force) elif not force: click.confirm( 'The current management key is stored on the YubiKey' ' and will not be cleared if no PIN is provided. Continue?', abort=True, err=True) if not new_management_key and not protect: if generate: new_management_key = generate_random_management_key() if not protect: click.echo( 'Generated management key: {}'.format( b2a_hex(new_management_key).decode('utf-8'))) elif force: ctx.fail('New management key not given. Please remove the --force ' 'flag, or set the --generate flag or the ' '--new-management-key option.') else: new_management_key = click.prompt( 'Enter your new management key', hide_input=True, confirmation_prompt=True, err=True) if new_management_key and type(new_management_key) is not bytes: try: new_management_key = a2b_hex(new_management_key) except Exception: ctx.fail('New management key has the wrong format.') try: controller.set_mgm_key( new_management_key, touch=touch, store_on_device=protect) except APDUError as e: logger.error('Failed to change management key', exc_info=e) ctx.fail('Changing the management key failed.')
[ "def", "change_management_key", "(", "ctx", ",", "management_key", ",", "pin", ",", "new_management_key", ",", "touch", ",", "protect", ",", "generate", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "pin_verified", "=", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ",", "require_pin_and_key", "=", "protect", ",", "mgm_key_prompt", "=", "'Enter your current management key '", "'[blank to use default key]'", ",", "no_prompt", "=", "force", ")", "if", "new_management_key", "and", "generate", ":", "ctx", ".", "fail", "(", "'Invalid options: --new-management-key conflicts with '", "'--generate'", ")", "# Touch not supported on NEO.", "if", "touch", "and", "controller", ".", "version", "<", "(", "4", ",", "0", ",", "0", ")", ":", "ctx", ".", "fail", "(", "'Require touch not supported on this YubiKey.'", ")", "# If an old stored key needs to be cleared, the PIN is needed.", "if", "not", "pin_verified", "and", "controller", ".", "has_stored_key", ":", "if", "pin", ":", "_verify_pin", "(", "ctx", ",", "controller", ",", "pin", ",", "no_prompt", "=", "force", ")", "elif", "not", "force", ":", "click", ".", "confirm", "(", "'The current management key is stored on the YubiKey'", "' and will not be cleared if no PIN is provided. Continue?'", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "if", "not", "new_management_key", "and", "not", "protect", ":", "if", "generate", ":", "new_management_key", "=", "generate_random_management_key", "(", ")", "if", "not", "protect", ":", "click", ".", "echo", "(", "'Generated management key: {}'", ".", "format", "(", "b2a_hex", "(", "new_management_key", ")", ".", "decode", "(", "'utf-8'", ")", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'New management key not given. Please remove the --force '", "'flag, or set the --generate flag or the '", "'--new-management-key option.'", ")", "else", ":", "new_management_key", "=", "click", ".", "prompt", "(", "'Enter your new management key'", ",", "hide_input", "=", "True", ",", "confirmation_prompt", "=", "True", ",", "err", "=", "True", ")", "if", "new_management_key", "and", "type", "(", "new_management_key", ")", "is", "not", "bytes", ":", "try", ":", "new_management_key", "=", "a2b_hex", "(", "new_management_key", ")", "except", "Exception", ":", "ctx", ".", "fail", "(", "'New management key has the wrong format.'", ")", "try", ":", "controller", ".", "set_mgm_key", "(", "new_management_key", ",", "touch", "=", "touch", ",", "store_on_device", "=", "protect", ")", "except", "APDUError", "as", "e", ":", "logger", ".", "error", "(", "'Failed to change management key'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Changing the management key failed.'", ")" ]
Change the management key. Management functionality is guarded by a 24 byte management key. This key is required for administrative tasks, such as generating key pairs. A random key may be generated and stored on the YubiKey, protected by PIN.
[ "Change", "the", "management", "key", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L735-L802
train
Yubico/yubikey-manager
ykman/cli/piv.py
unblock_pin
def unblock_pin(ctx, puk, new_pin): """ Unblock the PIN. Reset the PIN using the PUK code. """ controller = ctx.obj['controller'] if not puk: puk = click.prompt( 'Enter PUK', default='', show_default=False, hide_input=True, err=True) if not new_pin: new_pin = click.prompt( 'Enter a new PIN', default='', show_default=False, hide_input=True, err=True) controller.unblock_pin(puk, new_pin)
python
def unblock_pin(ctx, puk, new_pin): """ Unblock the PIN. Reset the PIN using the PUK code. """ controller = ctx.obj['controller'] if not puk: puk = click.prompt( 'Enter PUK', default='', show_default=False, hide_input=True, err=True) if not new_pin: new_pin = click.prompt( 'Enter a new PIN', default='', show_default=False, hide_input=True, err=True) controller.unblock_pin(puk, new_pin)
[ "def", "unblock_pin", "(", "ctx", ",", "puk", ",", "new_pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "puk", ":", "puk", "=", "click", ".", "prompt", "(", "'Enter PUK'", ",", "default", "=", "''", ",", "show_default", "=", "False", ",", "hide_input", "=", "True", ",", "err", "=", "True", ")", "if", "not", "new_pin", ":", "new_pin", "=", "click", ".", "prompt", "(", "'Enter a new PIN'", ",", "default", "=", "''", ",", "show_default", "=", "False", ",", "hide_input", "=", "True", ",", "err", "=", "True", ")", "controller", ".", "unblock_pin", "(", "puk", ",", "new_pin", ")" ]
Unblock the PIN. Reset the PIN using the PUK code.
[ "Unblock", "the", "PIN", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L809-L824
train
Yubico/yubikey-manager
ykman/cli/piv.py
read_object
def read_object(ctx, pin, object_id): """ Read arbitrary PIV object. Read PIV object by providing the object id. \b OBJECT-ID Id of PIV object in HEX. """ controller = ctx.obj['controller'] def do_read_object(retry=True): try: click.echo(controller.get_data(object_id)) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No data found.') elif e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: _verify_pin(ctx, controller, pin) do_read_object(retry=False) else: raise do_read_object()
python
def read_object(ctx, pin, object_id): """ Read arbitrary PIV object. Read PIV object by providing the object id. \b OBJECT-ID Id of PIV object in HEX. """ controller = ctx.obj['controller'] def do_read_object(retry=True): try: click.echo(controller.get_data(object_id)) except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail('No data found.') elif e.sw == SW.SECURITY_CONDITION_NOT_SATISFIED: _verify_pin(ctx, controller, pin) do_read_object(retry=False) else: raise do_read_object()
[ "def", "read_object", "(", "ctx", ",", "pin", ",", "object_id", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "def", "do_read_object", "(", "retry", "=", "True", ")", ":", "try", ":", "click", ".", "echo", "(", "controller", ".", "get_data", "(", "object_id", ")", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "'No data found.'", ")", "elif", "e", ".", "sw", "==", "SW", ".", "SECURITY_CONDITION_NOT_SATISFIED", ":", "_verify_pin", "(", "ctx", ",", "controller", ",", "pin", ")", "do_read_object", "(", "retry", "=", "False", ")", "else", ":", "raise", "do_read_object", "(", ")" ]
Read arbitrary PIV object. Read PIV object by providing the object id. \b OBJECT-ID Id of PIV object in HEX.
[ "Read", "arbitrary", "PIV", "object", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L833-L857
train
Yubico/yubikey-manager
ykman/cli/piv.py
write_object
def write_object(ctx, pin, management_key, object_id, data): """ Write an arbitrary PIV object. Write a PIV object by providing the object id. Yubico writable PIV objects are available in the range 5f0000 - 5fffff. \b OBJECT-ID Id of PIV object in HEX. DATA File containing the data to be written. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) def do_write_object(retry=True): try: controller.put_data(object_id, data.read()) except APDUError as e: logger.debug('Failed writing object', exc_info=e) if e.sw == SW.INCORRECT_PARAMETERS: ctx.fail('Something went wrong, is the object id valid?') raise do_write_object()
python
def write_object(ctx, pin, management_key, object_id, data): """ Write an arbitrary PIV object. Write a PIV object by providing the object id. Yubico writable PIV objects are available in the range 5f0000 - 5fffff. \b OBJECT-ID Id of PIV object in HEX. DATA File containing the data to be written. Use '-' to use stdin. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) def do_write_object(retry=True): try: controller.put_data(object_id, data.read()) except APDUError as e: logger.debug('Failed writing object', exc_info=e) if e.sw == SW.INCORRECT_PARAMETERS: ctx.fail('Something went wrong, is the object id valid?') raise do_write_object()
[ "def", "write_object", "(", "ctx", ",", "pin", ",", "management_key", ",", "object_id", ",", "data", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "_ensure_authenticated", "(", "ctx", ",", "controller", ",", "pin", ",", "management_key", ")", "def", "do_write_object", "(", "retry", "=", "True", ")", ":", "try", ":", "controller", ".", "put_data", "(", "object_id", ",", "data", ".", "read", "(", ")", ")", "except", "APDUError", "as", "e", ":", "logger", ".", "debug", "(", "'Failed writing object'", ",", "exc_info", "=", "e", ")", "if", "e", ".", "sw", "==", "SW", ".", "INCORRECT_PARAMETERS", ":", "ctx", ".", "fail", "(", "'Something went wrong, is the object id valid?'", ")", "raise", "do_write_object", "(", ")" ]
Write an arbitrary PIV object. Write a PIV object by providing the object id. Yubico writable PIV objects are available in the range 5f0000 - 5fffff. \b OBJECT-ID Id of PIV object in HEX. DATA File containing the data to be written. Use '-' to use stdin.
[ "Write", "an", "arbitrary", "PIV", "object", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/piv.py#L869-L894
train
Yubico/yubikey-manager
ykman/cli/fido.py
fido
def fido(ctx): """ Manage FIDO applications. Examples: \b Reset the FIDO (FIDO2 and U2F) applications: $ ykman fido reset \b Change the FIDO2 PIN from 123456 to 654321: $ ykman fido set-pin --pin 123456 --new-pin 654321 """ dev = ctx.obj['dev'] if dev.is_fips: try: ctx.obj['controller'] = FipsU2fController(dev.driver) except Exception as e: logger.debug('Failed to load FipsU2fController', exc_info=e) ctx.fail('Failed to load FIDO Application.') else: try: ctx.obj['controller'] = Fido2Controller(dev.driver) except Exception as e: logger.debug('Failed to load Fido2Controller', exc_info=e) ctx.fail('Failed to load FIDO 2 Application.')
python
def fido(ctx): """ Manage FIDO applications. Examples: \b Reset the FIDO (FIDO2 and U2F) applications: $ ykman fido reset \b Change the FIDO2 PIN from 123456 to 654321: $ ykman fido set-pin --pin 123456 --new-pin 654321 """ dev = ctx.obj['dev'] if dev.is_fips: try: ctx.obj['controller'] = FipsU2fController(dev.driver) except Exception as e: logger.debug('Failed to load FipsU2fController', exc_info=e) ctx.fail('Failed to load FIDO Application.') else: try: ctx.obj['controller'] = Fido2Controller(dev.driver) except Exception as e: logger.debug('Failed to load Fido2Controller', exc_info=e) ctx.fail('Failed to load FIDO 2 Application.')
[ "def", "fido", "(", "ctx", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "if", "dev", ".", "is_fips", ":", "try", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "FipsU2fController", "(", "dev", ".", "driver", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to load FipsU2fController'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to load FIDO Application.'", ")", "else", ":", "try", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "Fido2Controller", "(", "dev", ".", "driver", ")", "except", "Exception", "as", "e", ":", "logger", ".", "debug", "(", "'Failed to load Fido2Controller'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to load FIDO 2 Application.'", ")" ]
Manage FIDO applications. Examples: \b Reset the FIDO (FIDO2 and U2F) applications: $ ykman fido reset \b Change the FIDO2 PIN from 123456 to 654321: $ ykman fido set-pin --pin 123456 --new-pin 654321
[ "Manage", "FIDO", "applications", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L51-L78
train
Yubico/yubikey-manager
ykman/cli/fido.py
info
def info(ctx): """ Display status of FIDO2 application. """ controller = ctx.obj['controller'] if controller.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No')) else: if controller.has_pin: try: click.echo( 'PIN is set, with {} tries left.'.format( controller.get_pin_retries())) except CtapError as e: if e.code == CtapError.ERR.PIN_BLOCKED: click.echo('PIN is blocked.') else: click.echo('PIN is not set.')
python
def info(ctx): """ Display status of FIDO2 application. """ controller = ctx.obj['controller'] if controller.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No')) else: if controller.has_pin: try: click.echo( 'PIN is set, with {} tries left.'.format( controller.get_pin_retries())) except CtapError as e: if e.code == CtapError.ERR.PIN_BLOCKED: click.echo('PIN is blocked.') else: click.echo('PIN is not set.')
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "controller", ".", "is_fips", ":", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "controller", ".", "is_in_fips_mode", "else", "'No'", ")", ")", "else", ":", "if", "controller", ".", "has_pin", ":", "try", ":", "click", ".", "echo", "(", "'PIN is set, with {} tries left.'", ".", "format", "(", "controller", ".", "get_pin_retries", "(", ")", ")", ")", "except", "CtapError", "as", "e", ":", "if", "e", ".", "code", "==", "CtapError", ".", "ERR", ".", "PIN_BLOCKED", ":", "click", ".", "echo", "(", "'PIN is blocked.'", ")", "else", ":", "click", ".", "echo", "(", "'PIN is not set.'", ")" ]
Display status of FIDO2 application.
[ "Display", "status", "of", "FIDO2", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L83-L102
train
Yubico/yubikey-manager
ykman/cli/fido.py
reset
def reset(ctx, force): """ Reset all FIDO applications. This action will wipe all FIDO credentials, including FIDO U2F credentials, on the YubiKey and remove the PIN code. The reset must be triggered immediately after the YubiKey is inserted, and requires a touch on the YubiKey. """ n_keys = len(list(get_descriptors())) if n_keys > 1: ctx.fail('Only one YubiKey can be connected to perform a reset.') if not force: if not click.confirm('WARNING! This will delete all FIDO credentials, ' 'including FIDO U2F credentials, and restore ' 'factory settings. Proceed?', err=True): ctx.abort() def prompt_re_insert_key(): click.echo('Remove and re-insert your YubiKey to perform the reset...') removed = False while True: sleep(0.1) n_keys = len(list(get_descriptors())) if not n_keys: removed = True if removed and n_keys == 1: return def try_reset(controller_type): if not force: prompt_re_insert_key() dev = list(get_descriptors())[0].open_device(TRANSPORT.FIDO) controller = controller_type(dev.driver) controller.reset(touch_callback=prompt_for_touch) else: controller = ctx.obj['controller'] controller.reset(touch_callback=prompt_for_touch) if ctx.obj['dev'].is_fips: if not force: destroy_input = click.prompt( 'WARNING! This is a YubiKey FIPS device. This command will ' 'also overwrite the U2F attestation key; this action cannot be ' 'undone and this YubiKey will no longer be a FIPS compliant ' 'device.\n' 'To proceed, please enter the text "OVERWRITE"', default='', show_default=False, err=True ) if destroy_input != 'OVERWRITE': ctx.fail('Reset aborted by user.') try: try_reset(FipsU2fController) except ApduError as e: if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') except Exception as e: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') else: try: try_reset(Fido2Controller) except CtapError as e: if e.code == CtapError.ERR.ACTION_TIMEOUT: ctx.fail( 'Reset failed. You need to touch your' ' YubiKey to confirm the reset.') elif e.code == CtapError.ERR.NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error(e) ctx.fail('Reset failed.') except Exception as e: logger.error(e) ctx.fail('Reset failed.')
python
def reset(ctx, force): """ Reset all FIDO applications. This action will wipe all FIDO credentials, including FIDO U2F credentials, on the YubiKey and remove the PIN code. The reset must be triggered immediately after the YubiKey is inserted, and requires a touch on the YubiKey. """ n_keys = len(list(get_descriptors())) if n_keys > 1: ctx.fail('Only one YubiKey can be connected to perform a reset.') if not force: if not click.confirm('WARNING! This will delete all FIDO credentials, ' 'including FIDO U2F credentials, and restore ' 'factory settings. Proceed?', err=True): ctx.abort() def prompt_re_insert_key(): click.echo('Remove and re-insert your YubiKey to perform the reset...') removed = False while True: sleep(0.1) n_keys = len(list(get_descriptors())) if not n_keys: removed = True if removed and n_keys == 1: return def try_reset(controller_type): if not force: prompt_re_insert_key() dev = list(get_descriptors())[0].open_device(TRANSPORT.FIDO) controller = controller_type(dev.driver) controller.reset(touch_callback=prompt_for_touch) else: controller = ctx.obj['controller'] controller.reset(touch_callback=prompt_for_touch) if ctx.obj['dev'].is_fips: if not force: destroy_input = click.prompt( 'WARNING! This is a YubiKey FIPS device. This command will ' 'also overwrite the U2F attestation key; this action cannot be ' 'undone and this YubiKey will no longer be a FIPS compliant ' 'device.\n' 'To proceed, please enter the text "OVERWRITE"', default='', show_default=False, err=True ) if destroy_input != 'OVERWRITE': ctx.fail('Reset aborted by user.') try: try_reset(FipsU2fController) except ApduError as e: if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') except Exception as e: logger.error('Reset failed', exc_info=e) ctx.fail('Reset failed.') else: try: try_reset(Fido2Controller) except CtapError as e: if e.code == CtapError.ERR.ACTION_TIMEOUT: ctx.fail( 'Reset failed. You need to touch your' ' YubiKey to confirm the reset.') elif e.code == CtapError.ERR.NOT_ALLOWED: ctx.fail( 'Reset failed. Reset must be triggered within 5 seconds' ' after the YubiKey is inserted.') else: logger.error(e) ctx.fail('Reset failed.') except Exception as e: logger.error(e) ctx.fail('Reset failed.')
[ "def", "reset", "(", "ctx", ",", "force", ")", ":", "n_keys", "=", "len", "(", "list", "(", "get_descriptors", "(", ")", ")", ")", "if", "n_keys", ">", "1", ":", "ctx", ".", "fail", "(", "'Only one YubiKey can be connected to perform a reset.'", ")", "if", "not", "force", ":", "if", "not", "click", ".", "confirm", "(", "'WARNING! This will delete all FIDO credentials, '", "'including FIDO U2F credentials, and restore '", "'factory settings. Proceed?'", ",", "err", "=", "True", ")", ":", "ctx", ".", "abort", "(", ")", "def", "prompt_re_insert_key", "(", ")", ":", "click", ".", "echo", "(", "'Remove and re-insert your YubiKey to perform the reset...'", ")", "removed", "=", "False", "while", "True", ":", "sleep", "(", "0.1", ")", "n_keys", "=", "len", "(", "list", "(", "get_descriptors", "(", ")", ")", ")", "if", "not", "n_keys", ":", "removed", "=", "True", "if", "removed", "and", "n_keys", "==", "1", ":", "return", "def", "try_reset", "(", "controller_type", ")", ":", "if", "not", "force", ":", "prompt_re_insert_key", "(", ")", "dev", "=", "list", "(", "get_descriptors", "(", ")", ")", "[", "0", "]", ".", "open_device", "(", "TRANSPORT", ".", "FIDO", ")", "controller", "=", "controller_type", "(", "dev", ".", "driver", ")", "controller", ".", "reset", "(", "touch_callback", "=", "prompt_for_touch", ")", "else", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "controller", ".", "reset", "(", "touch_callback", "=", "prompt_for_touch", ")", "if", "ctx", ".", "obj", "[", "'dev'", "]", ".", "is_fips", ":", "if", "not", "force", ":", "destroy_input", "=", "click", ".", "prompt", "(", "'WARNING! This is a YubiKey FIPS device. This command will '", "'also overwrite the U2F attestation key; this action cannot be '", "'undone and this YubiKey will no longer be a FIPS compliant '", "'device.\\n'", "'To proceed, please enter the text \"OVERWRITE\"'", ",", "default", "=", "''", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "if", "destroy_input", "!=", "'OVERWRITE'", ":", "ctx", ".", "fail", "(", "'Reset aborted by user.'", ")", "try", ":", "try_reset", "(", "FipsU2fController", ")", "except", "ApduError", "as", "e", ":", "if", "e", ".", "code", "==", "SW", ".", "COMMAND_NOT_ALLOWED", ":", "ctx", ".", "fail", "(", "'Reset failed. Reset must be triggered within 5 seconds'", "' after the YubiKey is inserted.'", ")", "else", ":", "logger", ".", "error", "(", "'Reset failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Reset failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")", "else", ":", "try", ":", "try_reset", "(", "Fido2Controller", ")", "except", "CtapError", "as", "e", ":", "if", "e", ".", "code", "==", "CtapError", ".", "ERR", ".", "ACTION_TIMEOUT", ":", "ctx", ".", "fail", "(", "'Reset failed. You need to touch your'", "' YubiKey to confirm the reset.'", ")", "elif", "e", ".", "code", "==", "CtapError", ".", "ERR", ".", "NOT_ALLOWED", ":", "ctx", ".", "fail", "(", "'Reset failed. Reset must be triggered within 5 seconds'", "' after the YubiKey is inserted.'", ")", "else", ":", "logger", ".", "error", "(", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "e", ")", "ctx", ".", "fail", "(", "'Reset failed.'", ")" ]
Reset all FIDO applications. This action will wipe all FIDO credentials, including FIDO U2F credentials, on the YubiKey and remove the PIN code. The reset must be triggered immediately after the YubiKey is inserted, and requires a touch on the YubiKey.
[ "Reset", "all", "FIDO", "applications", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L210-L302
train
Yubico/yubikey-manager
ykman/cli/fido.py
unlock
def unlock(ctx, pin): """ Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration. """ controller = ctx.obj['controller'] if not controller.is_fips: ctx.fail('This is not a YubiKey FIPS, and therefore' ' does not support a U2F PIN.') if pin is None: pin = _prompt_current_pin('Enter your PIN') _fail_if_not_valid_pin(ctx, pin, True) try: controller.verify_pin(pin) except ApduError as e: if e.code == SW.VERIFY_FAIL_NO_RETRY: ctx.fail('Wrong PIN.') if e.code == SW.AUTH_METHOD_BLOCKED: ctx.fail('PIN is blocked.') if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail('PIN is not set.') logger.error('PIN verification failed', exc_info=e) ctx.fail('PIN verification failed.')
python
def unlock(ctx, pin): """ Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration. """ controller = ctx.obj['controller'] if not controller.is_fips: ctx.fail('This is not a YubiKey FIPS, and therefore' ' does not support a U2F PIN.') if pin is None: pin = _prompt_current_pin('Enter your PIN') _fail_if_not_valid_pin(ctx, pin, True) try: controller.verify_pin(pin) except ApduError as e: if e.code == SW.VERIFY_FAIL_NO_RETRY: ctx.fail('Wrong PIN.') if e.code == SW.AUTH_METHOD_BLOCKED: ctx.fail('PIN is blocked.') if e.code == SW.COMMAND_NOT_ALLOWED: ctx.fail('PIN is not set.') logger.error('PIN verification failed', exc_info=e) ctx.fail('PIN verification failed.')
[ "def", "unlock", "(", "ctx", ",", "pin", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "controller", ".", "is_fips", ":", "ctx", ".", "fail", "(", "'This is not a YubiKey FIPS, and therefore'", "' does not support a U2F PIN.'", ")", "if", "pin", "is", "None", ":", "pin", "=", "_prompt_current_pin", "(", "'Enter your PIN'", ")", "_fail_if_not_valid_pin", "(", "ctx", ",", "pin", ",", "True", ")", "try", ":", "controller", ".", "verify_pin", "(", "pin", ")", "except", "ApduError", "as", "e", ":", "if", "e", ".", "code", "==", "SW", ".", "VERIFY_FAIL_NO_RETRY", ":", "ctx", ".", "fail", "(", "'Wrong PIN.'", ")", "if", "e", ".", "code", "==", "SW", ".", "AUTH_METHOD_BLOCKED", ":", "ctx", ".", "fail", "(", "'PIN is blocked.'", ")", "if", "e", ".", "code", "==", "SW", ".", "COMMAND_NOT_ALLOWED", ":", "ctx", ".", "fail", "(", "'PIN is not set.'", ")", "logger", ".", "error", "(", "'PIN verification failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'PIN verification failed.'", ")" ]
Verify U2F PIN for YubiKey FIPS. Unlock the YubiKey FIPS and allow U2F registration.
[ "Verify", "U2F", "PIN", "for", "YubiKey", "FIPS", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/fido.py#L308-L335
train
Yubico/yubikey-manager
ykman/piv.py
PivController.get_pin_tries
def get_pin_tries(self): """ Returns the number of PIN retries left, 0 PIN authentication blocked. Note that 15 is the highest value that will be returned even if remaining tries is higher. """ # Verify without PIN gives number of tries left. _, sw = self.send_cmd(INS.VERIFY, 0, PIN, check=None) return tries_left(sw, self.version)
python
def get_pin_tries(self): """ Returns the number of PIN retries left, 0 PIN authentication blocked. Note that 15 is the highest value that will be returned even if remaining tries is higher. """ # Verify without PIN gives number of tries left. _, sw = self.send_cmd(INS.VERIFY, 0, PIN, check=None) return tries_left(sw, self.version)
[ "def", "get_pin_tries", "(", "self", ")", ":", "# Verify without PIN gives number of tries left.", "_", ",", "sw", "=", "self", ".", "send_cmd", "(", "INS", ".", "VERIFY", ",", "0", ",", "PIN", ",", "check", "=", "None", ")", "return", "tries_left", "(", "sw", ",", "self", ".", "version", ")" ]
Returns the number of PIN retries left, 0 PIN authentication blocked. Note that 15 is the highest value that will be returned even if remaining tries is higher.
[ "Returns", "the", "number", "of", "PIN", "retries", "left", "0", "PIN", "authentication", "blocked", ".", "Note", "that", "15", "is", "the", "highest", "value", "that", "will", "be", "returned", "even", "if", "remaining", "tries", "is", "higher", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/piv.py#L778-L786
train
Yubico/yubikey-manager
ykman/cli/__main__.py
cli
def cli(ctx, device, log_level, log_file, reader): """ Configure your YubiKey via the command line. Examples: \b List connected YubiKeys, only output serial number: $ ykman list --serials \b Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info """ ctx.obj = YkmanContextObject() if log_level: ykman.logging_setup.setup(log_level, log_file=log_file) if reader and device: ctx.fail('--reader and --device options can\'t be combined.') subcmd = next(c for c in COMMANDS if c.name == ctx.invoked_subcommand) if subcmd == list_keys: if reader: ctx.fail('--reader and list command can\'t be combined.') return transports = getattr(subcmd, 'transports', TRANSPORT.usb_transports()) if transports: def resolve_device(): if device is not None: dev = _run_cmd_for_serial(ctx, subcmd.name, transports, device) else: dev = _run_cmd_for_single(ctx, subcmd.name, transports, reader) ctx.call_on_close(dev.close) return dev ctx.obj.add_resolver('dev', resolve_device)
python
def cli(ctx, device, log_level, log_file, reader): """ Configure your YubiKey via the command line. Examples: \b List connected YubiKeys, only output serial number: $ ykman list --serials \b Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info """ ctx.obj = YkmanContextObject() if log_level: ykman.logging_setup.setup(log_level, log_file=log_file) if reader and device: ctx.fail('--reader and --device options can\'t be combined.') subcmd = next(c for c in COMMANDS if c.name == ctx.invoked_subcommand) if subcmd == list_keys: if reader: ctx.fail('--reader and list command can\'t be combined.') return transports = getattr(subcmd, 'transports', TRANSPORT.usb_transports()) if transports: def resolve_device(): if device is not None: dev = _run_cmd_for_serial(ctx, subcmd.name, transports, device) else: dev = _run_cmd_for_single(ctx, subcmd.name, transports, reader) ctx.call_on_close(dev.close) return dev ctx.obj.add_resolver('dev', resolve_device)
[ "def", "cli", "(", "ctx", ",", "device", ",", "log_level", ",", "log_file", ",", "reader", ")", ":", "ctx", ".", "obj", "=", "YkmanContextObject", "(", ")", "if", "log_level", ":", "ykman", ".", "logging_setup", ".", "setup", "(", "log_level", ",", "log_file", "=", "log_file", ")", "if", "reader", "and", "device", ":", "ctx", ".", "fail", "(", "'--reader and --device options can\\'t be combined.'", ")", "subcmd", "=", "next", "(", "c", "for", "c", "in", "COMMANDS", "if", "c", ".", "name", "==", "ctx", ".", "invoked_subcommand", ")", "if", "subcmd", "==", "list_keys", ":", "if", "reader", ":", "ctx", ".", "fail", "(", "'--reader and list command can\\'t be combined.'", ")", "return", "transports", "=", "getattr", "(", "subcmd", ",", "'transports'", ",", "TRANSPORT", ".", "usb_transports", "(", ")", ")", "if", "transports", ":", "def", "resolve_device", "(", ")", ":", "if", "device", "is", "not", "None", ":", "dev", "=", "_run_cmd_for_serial", "(", "ctx", ",", "subcmd", ".", "name", ",", "transports", ",", "device", ")", "else", ":", "dev", "=", "_run_cmd_for_single", "(", "ctx", ",", "subcmd", ".", "name", ",", "transports", ",", "reader", ")", "ctx", ".", "call_on_close", "(", "dev", ".", "close", ")", "return", "dev", "ctx", ".", "obj", ".", "add_resolver", "(", "'dev'", ",", "resolve_device", ")" ]
Configure your YubiKey via the command line. Examples: \b List connected YubiKeys, only output serial number: $ ykman list --serials \b Show information about YubiKey with serial number 0123456: $ ykman --device 0123456 info
[ "Configure", "your", "YubiKey", "via", "the", "command", "line", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/__main__.py#L154-L191
train
Yubico/yubikey-manager
ykman/cli/__main__.py
list_keys
def list_keys(ctx, serials, readers): """ List connected YubiKeys. """ if readers: for reader in list_readers(): click.echo(reader.name) ctx.exit() all_descriptors = get_descriptors() descriptors = [d for d in all_descriptors if d.key_type != YUBIKEY.SKY] skys = len(all_descriptors) - len(descriptors) handled_serials = set() for dev in list_devices(): handled = False if skys > 0 and dev.key_type == YUBIKEY.SKY: skys -= 1 serial = None handled = True else: serial = dev.serial if serial not in handled_serials: handled_serials.add(serial) matches = [d for d in descriptors if (d.key_type, d.mode) == (dev.driver.key_type, dev.driver.mode)] if len(matches) > 0: d = matches[0] descriptors.remove(d) handled = True if handled: if serials: if serial: click.echo(serial) else: click.echo('{} [{}]{}'.format( dev.device_name, dev.mode, ' Serial: {}'.format(serial) if serial else '') ) dev.close() if not descriptors and not skys: break
python
def list_keys(ctx, serials, readers): """ List connected YubiKeys. """ if readers: for reader in list_readers(): click.echo(reader.name) ctx.exit() all_descriptors = get_descriptors() descriptors = [d for d in all_descriptors if d.key_type != YUBIKEY.SKY] skys = len(all_descriptors) - len(descriptors) handled_serials = set() for dev in list_devices(): handled = False if skys > 0 and dev.key_type == YUBIKEY.SKY: skys -= 1 serial = None handled = True else: serial = dev.serial if serial not in handled_serials: handled_serials.add(serial) matches = [d for d in descriptors if (d.key_type, d.mode) == (dev.driver.key_type, dev.driver.mode)] if len(matches) > 0: d = matches[0] descriptors.remove(d) handled = True if handled: if serials: if serial: click.echo(serial) else: click.echo('{} [{}]{}'.format( dev.device_name, dev.mode, ' Serial: {}'.format(serial) if serial else '') ) dev.close() if not descriptors and not skys: break
[ "def", "list_keys", "(", "ctx", ",", "serials", ",", "readers", ")", ":", "if", "readers", ":", "for", "reader", "in", "list_readers", "(", ")", ":", "click", ".", "echo", "(", "reader", ".", "name", ")", "ctx", ".", "exit", "(", ")", "all_descriptors", "=", "get_descriptors", "(", ")", "descriptors", "=", "[", "d", "for", "d", "in", "all_descriptors", "if", "d", ".", "key_type", "!=", "YUBIKEY", ".", "SKY", "]", "skys", "=", "len", "(", "all_descriptors", ")", "-", "len", "(", "descriptors", ")", "handled_serials", "=", "set", "(", ")", "for", "dev", "in", "list_devices", "(", ")", ":", "handled", "=", "False", "if", "skys", ">", "0", "and", "dev", ".", "key_type", "==", "YUBIKEY", ".", "SKY", ":", "skys", "-=", "1", "serial", "=", "None", "handled", "=", "True", "else", ":", "serial", "=", "dev", ".", "serial", "if", "serial", "not", "in", "handled_serials", ":", "handled_serials", ".", "add", "(", "serial", ")", "matches", "=", "[", "d", "for", "d", "in", "descriptors", "if", "(", "d", ".", "key_type", ",", "d", ".", "mode", ")", "==", "(", "dev", ".", "driver", ".", "key_type", ",", "dev", ".", "driver", ".", "mode", ")", "]", "if", "len", "(", "matches", ")", ">", "0", ":", "d", "=", "matches", "[", "0", "]", "descriptors", ".", "remove", "(", "d", ")", "handled", "=", "True", "if", "handled", ":", "if", "serials", ":", "if", "serial", ":", "click", ".", "echo", "(", "serial", ")", "else", ":", "click", ".", "echo", "(", "'{} [{}]{}'", ".", "format", "(", "dev", ".", "device_name", ",", "dev", ".", "mode", ",", "' Serial: {}'", ".", "format", "(", "serial", ")", "if", "serial", "else", "''", ")", ")", "dev", ".", "close", "(", ")", "if", "not", "descriptors", "and", "not", "skys", ":", "break" ]
List connected YubiKeys.
[ "List", "connected", "YubiKeys", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/__main__.py#L200-L241
train
Yubico/yubikey-manager
ykman/cli/otp.py
otp
def otp(ctx, access_code): """ Manage OTP Application. The YubiKey provides two keyboard-based slots which can each be configured with a credential. Several credential types are supported. A slot configuration may be write-protected with an access code. This prevents the configuration to be overwritten without the access code provided. Mode switching the YubiKey is not possible when a slot is configured with an access code. Examples: \b Swap the configurations between the two slots: $ ykman otp swap \b Program a random challenge-response credential to slot 2: $ ykman otp chalresp --generate 2 \b Program a Yubico OTP credential to slot 2, using the serial as public id: $ ykman otp yubiotp 1 --serial-public-id \b Program a random 38 characters long static password to slot 2: $ ykman otp static --generate 2 --length 38 """ ctx.obj['controller'] = OtpController(ctx.obj['dev'].driver) if access_code is not None: if access_code == '': access_code = click.prompt( 'Enter access code', show_default=False, err=True) try: access_code = parse_access_code_hex(access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) ctx.obj['controller'].access_code = access_code
python
def otp(ctx, access_code): """ Manage OTP Application. The YubiKey provides two keyboard-based slots which can each be configured with a credential. Several credential types are supported. A slot configuration may be write-protected with an access code. This prevents the configuration to be overwritten without the access code provided. Mode switching the YubiKey is not possible when a slot is configured with an access code. Examples: \b Swap the configurations between the two slots: $ ykman otp swap \b Program a random challenge-response credential to slot 2: $ ykman otp chalresp --generate 2 \b Program a Yubico OTP credential to slot 2, using the serial as public id: $ ykman otp yubiotp 1 --serial-public-id \b Program a random 38 characters long static password to slot 2: $ ykman otp static --generate 2 --length 38 """ ctx.obj['controller'] = OtpController(ctx.obj['dev'].driver) if access_code is not None: if access_code == '': access_code = click.prompt( 'Enter access code', show_default=False, err=True) try: access_code = parse_access_code_hex(access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) ctx.obj['controller'].access_code = access_code
[ "def", "otp", "(", "ctx", ",", "access_code", ")", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "OtpController", "(", "ctx", ".", "obj", "[", "'dev'", "]", ".", "driver", ")", "if", "access_code", "is", "not", "None", ":", "if", "access_code", "==", "''", ":", "access_code", "=", "click", ".", "prompt", "(", "'Enter access code'", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "try", ":", "access_code", "=", "parse_access_code_hex", "(", "access_code", ")", "except", "Exception", "as", "e", ":", "ctx", ".", "fail", "(", "'Failed to parse access code: '", "+", "str", "(", "e", ")", ")", "ctx", ".", "obj", "[", "'controller'", "]", ".", "access_code", "=", "access_code" ]
Manage OTP Application. The YubiKey provides two keyboard-based slots which can each be configured with a credential. Several credential types are supported. A slot configuration may be write-protected with an access code. This prevents the configuration to be overwritten without the access code provided. Mode switching the YubiKey is not possible when a slot is configured with an access code. Examples: \b Swap the configurations between the two slots: $ ykman otp swap \b Program a random challenge-response credential to slot 2: $ ykman otp chalresp --generate 2 \b Program a Yubico OTP credential to slot 2, using the serial as public id: $ ykman otp yubiotp 1 --serial-public-id \b Program a random 38 characters long static password to slot 2: $ ykman otp static --generate 2 --length 38
[ "Manage", "OTP", "Application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L98-L140
train
Yubico/yubikey-manager
ykman/cli/otp.py
info
def info(ctx): """ Display status of YubiKey Slots. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] slot1, slot2 = controller.slot_status click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty')) click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty')) if dev.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
python
def info(ctx): """ Display status of YubiKey Slots. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] slot1, slot2 = controller.slot_status click.echo('Slot 1: {}'.format(slot1 and 'programmed' or 'empty')) click.echo('Slot 2: {}'.format(slot2 and 'programmed' or 'empty')) if dev.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
[ "def", "info", "(", "ctx", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "slot1", ",", "slot2", "=", "controller", ".", "slot_status", "click", ".", "echo", "(", "'Slot 1: {}'", ".", "format", "(", "slot1", "and", "'programmed'", "or", "'empty'", ")", ")", "click", ".", "echo", "(", "'Slot 2: {}'", ".", "format", "(", "slot2", "and", "'programmed'", "or", "'empty'", ")", ")", "if", "dev", ".", "is_fips", ":", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "controller", ".", "is_in_fips_mode", "else", "'No'", ")", ")" ]
Display status of YubiKey Slots.
[ "Display", "status", "of", "YubiKey", "Slots", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L145-L158
train
Yubico/yubikey-manager
ykman/cli/otp.py
swap
def swap(ctx): """ Swaps the two slot configurations. """ controller = ctx.obj['controller'] click.echo('Swapping slots...') try: controller.swap_slots() except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def swap(ctx): """ Swaps the two slot configurations. """ controller = ctx.obj['controller'] click.echo('Swapping slots...') try: controller.swap_slots() except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "swap", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "click", ".", "echo", "(", "'Swapping slots...'", ")", "try", ":", "controller", ".", "swap_slots", "(", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Swaps the two slot configurations.
[ "Swaps", "the", "two", "slot", "configurations", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L165-L174
train
Yubico/yubikey-manager
ykman/cli/otp.py
ndef
def ndef(ctx, slot, prefix): """ Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if not dev.config.nfc_supported: ctx.fail('NFC interface not available.') if not controller.slot_status[slot - 1]: ctx.fail('Slot {} is empty.'.format(slot)) try: if prefix: controller.configure_ndef_slot(slot, prefix) else: controller.configure_ndef_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def ndef(ctx, slot, prefix): """ Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if not dev.config.nfc_supported: ctx.fail('NFC interface not available.') if not controller.slot_status[slot - 1]: ctx.fail('Slot {} is empty.'.format(slot)) try: if prefix: controller.configure_ndef_slot(slot, prefix) else: controller.configure_ndef_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "ndef", "(", "ctx", ",", "slot", ",", "prefix", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "dev", ".", "config", ".", "nfc_supported", ":", "ctx", ".", "fail", "(", "'NFC interface not available.'", ")", "if", "not", "controller", ".", "slot_status", "[", "slot", "-", "1", "]", ":", "ctx", ".", "fail", "(", "'Slot {} is empty.'", ".", "format", "(", "slot", ")", ")", "try", ":", "if", "prefix", ":", "controller", ".", "configure_ndef_slot", "(", "slot", ",", "prefix", ")", "else", ":", "controller", ".", "configure_ndef_slot", "(", "slot", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Select slot configuration to use for NDEF. The default prefix will be used if no prefix is specified.
[ "Select", "slot", "configuration", "to", "use", "for", "NDEF", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L182-L202
train
Yubico/yubikey-manager
ykman/cli/otp.py
delete
def delete(ctx, slot, force): """ Deletes the configuration of a slot. """ controller = ctx.obj['controller'] if not force and not controller.slot_status[slot - 1]: ctx.fail('Not possible to delete an empty slot.') force or click.confirm( 'Do you really want to delete' ' the configuration of slot {}?'.format(slot), abort=True, err=True) click.echo('Deleting the configuration of slot {}...'.format(slot)) try: controller.zap_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def delete(ctx, slot, force): """ Deletes the configuration of a slot. """ controller = ctx.obj['controller'] if not force and not controller.slot_status[slot - 1]: ctx.fail('Not possible to delete an empty slot.') force or click.confirm( 'Do you really want to delete' ' the configuration of slot {}?'.format(slot), abort=True, err=True) click.echo('Deleting the configuration of slot {}...'.format(slot)) try: controller.zap_slot(slot) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "delete", "(", "ctx", ",", "slot", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "force", "and", "not", "controller", ".", "slot_status", "[", "slot", "-", "1", "]", ":", "ctx", ".", "fail", "(", "'Not possible to delete an empty slot.'", ")", "force", "or", "click", ".", "confirm", "(", "'Do you really want to delete'", "' the configuration of slot {}?'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "click", ".", "echo", "(", "'Deleting the configuration of slot {}...'", ".", "format", "(", "slot", ")", ")", "try", ":", "controller", ".", "zap_slot", "(", "slot", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Deletes the configuration of a slot.
[ "Deletes", "the", "configuration", "of", "a", "slot", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L209-L223
train
Yubico/yubikey-manager
ykman/cli/otp.py
yubiotp
def yubiotp(ctx, slot, public_id, private_id, key, no_enter, force, serial_public_id, generate_private_id, generate_key): """ Program a Yubico OTP credential. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if public_id and serial_public_id: ctx.fail('Invalid options: --public-id conflicts with ' '--serial-public-id.') if private_id and generate_private_id: ctx.fail('Invalid options: --private-id conflicts with ' '--generate-public-id.') if key and generate_key: ctx.fail('Invalid options: --key conflicts with --generate-key.') if not public_id: if serial_public_id: if dev.serial is None: ctx.fail('Serial number not set, public ID must be provided') public_id = modhex_encode( b'\xff\x00' + struct.pack(b'>I', dev.serial)) click.echo( 'Using YubiKey serial as public ID: {}'.format(public_id)) elif force: ctx.fail( 'Public ID not given. Please remove the --force flag, or ' 'add the --serial-public-id flag or --public-id option.') else: public_id = click.prompt('Enter public ID', err=True) try: public_id = modhex_decode(public_id) except KeyError: ctx.fail('Invalid public ID, must be modhex.') if not private_id: if generate_private_id: private_id = os.urandom(6) click.echo( 'Using a randomly generated private ID: {}'.format( b2a_hex(private_id).decode('ascii'))) elif force: ctx.fail( 'Private ID not given. Please remove the --force flag, or ' 'add the --generate-private-id flag or --private-id option.') else: private_id = click.prompt('Enter private ID', err=True) private_id = a2b_hex(private_id) if not key: if generate_key: key = os.urandom(16) click.echo( 'Using a randomly generated secret key: {}'.format( b2a_hex(key).decode('ascii'))) elif force: ctx.fail('Secret key not given. Please remove the --force flag, or ' 'add the --generate-key flag or --key option.') else: key = click.prompt('Enter secret key', err=True) key = a2b_hex(key) force or click.confirm('Program an OTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_otp(slot, key, public_id, private_id, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def yubiotp(ctx, slot, public_id, private_id, key, no_enter, force, serial_public_id, generate_private_id, generate_key): """ Program a Yubico OTP credential. """ dev = ctx.obj['dev'] controller = ctx.obj['controller'] if public_id and serial_public_id: ctx.fail('Invalid options: --public-id conflicts with ' '--serial-public-id.') if private_id and generate_private_id: ctx.fail('Invalid options: --private-id conflicts with ' '--generate-public-id.') if key and generate_key: ctx.fail('Invalid options: --key conflicts with --generate-key.') if not public_id: if serial_public_id: if dev.serial is None: ctx.fail('Serial number not set, public ID must be provided') public_id = modhex_encode( b'\xff\x00' + struct.pack(b'>I', dev.serial)) click.echo( 'Using YubiKey serial as public ID: {}'.format(public_id)) elif force: ctx.fail( 'Public ID not given. Please remove the --force flag, or ' 'add the --serial-public-id flag or --public-id option.') else: public_id = click.prompt('Enter public ID', err=True) try: public_id = modhex_decode(public_id) except KeyError: ctx.fail('Invalid public ID, must be modhex.') if not private_id: if generate_private_id: private_id = os.urandom(6) click.echo( 'Using a randomly generated private ID: {}'.format( b2a_hex(private_id).decode('ascii'))) elif force: ctx.fail( 'Private ID not given. Please remove the --force flag, or ' 'add the --generate-private-id flag or --private-id option.') else: private_id = click.prompt('Enter private ID', err=True) private_id = a2b_hex(private_id) if not key: if generate_key: key = os.urandom(16) click.echo( 'Using a randomly generated secret key: {}'.format( b2a_hex(key).decode('ascii'))) elif force: ctx.fail('Secret key not given. Please remove the --force flag, or ' 'add the --generate-key flag or --key option.') else: key = click.prompt('Enter secret key', err=True) key = a2b_hex(key) force or click.confirm('Program an OTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_otp(slot, key, public_id, private_id, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "yubiotp", "(", "ctx", ",", "slot", ",", "public_id", ",", "private_id", ",", "key", ",", "no_enter", ",", "force", ",", "serial_public_id", ",", "generate_private_id", ",", "generate_key", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "public_id", "and", "serial_public_id", ":", "ctx", ".", "fail", "(", "'Invalid options: --public-id conflicts with '", "'--serial-public-id.'", ")", "if", "private_id", "and", "generate_private_id", ":", "ctx", ".", "fail", "(", "'Invalid options: --private-id conflicts with '", "'--generate-public-id.'", ")", "if", "key", "and", "generate_key", ":", "ctx", ".", "fail", "(", "'Invalid options: --key conflicts with --generate-key.'", ")", "if", "not", "public_id", ":", "if", "serial_public_id", ":", "if", "dev", ".", "serial", "is", "None", ":", "ctx", ".", "fail", "(", "'Serial number not set, public ID must be provided'", ")", "public_id", "=", "modhex_encode", "(", "b'\\xff\\x00'", "+", "struct", ".", "pack", "(", "b'>I'", ",", "dev", ".", "serial", ")", ")", "click", ".", "echo", "(", "'Using YubiKey serial as public ID: {}'", ".", "format", "(", "public_id", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'Public ID not given. Please remove the --force flag, or '", "'add the --serial-public-id flag or --public-id option.'", ")", "else", ":", "public_id", "=", "click", ".", "prompt", "(", "'Enter public ID'", ",", "err", "=", "True", ")", "try", ":", "public_id", "=", "modhex_decode", "(", "public_id", ")", "except", "KeyError", ":", "ctx", ".", "fail", "(", "'Invalid public ID, must be modhex.'", ")", "if", "not", "private_id", ":", "if", "generate_private_id", ":", "private_id", "=", "os", ".", "urandom", "(", "6", ")", "click", ".", "echo", "(", "'Using a randomly generated private ID: {}'", ".", "format", "(", "b2a_hex", "(", "private_id", ")", ".", "decode", "(", "'ascii'", ")", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'Private ID not given. Please remove the --force flag, or '", "'add the --generate-private-id flag or --private-id option.'", ")", "else", ":", "private_id", "=", "click", ".", "prompt", "(", "'Enter private ID'", ",", "err", "=", "True", ")", "private_id", "=", "a2b_hex", "(", "private_id", ")", "if", "not", "key", ":", "if", "generate_key", ":", "key", "=", "os", ".", "urandom", "(", "16", ")", "click", ".", "echo", "(", "'Using a randomly generated secret key: {}'", ".", "format", "(", "b2a_hex", "(", "key", ")", ".", "decode", "(", "'ascii'", ")", ")", ")", "elif", "force", ":", "ctx", ".", "fail", "(", "'Secret key not given. Please remove the --force flag, or '", "'add the --generate-key flag or --key option.'", ")", "else", ":", "key", "=", "click", ".", "prompt", "(", "'Enter secret key'", ",", "err", "=", "True", ")", "key", "=", "a2b_hex", "(", "key", ")", "force", "or", "click", ".", "confirm", "(", "'Program an OTP credential in slot {}?'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "try", ":", "controller", ".", "program_otp", "(", "slot", ",", "key", ",", "public_id", ",", "private_id", ",", "not", "no_enter", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Program a Yubico OTP credential.
[ "Program", "a", "Yubico", "OTP", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L247-L321
train
Yubico/yubikey-manager
ykman/cli/otp.py
static
def static( ctx, slot, password, generate, length, keyboard_layout, no_enter, force): """ Configure a static password. To avoid problems with different keyboard layouts, the following characters are allowed by default: cbdefghijklnrtuv Use the --keyboard-layout option to allow more characters based on preferred keyboard layout. """ controller = ctx.obj['controller'] keyboard_layout = KEYBOARD_LAYOUT[keyboard_layout] if password and len(password) > 38: ctx.fail('Password too long (maximum length is 38 characters).') if generate and not length: ctx.fail('Provide a length for the generated password.') if not password and not generate: password = click.prompt('Enter a static password', err=True) elif not password and generate: password = generate_static_pw(length, keyboard_layout) if not force: _confirm_slot_overwrite(controller, slot) try: controller.program_static( slot, password, not no_enter, keyboard_layout=keyboard_layout) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def static( ctx, slot, password, generate, length, keyboard_layout, no_enter, force): """ Configure a static password. To avoid problems with different keyboard layouts, the following characters are allowed by default: cbdefghijklnrtuv Use the --keyboard-layout option to allow more characters based on preferred keyboard layout. """ controller = ctx.obj['controller'] keyboard_layout = KEYBOARD_LAYOUT[keyboard_layout] if password and len(password) > 38: ctx.fail('Password too long (maximum length is 38 characters).') if generate and not length: ctx.fail('Provide a length for the generated password.') if not password and not generate: password = click.prompt('Enter a static password', err=True) elif not password and generate: password = generate_static_pw(length, keyboard_layout) if not force: _confirm_slot_overwrite(controller, slot) try: controller.program_static( slot, password, not no_enter, keyboard_layout=keyboard_layout) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "static", "(", "ctx", ",", "slot", ",", "password", ",", "generate", ",", "length", ",", "keyboard_layout", ",", "no_enter", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "keyboard_layout", "=", "KEYBOARD_LAYOUT", "[", "keyboard_layout", "]", "if", "password", "and", "len", "(", "password", ")", ">", "38", ":", "ctx", ".", "fail", "(", "'Password too long (maximum length is 38 characters).'", ")", "if", "generate", "and", "not", "length", ":", "ctx", ".", "fail", "(", "'Provide a length for the generated password.'", ")", "if", "not", "password", "and", "not", "generate", ":", "password", "=", "click", ".", "prompt", "(", "'Enter a static password'", ",", "err", "=", "True", ")", "elif", "not", "password", "and", "generate", ":", "password", "=", "generate_static_pw", "(", "length", ",", "keyboard_layout", ")", "if", "not", "force", ":", "_confirm_slot_overwrite", "(", "controller", ",", "slot", ")", "try", ":", "controller", ".", "program_static", "(", "slot", ",", "password", ",", "not", "no_enter", ",", "keyboard_layout", "=", "keyboard_layout", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Configure a static password. To avoid problems with different keyboard layouts, the following characters are allowed by default: cbdefghijklnrtuv Use the --keyboard-layout option to allow more characters based on preferred keyboard layout.
[ "Configure", "a", "static", "password", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L341-L373
train
Yubico/yubikey-manager
ykman/cli/otp.py
chalresp
def chalresp(ctx, slot, key, totp, touch, force, generate): """ Program a challenge-response credential. If KEY is not given, an interactive prompt will ask for it. """ controller = ctx.obj['controller'] if key: if generate: ctx.fail('Invalid options: --generate conflicts with KEY argument.') elif totp: key = parse_b32_key(key) else: key = parse_key(key) else: if force and not generate: ctx.fail('No secret key given. Please remove the --force flag, ' 'set the KEY argument or set the --generate flag.') elif totp: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) else: if generate: key = os.urandom(20) click.echo('Using a randomly generated key: {}'.format( b2a_hex(key).decode('ascii'))) else: key = click.prompt('Enter a secret key', err=True) key = parse_key(key) cred_type = 'TOTP' if totp else 'challenge-response' force or click.confirm('Program a {} credential in slot {}?' .format(cred_type, slot), abort=True, err=True) try: controller.program_chalresp(slot, key, touch) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def chalresp(ctx, slot, key, totp, touch, force, generate): """ Program a challenge-response credential. If KEY is not given, an interactive prompt will ask for it. """ controller = ctx.obj['controller'] if key: if generate: ctx.fail('Invalid options: --generate conflicts with KEY argument.') elif totp: key = parse_b32_key(key) else: key = parse_key(key) else: if force and not generate: ctx.fail('No secret key given. Please remove the --force flag, ' 'set the KEY argument or set the --generate flag.') elif totp: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) else: if generate: key = os.urandom(20) click.echo('Using a randomly generated key: {}'.format( b2a_hex(key).decode('ascii'))) else: key = click.prompt('Enter a secret key', err=True) key = parse_key(key) cred_type = 'TOTP' if totp else 'challenge-response' force or click.confirm('Program a {} credential in slot {}?' .format(cred_type, slot), abort=True, err=True) try: controller.program_chalresp(slot, key, touch) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "chalresp", "(", "ctx", ",", "slot", ",", "key", ",", "totp", ",", "touch", ",", "force", ",", "generate", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "key", ":", "if", "generate", ":", "ctx", ".", "fail", "(", "'Invalid options: --generate conflicts with KEY argument.'", ")", "elif", "totp", ":", "key", "=", "parse_b32_key", "(", "key", ")", "else", ":", "key", "=", "parse_key", "(", "key", ")", "else", ":", "if", "force", "and", "not", "generate", ":", "ctx", ".", "fail", "(", "'No secret key given. Please remove the --force flag, '", "'set the KEY argument or set the --generate flag.'", ")", "elif", "totp", ":", "while", "True", ":", "key", "=", "click", ".", "prompt", "(", "'Enter a secret key (base32)'", ",", "err", "=", "True", ")", "try", ":", "key", "=", "parse_b32_key", "(", "key", ")", "break", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "else", ":", "if", "generate", ":", "key", "=", "os", ".", "urandom", "(", "20", ")", "click", ".", "echo", "(", "'Using a randomly generated key: {}'", ".", "format", "(", "b2a_hex", "(", "key", ")", ".", "decode", "(", "'ascii'", ")", ")", ")", "else", ":", "key", "=", "click", ".", "prompt", "(", "'Enter a secret key'", ",", "err", "=", "True", ")", "key", "=", "parse_key", "(", "key", ")", "cred_type", "=", "'TOTP'", "if", "totp", "else", "'challenge-response'", "force", "or", "click", ".", "confirm", "(", "'Program a {} credential in slot {}?'", ".", "format", "(", "cred_type", ",", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "try", ":", "controller", ".", "program_chalresp", "(", "slot", ",", "key", ",", "touch", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Program a challenge-response credential. If KEY is not given, an interactive prompt will ask for it.
[ "Program", "a", "challenge", "-", "response", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L390-L432
train
Yubico/yubikey-manager
ykman/cli/otp.py
calculate
def calculate(ctx, slot, challenge, totp, digits): """ Perform a challenge-response operation. Send a challenge (in hex) to a YubiKey slot with a challenge-response credential, and read the response. Supports output as a OATH-TOTP code. """ controller = ctx.obj['controller'] if not challenge and not totp: ctx.fail('No challenge provided.') # Check that slot is not empty slot1, slot2 = controller.slot_status if (slot == 1 and not slot1) or (slot == 2 and not slot2): ctx.fail('Cannot perform challenge-response on an empty slot.') # Timestamp challenge should be int if challenge and totp: try: challenge = int(challenge) except Exception as e: logger.error('Error', exc_info=e) ctx.fail('Timestamp challenge for TOTP must be an integer.') try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=False) except YkpersError as e: # Touch is set if e.errno == 11: prompt_for_touch() try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=True) except YkpersError as e: # Touch timed out if e.errno == 4: ctx.fail('The YubiKey timed out.') else: ctx.fail(e) else: ctx.fail('Failed to calculate challenge.') click.echo(res)
python
def calculate(ctx, slot, challenge, totp, digits): """ Perform a challenge-response operation. Send a challenge (in hex) to a YubiKey slot with a challenge-response credential, and read the response. Supports output as a OATH-TOTP code. """ controller = ctx.obj['controller'] if not challenge and not totp: ctx.fail('No challenge provided.') # Check that slot is not empty slot1, slot2 = controller.slot_status if (slot == 1 and not slot1) or (slot == 2 and not slot2): ctx.fail('Cannot perform challenge-response on an empty slot.') # Timestamp challenge should be int if challenge and totp: try: challenge = int(challenge) except Exception as e: logger.error('Error', exc_info=e) ctx.fail('Timestamp challenge for TOTP must be an integer.') try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=False) except YkpersError as e: # Touch is set if e.errno == 11: prompt_for_touch() try: res = controller.calculate( slot, challenge, totp=totp, digits=int(digits), wait_for_touch=True) except YkpersError as e: # Touch timed out if e.errno == 4: ctx.fail('The YubiKey timed out.') else: ctx.fail(e) else: ctx.fail('Failed to calculate challenge.') click.echo(res)
[ "def", "calculate", "(", "ctx", ",", "slot", ",", "challenge", ",", "totp", ",", "digits", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "challenge", "and", "not", "totp", ":", "ctx", ".", "fail", "(", "'No challenge provided.'", ")", "# Check that slot is not empty", "slot1", ",", "slot2", "=", "controller", ".", "slot_status", "if", "(", "slot", "==", "1", "and", "not", "slot1", ")", "or", "(", "slot", "==", "2", "and", "not", "slot2", ")", ":", "ctx", ".", "fail", "(", "'Cannot perform challenge-response on an empty slot.'", ")", "# Timestamp challenge should be int", "if", "challenge", "and", "totp", ":", "try", ":", "challenge", "=", "int", "(", "challenge", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Error'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Timestamp challenge for TOTP must be an integer.'", ")", "try", ":", "res", "=", "controller", ".", "calculate", "(", "slot", ",", "challenge", ",", "totp", "=", "totp", ",", "digits", "=", "int", "(", "digits", ")", ",", "wait_for_touch", "=", "False", ")", "except", "YkpersError", "as", "e", ":", "# Touch is set", "if", "e", ".", "errno", "==", "11", ":", "prompt_for_touch", "(", ")", "try", ":", "res", "=", "controller", ".", "calculate", "(", "slot", ",", "challenge", ",", "totp", "=", "totp", ",", "digits", "=", "int", "(", "digits", ")", ",", "wait_for_touch", "=", "True", ")", "except", "YkpersError", "as", "e", ":", "# Touch timed out", "if", "e", ".", "errno", "==", "4", ":", "ctx", ".", "fail", "(", "'The YubiKey timed out.'", ")", "else", ":", "ctx", ".", "fail", "(", "e", ")", "else", ":", "ctx", ".", "fail", "(", "'Failed to calculate challenge.'", ")", "click", ".", "echo", "(", "res", ")" ]
Perform a challenge-response operation. Send a challenge (in hex) to a YubiKey slot with a challenge-response credential, and read the response. Supports output as a OATH-TOTP code.
[ "Perform", "a", "challenge", "-", "response", "operation", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L445-L488
train
Yubico/yubikey-manager
ykman/cli/otp.py
hotp
def hotp(ctx, slot, key, digits, counter, no_enter, force): """ Program an HMAC-SHA1 OATH-HOTP credential. """ controller = ctx.obj['controller'] if not key: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) force or click.confirm( 'Program a HOTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_hotp( slot, key, counter, int(digits) == 8, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
python
def hotp(ctx, slot, key, digits, counter, no_enter, force): """ Program an HMAC-SHA1 OATH-HOTP credential. """ controller = ctx.obj['controller'] if not key: while True: key = click.prompt('Enter a secret key (base32)', err=True) try: key = parse_b32_key(key) break except Exception as e: click.echo(e) force or click.confirm( 'Program a HOTP credential in slot {}?'.format(slot), abort=True, err=True) try: controller.program_hotp( slot, key, counter, int(digits) == 8, not no_enter) except YkpersError as e: _failed_to_write_msg(ctx, e)
[ "def", "hotp", "(", "ctx", ",", "slot", ",", "key", ",", "digits", ",", "counter", ",", "no_enter", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "not", "key", ":", "while", "True", ":", "key", "=", "click", ".", "prompt", "(", "'Enter a secret key (base32)'", ",", "err", "=", "True", ")", "try", ":", "key", "=", "parse_b32_key", "(", "key", ")", "break", "except", "Exception", "as", "e", ":", "click", ".", "echo", "(", "e", ")", "force", "or", "click", ".", "confirm", "(", "'Program a HOTP credential in slot {}?'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "try", ":", "controller", ".", "program_hotp", "(", "slot", ",", "key", ",", "counter", ",", "int", "(", "digits", ")", "==", "8", ",", "not", "no_enter", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")" ]
Program an HMAC-SHA1 OATH-HOTP credential.
[ "Program", "an", "HMAC", "-", "SHA1", "OATH", "-", "HOTP", "credential", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L502-L524
train
Yubico/yubikey-manager
ykman/cli/otp.py
settings
def settings(ctx, slot, new_access_code, delete_access_code, enter, pacing, force): """ Update the settings for a slot. Change the settings for a slot without changing the stored secret. All settings not specified will be written with default values. """ controller = ctx.obj['controller'] if (new_access_code is not None) and delete_access_code: ctx.fail('--new-access-code conflicts with --delete-access-code.') if not controller.slot_status[slot - 1]: ctx.fail('Not possible to update settings on an empty slot.') if new_access_code is not None: if new_access_code == '': new_access_code = click.prompt( 'Enter new access code', show_default=False, err=True) try: new_access_code = parse_access_code_hex(new_access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) force or click.confirm( 'Update the settings for slot {}? ' 'All existing settings will be overwritten.'.format(slot), abort=True, err=True) click.echo('Updating settings for slot {}...'.format(slot)) if pacing is not None: pacing = int(pacing) try: controller.update_settings(slot, enter=enter, pacing=pacing) except YkpersError as e: _failed_to_write_msg(ctx, e) if new_access_code: try: controller.set_access_code(slot, new_access_code) except Exception as e: logger.error('Failed to set access code', exc_info=e) ctx.fail('Failed to set access code: ' + str(e)) if delete_access_code: try: controller.delete_access_code(slot) except Exception as e: logger.error('Failed to delete access code', exc_info=e) ctx.fail('Failed to delete access code: ' + str(e))
python
def settings(ctx, slot, new_access_code, delete_access_code, enter, pacing, force): """ Update the settings for a slot. Change the settings for a slot without changing the stored secret. All settings not specified will be written with default values. """ controller = ctx.obj['controller'] if (new_access_code is not None) and delete_access_code: ctx.fail('--new-access-code conflicts with --delete-access-code.') if not controller.slot_status[slot - 1]: ctx.fail('Not possible to update settings on an empty slot.') if new_access_code is not None: if new_access_code == '': new_access_code = click.prompt( 'Enter new access code', show_default=False, err=True) try: new_access_code = parse_access_code_hex(new_access_code) except Exception as e: ctx.fail('Failed to parse access code: ' + str(e)) force or click.confirm( 'Update the settings for slot {}? ' 'All existing settings will be overwritten.'.format(slot), abort=True, err=True) click.echo('Updating settings for slot {}...'.format(slot)) if pacing is not None: pacing = int(pacing) try: controller.update_settings(slot, enter=enter, pacing=pacing) except YkpersError as e: _failed_to_write_msg(ctx, e) if new_access_code: try: controller.set_access_code(slot, new_access_code) except Exception as e: logger.error('Failed to set access code', exc_info=e) ctx.fail('Failed to set access code: ' + str(e)) if delete_access_code: try: controller.delete_access_code(slot) except Exception as e: logger.error('Failed to delete access code', exc_info=e) ctx.fail('Failed to delete access code: ' + str(e))
[ "def", "settings", "(", "ctx", ",", "slot", ",", "new_access_code", ",", "delete_access_code", ",", "enter", ",", "pacing", ",", "force", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "if", "(", "new_access_code", "is", "not", "None", ")", "and", "delete_access_code", ":", "ctx", ".", "fail", "(", "'--new-access-code conflicts with --delete-access-code.'", ")", "if", "not", "controller", ".", "slot_status", "[", "slot", "-", "1", "]", ":", "ctx", ".", "fail", "(", "'Not possible to update settings on an empty slot.'", ")", "if", "new_access_code", "is", "not", "None", ":", "if", "new_access_code", "==", "''", ":", "new_access_code", "=", "click", ".", "prompt", "(", "'Enter new access code'", ",", "show_default", "=", "False", ",", "err", "=", "True", ")", "try", ":", "new_access_code", "=", "parse_access_code_hex", "(", "new_access_code", ")", "except", "Exception", "as", "e", ":", "ctx", ".", "fail", "(", "'Failed to parse access code: '", "+", "str", "(", "e", ")", ")", "force", "or", "click", ".", "confirm", "(", "'Update the settings for slot {}? '", "'All existing settings will be overwritten.'", ".", "format", "(", "slot", ")", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "click", ".", "echo", "(", "'Updating settings for slot {}...'", ".", "format", "(", "slot", ")", ")", "if", "pacing", "is", "not", "None", ":", "pacing", "=", "int", "(", "pacing", ")", "try", ":", "controller", ".", "update_settings", "(", "slot", ",", "enter", "=", "enter", ",", "pacing", "=", "pacing", ")", "except", "YkpersError", "as", "e", ":", "_failed_to_write_msg", "(", "ctx", ",", "e", ")", "if", "new_access_code", ":", "try", ":", "controller", ".", "set_access_code", "(", "slot", ",", "new_access_code", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to set access code'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to set access code: '", "+", "str", "(", "e", ")", ")", "if", "delete_access_code", ":", "try", ":", "controller", ".", "delete_access_code", "(", "slot", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to delete access code'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to delete access code: '", "+", "str", "(", "e", ")", ")" ]
Update the settings for a slot. Change the settings for a slot without changing the stored secret. All settings not specified will be written with default values.
[ "Update", "the", "settings", "for", "a", "slot", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/otp.py#L545-L597
train
Yubico/yubikey-manager
ykman/util.py
parse_private_key
def parse_private_key(data, password): """ Identifies, decrypts and returns a cryptography private key object. """ # PEM if is_pem(data): if b'ENCRYPTED' in data: if password is None: raise TypeError('No password provided for encrypted key.') try: return serialization.load_pem_private_key( data, password, backend=default_backend()) except ValueError: # Cryptography raises ValueError if decryption fails. raise except Exception: pass # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_privatekey( crypto.FILETYPE_PEM, p12.get_privatekey()) return serialization.load_pem_private_key( data, password=None, backend=default_backend()) except crypto.Error as e: raise ValueError(e) # DER try: return serialization.load_der_private_key( data, password, backend=default_backend()) except Exception: pass # All parsing failed raise ValueError('Could not parse private key.')
python
def parse_private_key(data, password): """ Identifies, decrypts and returns a cryptography private key object. """ # PEM if is_pem(data): if b'ENCRYPTED' in data: if password is None: raise TypeError('No password provided for encrypted key.') try: return serialization.load_pem_private_key( data, password, backend=default_backend()) except ValueError: # Cryptography raises ValueError if decryption fails. raise except Exception: pass # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_privatekey( crypto.FILETYPE_PEM, p12.get_privatekey()) return serialization.load_pem_private_key( data, password=None, backend=default_backend()) except crypto.Error as e: raise ValueError(e) # DER try: return serialization.load_der_private_key( data, password, backend=default_backend()) except Exception: pass # All parsing failed raise ValueError('Could not parse private key.')
[ "def", "parse_private_key", "(", "data", ",", "password", ")", ":", "# PEM", "if", "is_pem", "(", "data", ")", ":", "if", "b'ENCRYPTED'", "in", "data", ":", "if", "password", "is", "None", ":", "raise", "TypeError", "(", "'No password provided for encrypted key.'", ")", "try", ":", "return", "serialization", ".", "load_pem_private_key", "(", "data", ",", "password", ",", "backend", "=", "default_backend", "(", ")", ")", "except", "ValueError", ":", "# Cryptography raises ValueError if decryption fails.", "raise", "except", "Exception", ":", "pass", "# PKCS12", "if", "is_pkcs12", "(", "data", ")", ":", "try", ":", "p12", "=", "crypto", ".", "load_pkcs12", "(", "data", ",", "password", ")", "data", "=", "crypto", ".", "dump_privatekey", "(", "crypto", ".", "FILETYPE_PEM", ",", "p12", ".", "get_privatekey", "(", ")", ")", "return", "serialization", ".", "load_pem_private_key", "(", "data", ",", "password", "=", "None", ",", "backend", "=", "default_backend", "(", ")", ")", "except", "crypto", ".", "Error", "as", "e", ":", "raise", "ValueError", "(", "e", ")", "# DER", "try", ":", "return", "serialization", ".", "load_der_private_key", "(", "data", ",", "password", ",", "backend", "=", "default_backend", "(", ")", ")", "except", "Exception", ":", "pass", "# All parsing failed", "raise", "ValueError", "(", "'Could not parse private key.'", ")" ]
Identifies, decrypts and returns a cryptography private key object.
[ "Identifies", "decrypts", "and", "returns", "a", "cryptography", "private", "key", "object", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/util.py#L419-L456
train
Yubico/yubikey-manager
ykman/util.py
parse_certificates
def parse_certificates(data, password): """ Identifies, decrypts and returns list of cryptography x509 certificates. """ # PEM if is_pem(data): certs = [] for cert in data.split(PEM_IDENTIFIER): try: certs.append( x509.load_pem_x509_certificate( PEM_IDENTIFIER + cert, default_backend())) except Exception: pass # Could be valid PEM but not certificates. if len(certs) > 0: return certs # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_certificate( crypto.FILETYPE_PEM, p12.get_certificate()) return [x509.load_pem_x509_certificate(data, default_backend())] except crypto.Error as e: raise ValueError(e) # DER try: return [x509.load_der_x509_certificate(data, default_backend())] except Exception: pass raise ValueError('Could not parse certificate.')
python
def parse_certificates(data, password): """ Identifies, decrypts and returns list of cryptography x509 certificates. """ # PEM if is_pem(data): certs = [] for cert in data.split(PEM_IDENTIFIER): try: certs.append( x509.load_pem_x509_certificate( PEM_IDENTIFIER + cert, default_backend())) except Exception: pass # Could be valid PEM but not certificates. if len(certs) > 0: return certs # PKCS12 if is_pkcs12(data): try: p12 = crypto.load_pkcs12(data, password) data = crypto.dump_certificate( crypto.FILETYPE_PEM, p12.get_certificate()) return [x509.load_pem_x509_certificate(data, default_backend())] except crypto.Error as e: raise ValueError(e) # DER try: return [x509.load_der_x509_certificate(data, default_backend())] except Exception: pass raise ValueError('Could not parse certificate.')
[ "def", "parse_certificates", "(", "data", ",", "password", ")", ":", "# PEM", "if", "is_pem", "(", "data", ")", ":", "certs", "=", "[", "]", "for", "cert", "in", "data", ".", "split", "(", "PEM_IDENTIFIER", ")", ":", "try", ":", "certs", ".", "append", "(", "x509", ".", "load_pem_x509_certificate", "(", "PEM_IDENTIFIER", "+", "cert", ",", "default_backend", "(", ")", ")", ")", "except", "Exception", ":", "pass", "# Could be valid PEM but not certificates.", "if", "len", "(", "certs", ")", ">", "0", ":", "return", "certs", "# PKCS12", "if", "is_pkcs12", "(", "data", ")", ":", "try", ":", "p12", "=", "crypto", ".", "load_pkcs12", "(", "data", ",", "password", ")", "data", "=", "crypto", ".", "dump_certificate", "(", "crypto", ".", "FILETYPE_PEM", ",", "p12", ".", "get_certificate", "(", ")", ")", "return", "[", "x509", ".", "load_pem_x509_certificate", "(", "data", ",", "default_backend", "(", ")", ")", "]", "except", "crypto", ".", "Error", "as", "e", ":", "raise", "ValueError", "(", "e", ")", "# DER", "try", ":", "return", "[", "x509", ".", "load_der_x509_certificate", "(", "data", ",", "default_backend", "(", ")", ")", "]", "except", "Exception", ":", "pass", "raise", "ValueError", "(", "'Could not parse certificate.'", ")" ]
Identifies, decrypts and returns list of cryptography x509 certificates.
[ "Identifies", "decrypts", "and", "returns", "list", "of", "cryptography", "x509", "certificates", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/util.py#L459-L494
train
Yubico/yubikey-manager
ykman/util.py
get_leaf_certificates
def get_leaf_certificates(certs): """ Extracts the leaf certificates from a list of certificates. Leaf certificates are ones whose subject does not appear as issuer among the others. """ issuers = [cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) for cert in certs] leafs = [cert for cert in certs if (cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) not in issuers)] return leafs
python
def get_leaf_certificates(certs): """ Extracts the leaf certificates from a list of certificates. Leaf certificates are ones whose subject does not appear as issuer among the others. """ issuers = [cert.issuer.get_attributes_for_oid(x509.NameOID.COMMON_NAME) for cert in certs] leafs = [cert for cert in certs if (cert.subject.get_attributes_for_oid(x509.NameOID.COMMON_NAME) not in issuers)] return leafs
[ "def", "get_leaf_certificates", "(", "certs", ")", ":", "issuers", "=", "[", "cert", ".", "issuer", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "for", "cert", "in", "certs", "]", "leafs", "=", "[", "cert", "for", "cert", "in", "certs", "if", "(", "cert", ".", "subject", ".", "get_attributes_for_oid", "(", "x509", ".", "NameOID", ".", "COMMON_NAME", ")", "not", "in", "issuers", ")", "]", "return", "leafs" ]
Extracts the leaf certificates from a list of certificates. Leaf certificates are ones whose subject does not appear as issuer among the others.
[ "Extracts", "the", "leaf", "certificates", "from", "a", "list", "of", "certificates", ".", "Leaf", "certificates", "are", "ones", "whose", "subject", "does", "not", "appear", "as", "issuer", "among", "the", "others", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/util.py#L497-L508
train
Yubico/yubikey-manager
ykman/cli/config.py
set_lock_code
def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force): """ Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value. """ dev = ctx.obj['dev'] def prompt_new_lock_code(): return prompt_lock_code(prompt='Enter your new lock code') def prompt_current_lock_code(): return prompt_lock_code(prompt='Enter your current lock code') def change_lock_code(lock_code, new_lock_code): lock_code = _parse_lock_code(ctx, lock_code) new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Changing the lock code failed', exc_info=e) ctx.fail('Failed to change the lock code. Wrong current code?') def set_lock_code(new_lock_code): new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True) except Exception as e: logger.error('Setting the lock code failed', exc_info=e) ctx.fail('Failed to set the lock code.') if generate and new_lock_code: ctx.fail('Invalid options: --new-lock-code conflicts with --generate.') if clear: new_lock_code = CLEAR_LOCK_CODE if generate: new_lock_code = b2a_hex(os.urandom(16)).decode('utf-8') click.echo( 'Using a randomly generated lock code: {}'.format(new_lock_code)) force or click.confirm( 'Lock configuration with this lock code?', abort=True, err=True) if dev.config.configuration_locked: if lock_code: if new_lock_code: change_lock_code(lock_code, new_lock_code) else: new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if new_lock_code: lock_code = prompt_current_lock_code() change_lock_code(lock_code, new_lock_code) else: lock_code = prompt_current_lock_code() new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if lock_code: ctx.fail( 'There is no current lock code set. ' 'Use --new-lock-code to set one.') else: if new_lock_code: set_lock_code(new_lock_code) else: new_lock_code = prompt_new_lock_code() set_lock_code(new_lock_code)
python
def set_lock_code(ctx, lock_code, new_lock_code, clear, generate, force): """ Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value. """ dev = ctx.obj['dev'] def prompt_new_lock_code(): return prompt_lock_code(prompt='Enter your new lock code') def prompt_current_lock_code(): return prompt_lock_code(prompt='Enter your current lock code') def change_lock_code(lock_code, new_lock_code): lock_code = _parse_lock_code(ctx, lock_code) new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Changing the lock code failed', exc_info=e) ctx.fail('Failed to change the lock code. Wrong current code?') def set_lock_code(new_lock_code): new_lock_code = _parse_lock_code(ctx, new_lock_code) try: dev.write_config( device_config( config_lock=new_lock_code), reboot=True) except Exception as e: logger.error('Setting the lock code failed', exc_info=e) ctx.fail('Failed to set the lock code.') if generate and new_lock_code: ctx.fail('Invalid options: --new-lock-code conflicts with --generate.') if clear: new_lock_code = CLEAR_LOCK_CODE if generate: new_lock_code = b2a_hex(os.urandom(16)).decode('utf-8') click.echo( 'Using a randomly generated lock code: {}'.format(new_lock_code)) force or click.confirm( 'Lock configuration with this lock code?', abort=True, err=True) if dev.config.configuration_locked: if lock_code: if new_lock_code: change_lock_code(lock_code, new_lock_code) else: new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if new_lock_code: lock_code = prompt_current_lock_code() change_lock_code(lock_code, new_lock_code) else: lock_code = prompt_current_lock_code() new_lock_code = prompt_new_lock_code() change_lock_code(lock_code, new_lock_code) else: if lock_code: ctx.fail( 'There is no current lock code set. ' 'Use --new-lock-code to set one.') else: if new_lock_code: set_lock_code(new_lock_code) else: new_lock_code = prompt_new_lock_code() set_lock_code(new_lock_code)
[ "def", "set_lock_code", "(", "ctx", ",", "lock_code", ",", "new_lock_code", ",", "clear", ",", "generate", ",", "force", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "def", "prompt_new_lock_code", "(", ")", ":", "return", "prompt_lock_code", "(", "prompt", "=", "'Enter your new lock code'", ")", "def", "prompt_current_lock_code", "(", ")", ":", "return", "prompt_lock_code", "(", "prompt", "=", "'Enter your current lock code'", ")", "def", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", ":", "lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "lock_code", ")", "new_lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "new_lock_code", ")", "try", ":", "dev", ".", "write_config", "(", "device_config", "(", "config_lock", "=", "new_lock_code", ")", ",", "reboot", "=", "True", ",", "lock_key", "=", "lock_code", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Changing the lock code failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to change the lock code. Wrong current code?'", ")", "def", "set_lock_code", "(", "new_lock_code", ")", ":", "new_lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "new_lock_code", ")", "try", ":", "dev", ".", "write_config", "(", "device_config", "(", "config_lock", "=", "new_lock_code", ")", ",", "reboot", "=", "True", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Setting the lock code failed'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to set the lock code.'", ")", "if", "generate", "and", "new_lock_code", ":", "ctx", ".", "fail", "(", "'Invalid options: --new-lock-code conflicts with --generate.'", ")", "if", "clear", ":", "new_lock_code", "=", "CLEAR_LOCK_CODE", "if", "generate", ":", "new_lock_code", "=", "b2a_hex", "(", "os", ".", "urandom", "(", "16", ")", ")", ".", "decode", "(", "'utf-8'", ")", "click", ".", "echo", "(", "'Using a randomly generated lock code: {}'", ".", "format", "(", "new_lock_code", ")", ")", "force", "or", "click", ".", "confirm", "(", "'Lock configuration with this lock code?'", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "if", "dev", ".", "config", ".", "configuration_locked", ":", "if", "lock_code", ":", "if", "new_lock_code", ":", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "new_lock_code", "=", "prompt_new_lock_code", "(", ")", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "if", "new_lock_code", ":", "lock_code", "=", "prompt_current_lock_code", "(", ")", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "lock_code", "=", "prompt_current_lock_code", "(", ")", "new_lock_code", "=", "prompt_new_lock_code", "(", ")", "change_lock_code", "(", "lock_code", ",", "new_lock_code", ")", "else", ":", "if", "lock_code", ":", "ctx", ".", "fail", "(", "'There is no current lock code set. '", "'Use --new-lock-code to set one.'", ")", "else", ":", "if", "new_lock_code", ":", "set_lock_code", "(", "new_lock_code", ")", "else", ":", "new_lock_code", "=", "prompt_new_lock_code", "(", ")", "set_lock_code", "(", "new_lock_code", ")" ]
Set or change the configuration lock code. A lock code may be used to protect the application configuration. The lock code must be a 32 characters (16 bytes) hex value.
[ "Set", "or", "change", "the", "configuration", "lock", "code", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/config.py#L101-L179
train
Yubico/yubikey-manager
ykman/cli/config.py
nfc
def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force): """ Enable or disable applications over NFC. """ if not (list or enable_all or enable or disable_all or disable): ctx.fail('No configuration options chosen.') if enable_all: enable = APPLICATION.__members__.keys() if disable_all: disable = APPLICATION.__members__.keys() _ensure_not_invalid_options(ctx, enable, disable) dev = ctx.obj['dev'] nfc_supported = dev.config.nfc_supported nfc_enabled = dev.config.nfc_enabled if not nfc_supported: ctx.fail('NFC interface not available.') if list: _list_apps(ctx, nfc_enabled) for app in enable: if APPLICATION[app] & nfc_supported: nfc_enabled |= APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) for app in disable: if APPLICATION[app] & nfc_supported: nfc_enabled &= ~APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) f_confirm = '{}{}Configure NFC interface?'.format( 'Enable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in enable])) if enable else '', 'Disable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in disable])) if disable else '') is_locked = dev.config.configuration_locked if force and is_locked and not lock_code: ctx.fail('Configuration is locked - please supply the --lock-code ' 'option.') if lock_code and not is_locked: ctx.fail('Configuration is not locked - please remove the ' '--lock-code option.') force or click.confirm(f_confirm, abort=True, err=True) if is_locked and not lock_code: lock_code = prompt_lock_code() if lock_code: lock_code = _parse_lock_code(ctx, lock_code) try: dev.write_config( device_config( nfc_enabled=nfc_enabled), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Failed to write config', exc_info=e) ctx.fail('Failed to configure NFC applications.')
python
def nfc(ctx, enable, disable, enable_all, disable_all, list, lock_code, force): """ Enable or disable applications over NFC. """ if not (list or enable_all or enable or disable_all or disable): ctx.fail('No configuration options chosen.') if enable_all: enable = APPLICATION.__members__.keys() if disable_all: disable = APPLICATION.__members__.keys() _ensure_not_invalid_options(ctx, enable, disable) dev = ctx.obj['dev'] nfc_supported = dev.config.nfc_supported nfc_enabled = dev.config.nfc_enabled if not nfc_supported: ctx.fail('NFC interface not available.') if list: _list_apps(ctx, nfc_enabled) for app in enable: if APPLICATION[app] & nfc_supported: nfc_enabled |= APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) for app in disable: if APPLICATION[app] & nfc_supported: nfc_enabled &= ~APPLICATION[app] else: ctx.fail('{} not supported over NFC.'.format(app)) f_confirm = '{}{}Configure NFC interface?'.format( 'Enable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in enable])) if enable else '', 'Disable {}.\n'.format( ', '.join( [str(APPLICATION[app]) for app in disable])) if disable else '') is_locked = dev.config.configuration_locked if force and is_locked and not lock_code: ctx.fail('Configuration is locked - please supply the --lock-code ' 'option.') if lock_code and not is_locked: ctx.fail('Configuration is not locked - please remove the ' '--lock-code option.') force or click.confirm(f_confirm, abort=True, err=True) if is_locked and not lock_code: lock_code = prompt_lock_code() if lock_code: lock_code = _parse_lock_code(ctx, lock_code) try: dev.write_config( device_config( nfc_enabled=nfc_enabled), reboot=True, lock_key=lock_code) except Exception as e: logger.error('Failed to write config', exc_info=e) ctx.fail('Failed to configure NFC applications.')
[ "def", "nfc", "(", "ctx", ",", "enable", ",", "disable", ",", "enable_all", ",", "disable_all", ",", "list", ",", "lock_code", ",", "force", ")", ":", "if", "not", "(", "list", "or", "enable_all", "or", "enable", "or", "disable_all", "or", "disable", ")", ":", "ctx", ".", "fail", "(", "'No configuration options chosen.'", ")", "if", "enable_all", ":", "enable", "=", "APPLICATION", ".", "__members__", ".", "keys", "(", ")", "if", "disable_all", ":", "disable", "=", "APPLICATION", ".", "__members__", ".", "keys", "(", ")", "_ensure_not_invalid_options", "(", "ctx", ",", "enable", ",", "disable", ")", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "nfc_supported", "=", "dev", ".", "config", ".", "nfc_supported", "nfc_enabled", "=", "dev", ".", "config", ".", "nfc_enabled", "if", "not", "nfc_supported", ":", "ctx", ".", "fail", "(", "'NFC interface not available.'", ")", "if", "list", ":", "_list_apps", "(", "ctx", ",", "nfc_enabled", ")", "for", "app", "in", "enable", ":", "if", "APPLICATION", "[", "app", "]", "&", "nfc_supported", ":", "nfc_enabled", "|=", "APPLICATION", "[", "app", "]", "else", ":", "ctx", ".", "fail", "(", "'{} not supported over NFC.'", ".", "format", "(", "app", ")", ")", "for", "app", "in", "disable", ":", "if", "APPLICATION", "[", "app", "]", "&", "nfc_supported", ":", "nfc_enabled", "&=", "~", "APPLICATION", "[", "app", "]", "else", ":", "ctx", ".", "fail", "(", "'{} not supported over NFC.'", ".", "format", "(", "app", ")", ")", "f_confirm", "=", "'{}{}Configure NFC interface?'", ".", "format", "(", "'Enable {}.\\n'", ".", "format", "(", "', '", ".", "join", "(", "[", "str", "(", "APPLICATION", "[", "app", "]", ")", "for", "app", "in", "enable", "]", ")", ")", "if", "enable", "else", "''", ",", "'Disable {}.\\n'", ".", "format", "(", "', '", ".", "join", "(", "[", "str", "(", "APPLICATION", "[", "app", "]", ")", "for", "app", "in", "disable", "]", ")", ")", "if", "disable", "else", "''", ")", "is_locked", "=", "dev", ".", "config", ".", "configuration_locked", "if", "force", "and", "is_locked", "and", "not", "lock_code", ":", "ctx", ".", "fail", "(", "'Configuration is locked - please supply the --lock-code '", "'option.'", ")", "if", "lock_code", "and", "not", "is_locked", ":", "ctx", ".", "fail", "(", "'Configuration is not locked - please remove the '", "'--lock-code option.'", ")", "force", "or", "click", ".", "confirm", "(", "f_confirm", ",", "abort", "=", "True", ",", "err", "=", "True", ")", "if", "is_locked", "and", "not", "lock_code", ":", "lock_code", "=", "prompt_lock_code", "(", ")", "if", "lock_code", ":", "lock_code", "=", "_parse_lock_code", "(", "ctx", ",", "lock_code", ")", "try", ":", "dev", ".", "write_config", "(", "device_config", "(", "nfc_enabled", "=", "nfc_enabled", ")", ",", "reboot", "=", "True", ",", "lock_key", "=", "lock_code", ")", "except", "Exception", "as", "e", ":", "logger", ".", "error", "(", "'Failed to write config'", ",", "exc_info", "=", "e", ")", "ctx", ".", "fail", "(", "'Failed to configure NFC applications.'", ")" ]
Enable or disable applications over NFC.
[ "Enable", "or", "disable", "applications", "over", "NFC", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/config.py#L332-L401
train
Yubico/yubikey-manager
ykman/cli/info.py
info
def info(ctx, check_fips): """ Show general information. Displays information about the attached YubiKey such as serial number, firmware version, applications, etc. """ dev = ctx.obj['dev'] if dev.is_fips and check_fips: fips_status = get_overall_fips_status(dev.serial, dev.config) click.echo('Device type: {}'.format(dev.device_name)) click.echo('Serial number: {}'.format( dev.serial or 'Not set or unreadable')) if dev.version: f_version = '.'.join(str(x) for x in dev.version) click.echo('Firmware version: {}'.format(f_version)) else: click.echo('Firmware version: Uncertain, re-run with only one ' 'YubiKey connected') config = dev.config if config.form_factor: click.echo('Form factor: {!s}'.format(config.form_factor)) click.echo('Enabled USB interfaces: {}'.format(dev.mode)) if config.nfc_supported: f_nfc = 'enabled' if config.nfc_enabled else 'disabled' click.echo('NFC interface is {}.'.format(f_nfc)) if config.configuration_locked: click.echo('Configured applications are protected by a lock code.') click.echo() print_app_status_table(config) if dev.is_fips and check_fips: click.echo() click.echo('FIPS Approved Mode: {}'.format( 'Yes' if all(fips_status.values()) else 'No')) status_keys = list(fips_status.keys()) status_keys.sort() for status_key in status_keys: click.echo(' {}: {}'.format( status_key, 'Yes' if fips_status[status_key] else 'No'))
python
def info(ctx, check_fips): """ Show general information. Displays information about the attached YubiKey such as serial number, firmware version, applications, etc. """ dev = ctx.obj['dev'] if dev.is_fips and check_fips: fips_status = get_overall_fips_status(dev.serial, dev.config) click.echo('Device type: {}'.format(dev.device_name)) click.echo('Serial number: {}'.format( dev.serial or 'Not set or unreadable')) if dev.version: f_version = '.'.join(str(x) for x in dev.version) click.echo('Firmware version: {}'.format(f_version)) else: click.echo('Firmware version: Uncertain, re-run with only one ' 'YubiKey connected') config = dev.config if config.form_factor: click.echo('Form factor: {!s}'.format(config.form_factor)) click.echo('Enabled USB interfaces: {}'.format(dev.mode)) if config.nfc_supported: f_nfc = 'enabled' if config.nfc_enabled else 'disabled' click.echo('NFC interface is {}.'.format(f_nfc)) if config.configuration_locked: click.echo('Configured applications are protected by a lock code.') click.echo() print_app_status_table(config) if dev.is_fips and check_fips: click.echo() click.echo('FIPS Approved Mode: {}'.format( 'Yes' if all(fips_status.values()) else 'No')) status_keys = list(fips_status.keys()) status_keys.sort() for status_key in status_keys: click.echo(' {}: {}'.format( status_key, 'Yes' if fips_status[status_key] else 'No'))
[ "def", "info", "(", "ctx", ",", "check_fips", ")", ":", "dev", "=", "ctx", ".", "obj", "[", "'dev'", "]", "if", "dev", ".", "is_fips", "and", "check_fips", ":", "fips_status", "=", "get_overall_fips_status", "(", "dev", ".", "serial", ",", "dev", ".", "config", ")", "click", ".", "echo", "(", "'Device type: {}'", ".", "format", "(", "dev", ".", "device_name", ")", ")", "click", ".", "echo", "(", "'Serial number: {}'", ".", "format", "(", "dev", ".", "serial", "or", "'Not set or unreadable'", ")", ")", "if", "dev", ".", "version", ":", "f_version", "=", "'.'", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "dev", ".", "version", ")", "click", ".", "echo", "(", "'Firmware version: {}'", ".", "format", "(", "f_version", ")", ")", "else", ":", "click", ".", "echo", "(", "'Firmware version: Uncertain, re-run with only one '", "'YubiKey connected'", ")", "config", "=", "dev", ".", "config", "if", "config", ".", "form_factor", ":", "click", ".", "echo", "(", "'Form factor: {!s}'", ".", "format", "(", "config", ".", "form_factor", ")", ")", "click", ".", "echo", "(", "'Enabled USB interfaces: {}'", ".", "format", "(", "dev", ".", "mode", ")", ")", "if", "config", ".", "nfc_supported", ":", "f_nfc", "=", "'enabled'", "if", "config", ".", "nfc_enabled", "else", "'disabled'", "click", ".", "echo", "(", "'NFC interface is {}.'", ".", "format", "(", "f_nfc", ")", ")", "if", "config", ".", "configuration_locked", ":", "click", ".", "echo", "(", "'Configured applications are protected by a lock code.'", ")", "click", ".", "echo", "(", ")", "print_app_status_table", "(", "config", ")", "if", "dev", ".", "is_fips", "and", "check_fips", ":", "click", ".", "echo", "(", ")", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "all", "(", "fips_status", ".", "values", "(", ")", ")", "else", "'No'", ")", ")", "status_keys", "=", "list", "(", "fips_status", ".", "keys", "(", ")", ")", "status_keys", ".", "sort", "(", ")", "for", "status_key", "in", "status_keys", ":", "click", ".", "echo", "(", "' {}: {}'", ".", "format", "(", "status_key", ",", "'Yes'", "if", "fips_status", "[", "status_key", "]", "else", "'No'", ")", ")" ]
Show general information. Displays information about the attached YubiKey such as serial number, firmware version, applications, etc.
[ "Show", "general", "information", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/info.py#L130-L175
train
Yubico/yubikey-manager
ykman/cli/oath.py
oath
def oath(ctx, password): """ Manage OATH Application. Examples: \b Generate codes for credentials starting with 'yubi': $ ykman oath code yubi \b Add a touch credential with the secret key f5up4ub3dw and the name yubico: $ ykman oath add yubico f5up4ub3dw --touch \b Set a password for the OATH application: $ ykman oath set-password """ try: controller = OathController(ctx.obj['dev'].driver) ctx.obj['controller'] = controller ctx.obj['settings'] = Settings('oath') except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The OATH application can't be found on this YubiKey.") raise if password: ctx.obj['key'] = controller.derive_key(password)
python
def oath(ctx, password): """ Manage OATH Application. Examples: \b Generate codes for credentials starting with 'yubi': $ ykman oath code yubi \b Add a touch credential with the secret key f5up4ub3dw and the name yubico: $ ykman oath add yubico f5up4ub3dw --touch \b Set a password for the OATH application: $ ykman oath set-password """ try: controller = OathController(ctx.obj['dev'].driver) ctx.obj['controller'] = controller ctx.obj['settings'] = Settings('oath') except APDUError as e: if e.sw == SW.NOT_FOUND: ctx.fail("The OATH application can't be found on this YubiKey.") raise if password: ctx.obj['key'] = controller.derive_key(password)
[ "def", "oath", "(", "ctx", ",", "password", ")", ":", "try", ":", "controller", "=", "OathController", "(", "ctx", ".", "obj", "[", "'dev'", "]", ".", "driver", ")", "ctx", ".", "obj", "[", "'controller'", "]", "=", "controller", "ctx", ".", "obj", "[", "'settings'", "]", "=", "Settings", "(", "'oath'", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "==", "SW", ".", "NOT_FOUND", ":", "ctx", ".", "fail", "(", "\"The OATH application can't be found on this YubiKey.\"", ")", "raise", "if", "password", ":", "ctx", ".", "obj", "[", "'key'", "]", "=", "controller", ".", "derive_key", "(", "password", ")" ]
Manage OATH Application. Examples: \b Generate codes for credentials starting with 'yubi': $ ykman oath code yubi \b Add a touch credential with the secret key f5up4ub3dw and the name yubico: $ ykman oath add yubico f5up4ub3dw --touch \b Set a password for the OATH application: $ ykman oath set-password
[ "Manage", "OATH", "Application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L87-L115
train
Yubico/yubikey-manager
ykman/cli/oath.py
info
def info(ctx): """ Display status of OATH application. """ controller = ctx.obj['controller'] version = controller.version click.echo( 'OATH version: {}.{}.{}'.format(version[0], version[1], version[2])) click.echo('Password protection ' + ('enabled' if controller.locked else 'disabled')) keys = ctx.obj['settings'].get('keys', {}) if controller.locked and controller.id in keys: click.echo('The password for this YubiKey is remembered by ykman.') if ctx.obj['dev'].is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
python
def info(ctx): """ Display status of OATH application. """ controller = ctx.obj['controller'] version = controller.version click.echo( 'OATH version: {}.{}.{}'.format(version[0], version[1], version[2])) click.echo('Password protection ' + ('enabled' if controller.locked else 'disabled')) keys = ctx.obj['settings'].get('keys', {}) if controller.locked and controller.id in keys: click.echo('The password for this YubiKey is remembered by ykman.') if ctx.obj['dev'].is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No'))
[ "def", "info", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "version", "=", "controller", ".", "version", "click", ".", "echo", "(", "'OATH version: {}.{}.{}'", ".", "format", "(", "version", "[", "0", "]", ",", "version", "[", "1", "]", ",", "version", "[", "2", "]", ")", ")", "click", ".", "echo", "(", "'Password protection '", "+", "(", "'enabled'", "if", "controller", ".", "locked", "else", "'disabled'", ")", ")", "keys", "=", "ctx", ".", "obj", "[", "'settings'", "]", ".", "get", "(", "'keys'", ",", "{", "}", ")", "if", "controller", ".", "locked", "and", "controller", ".", "id", "in", "keys", ":", "click", ".", "echo", "(", "'The password for this YubiKey is remembered by ykman.'", ")", "if", "ctx", ".", "obj", "[", "'dev'", "]", ".", "is_fips", ":", "click", ".", "echo", "(", "'FIPS Approved Mode: {}'", ".", "format", "(", "'Yes'", "if", "controller", ".", "is_in_fips_mode", "else", "'No'", ")", ")" ]
Display status of OATH application.
[ "Display", "status", "of", "OATH", "application", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L120-L137
train
Yubico/yubikey-manager
ykman/cli/oath.py
reset
def reset(ctx): """ Reset all OATH data. This action will wipe all credentials and reset factory settings for the OATH application on the YubiKey. """ controller = ctx.obj['controller'] click.echo('Resetting OATH data...') old_id = controller.id controller.reset() settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) if old_id in keys: del keys[old_id] settings.write() click.echo( 'Success! All OATH credentials have been cleared from your YubiKey.')
python
def reset(ctx): """ Reset all OATH data. This action will wipe all credentials and reset factory settings for the OATH application on the YubiKey. """ controller = ctx.obj['controller'] click.echo('Resetting OATH data...') old_id = controller.id controller.reset() settings = ctx.obj['settings'] keys = settings.setdefault('keys', {}) if old_id in keys: del keys[old_id] settings.write() click.echo( 'Success! All OATH credentials have been cleared from your YubiKey.')
[ "def", "reset", "(", "ctx", ")", ":", "controller", "=", "ctx", ".", "obj", "[", "'controller'", "]", "click", ".", "echo", "(", "'Resetting OATH data...'", ")", "old_id", "=", "controller", ".", "id", "controller", ".", "reset", "(", ")", "settings", "=", "ctx", ".", "obj", "[", "'settings'", "]", "keys", "=", "settings", ".", "setdefault", "(", "'keys'", ",", "{", "}", ")", "if", "old_id", "in", "keys", ":", "del", "keys", "[", "old_id", "]", "settings", ".", "write", "(", ")", "click", ".", "echo", "(", "'Success! All OATH credentials have been cleared from your YubiKey.'", ")" ]
Reset all OATH data. This action will wipe all credentials and reset factory settings for the OATH application on the YubiKey.
[ "Reset", "all", "OATH", "data", "." ]
3ac27bc59ae76a59db9d09a530494add2edbbabf
https://github.com/Yubico/yubikey-manager/blob/3ac27bc59ae76a59db9d09a530494add2edbbabf/ykman/cli/oath.py#L145-L165
train