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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
romanz/trezor-agent | libagent/util.py | ExpiringCache.get | def get(self):
"""Returns existing value, or None if deadline has expired."""
if self.timer() > self.deadline:
self.value = None
return self.value | python | def get(self):
"""Returns existing value, or None if deadline has expired."""
if self.timer() > self.deadline:
self.value = None
return self.value | [
"def",
"get",
"(",
"self",
")",
":",
"if",
"self",
".",
"timer",
"(",
")",
">",
"self",
".",
"deadline",
":",
"self",
".",
"value",
"=",
"None",
"return",
"self",
".",
"value"
] | Returns existing value, or None if deadline has expired. | [
"Returns",
"existing",
"value",
"or",
"None",
"if",
"deadline",
"has",
"expired",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L271-L275 | train |
romanz/trezor-agent | libagent/util.py | ExpiringCache.set | def set(self, value):
"""Set new value and reset the deadline for expiration."""
self.deadline = self.timer() + self.duration
self.value = value | python | def set(self, value):
"""Set new value and reset the deadline for expiration."""
self.deadline = self.timer() + self.duration
self.value = value | [
"def",
"set",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"deadline",
"=",
"self",
".",
"timer",
"(",
")",
"+",
"self",
".",
"duration",
"self",
".",
"value",
"=",
"value"
] | Set new value and reset the deadline for expiration. | [
"Set",
"new",
"value",
"and",
"reset",
"the",
"deadline",
"for",
"expiration",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/util.py#L277-L280 | train |
romanz/trezor-agent | libagent/gpg/agent.py | sig_encode | def sig_encode(r, s):
"""Serialize ECDSA signature data into GPG S-expression."""
r = util.assuan_serialize(util.num2bytes(r, 32))
s = util.assuan_serialize(util.num2bytes(s, 32))
return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))' | python | def sig_encode(r, s):
"""Serialize ECDSA signature data into GPG S-expression."""
r = util.assuan_serialize(util.num2bytes(r, 32))
s = util.assuan_serialize(util.num2bytes(s, 32))
return b'(7:sig-val(5:ecdsa(1:r32:' + r + b')(1:s32:' + s + b')))' | [
"def",
"sig_encode",
"(",
"r",
",",
"s",
")",
":",
"r",
"=",
"util",
".",
"assuan_serialize",
"(",
"util",
".",
"num2bytes",
"(",
"r",
",",
"32",
")",
")",
"s",
"=",
"util",
".",
"assuan_serialize",
"(",
"util",
".",
"num2bytes",
"(",
"s",
",",
"... | Serialize ECDSA signature data into GPG S-expression. | [
"Serialize",
"ECDSA",
"signature",
"data",
"into",
"GPG",
"S",
"-",
"expression",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L24-L28 | train |
romanz/trezor-agent | libagent/gpg/agent.py | parse_ecdh | def parse_ecdh(line):
"""Parse ECDH request and return remote public key."""
prefix, line = line.split(b' ', 1)
assert prefix == b'D'
exp, leftover = keyring.parse(keyring.unescape(line))
log.debug('ECDH s-exp: %r', exp)
assert not leftover
label, exp = exp
assert label == b'enc-val'
... | python | def parse_ecdh(line):
"""Parse ECDH request and return remote public key."""
prefix, line = line.split(b' ', 1)
assert prefix == b'D'
exp, leftover = keyring.parse(keyring.unescape(line))
log.debug('ECDH s-exp: %r', exp)
assert not leftover
label, exp = exp
assert label == b'enc-val'
... | [
"def",
"parse_ecdh",
"(",
"line",
")",
":",
"prefix",
",",
"line",
"=",
"line",
".",
"split",
"(",
"b' '",
",",
"1",
")",
"assert",
"prefix",
"==",
"b'D'",
"exp",
",",
"leftover",
"=",
"keyring",
".",
"parse",
"(",
"keyring",
".",
"unescape",
"(",
... | Parse ECDH request and return remote public key. | [
"Parse",
"ECDH",
"request",
"and",
"return",
"remote",
"public",
"key",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L37-L49 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.handle_getinfo | def handle_getinfo(self, conn, args):
"""Handle some of the GETINFO messages."""
result = None
if args[0] == b'version':
result = self.version
elif args[0] == b's2k_count':
# Use highest number of S2K iterations.
# https://www.gnupg.org/documentation/m... | python | def handle_getinfo(self, conn, args):
"""Handle some of the GETINFO messages."""
result = None
if args[0] == b'version':
result = self.version
elif args[0] == b's2k_count':
# Use highest number of S2K iterations.
# https://www.gnupg.org/documentation/m... | [
"def",
"handle_getinfo",
"(",
"self",
",",
"conn",
",",
"args",
")",
":",
"result",
"=",
"None",
"if",
"args",
"[",
"0",
"]",
"==",
"b'version'",
":",
"result",
"=",
"self",
".",
"version",
"elif",
"args",
"[",
"0",
"]",
"==",
"b's2k_count'",
":",
... | Handle some of the GETINFO messages. | [
"Handle",
"some",
"of",
"the",
"GETINFO",
"messages",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L129-L143 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.handle_scd | def handle_scd(self, conn, args):
"""No support for smart-card device protocol."""
reply = {
(b'GETINFO', b'version'): self.version,
}.get(args)
if reply is None:
raise AgentError(b'ERR 100696144 No such device <SCD>')
keyring.sendline(conn, b'D ' + reply) | python | def handle_scd(self, conn, args):
"""No support for smart-card device protocol."""
reply = {
(b'GETINFO', b'version'): self.version,
}.get(args)
if reply is None:
raise AgentError(b'ERR 100696144 No such device <SCD>')
keyring.sendline(conn, b'D ' + reply) | [
"def",
"handle_scd",
"(",
"self",
",",
"conn",
",",
"args",
")",
":",
"reply",
"=",
"{",
"(",
"b'GETINFO'",
",",
"b'version'",
")",
":",
"self",
".",
"version",
",",
"}",
".",
"get",
"(",
"args",
")",
"if",
"reply",
"is",
"None",
":",
"raise",
"A... | No support for smart-card device protocol. | [
"No",
"support",
"for",
"smart",
"-",
"card",
"device",
"protocol",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L145-L152 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.get_identity | def get_identity(self, keygrip):
"""
Returns device.interface.Identity that matches specified keygrip.
In case of missing keygrip, KeyError will be raised.
"""
keygrip_bytes = binascii.unhexlify(keygrip)
pubkey_dict, user_ids = decode.load_by_keygrip(
pubkey_... | python | def get_identity(self, keygrip):
"""
Returns device.interface.Identity that matches specified keygrip.
In case of missing keygrip, KeyError will be raised.
"""
keygrip_bytes = binascii.unhexlify(keygrip)
pubkey_dict, user_ids = decode.load_by_keygrip(
pubkey_... | [
"def",
"get_identity",
"(",
"self",
",",
"keygrip",
")",
":",
"keygrip_bytes",
"=",
"binascii",
".",
"unhexlify",
"(",
"keygrip",
")",
"pubkey_dict",
",",
"user_ids",
"=",
"decode",
".",
"load_by_keygrip",
"(",
"pubkey_bytes",
"=",
"self",
".",
"pubkey_bytes",... | Returns device.interface.Identity that matches specified keygrip.
In case of missing keygrip, KeyError will be raised. | [
"Returns",
"device",
".",
"interface",
".",
"Identity",
"that",
"matches",
"specified",
"keygrip",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L155-L176 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.pksign | def pksign(self, conn):
"""Sign a message digest using a private EC key."""
log.debug('signing %r digest (algo #%s)', self.digest, self.algo)
identity = self.get_identity(keygrip=self.keygrip)
r, s = self.client.sign(identity=identity,
digest=binascii.unhe... | python | def pksign(self, conn):
"""Sign a message digest using a private EC key."""
log.debug('signing %r digest (algo #%s)', self.digest, self.algo)
identity = self.get_identity(keygrip=self.keygrip)
r, s = self.client.sign(identity=identity,
digest=binascii.unhe... | [
"def",
"pksign",
"(",
"self",
",",
"conn",
")",
":",
"log",
".",
"debug",
"(",
"'signing %r digest (algo #%s)'",
",",
"self",
".",
"digest",
",",
"self",
".",
"algo",
")",
"identity",
"=",
"self",
".",
"get_identity",
"(",
"keygrip",
"=",
"self",
".",
... | Sign a message digest using a private EC key. | [
"Sign",
"a",
"message",
"digest",
"using",
"a",
"private",
"EC",
"key",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L178-L186 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.pkdecrypt | def pkdecrypt(self, conn):
"""Handle decryption using ECDH."""
for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:
keyring.sendline(conn, msg)
line = keyring.recvline(conn)
assert keyring.recvline(conn) == b'END'
remote_pubkey = parse_ecdh(line)
id... | python | def pkdecrypt(self, conn):
"""Handle decryption using ECDH."""
for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:
keyring.sendline(conn, msg)
line = keyring.recvline(conn)
assert keyring.recvline(conn) == b'END'
remote_pubkey = parse_ecdh(line)
id... | [
"def",
"pkdecrypt",
"(",
"self",
",",
"conn",
")",
":",
"for",
"msg",
"in",
"[",
"b'S INQUIRE_MAXLEN 4096'",
",",
"b'INQUIRE CIPHERTEXT'",
"]",
":",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"msg",
")",
"line",
"=",
"keyring",
".",
"recvline",
"(",
"... | Handle decryption using ECDH. | [
"Handle",
"decryption",
"using",
"ECDH",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L188-L199 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.have_key | def have_key(self, *keygrips):
"""Check if any keygrip corresponds to a TREZOR-based key."""
for keygrip in keygrips:
try:
self.get_identity(keygrip=keygrip)
break
except KeyError as e:
log.warning('HAVEKEY(%s) failed: %s', keygrip,... | python | def have_key(self, *keygrips):
"""Check if any keygrip corresponds to a TREZOR-based key."""
for keygrip in keygrips:
try:
self.get_identity(keygrip=keygrip)
break
except KeyError as e:
log.warning('HAVEKEY(%s) failed: %s', keygrip,... | [
"def",
"have_key",
"(",
"self",
",",
"*",
"keygrips",
")",
":",
"for",
"keygrip",
"in",
"keygrips",
":",
"try",
":",
"self",
".",
"get_identity",
"(",
"keygrip",
"=",
"keygrip",
")",
"break",
"except",
"KeyError",
"as",
"e",
":",
"log",
".",
"warning",... | Check if any keygrip corresponds to a TREZOR-based key. | [
"Check",
"if",
"any",
"keygrip",
"corresponds",
"to",
"a",
"TREZOR",
"-",
"based",
"key",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L201-L210 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.set_hash | def set_hash(self, algo, digest):
"""Set algorithm ID and hexadecimal digest for next operation."""
self.algo = algo
self.digest = digest | python | def set_hash(self, algo, digest):
"""Set algorithm ID and hexadecimal digest for next operation."""
self.algo = algo
self.digest = digest | [
"def",
"set_hash",
"(",
"self",
",",
"algo",
",",
"digest",
")",
":",
"self",
".",
"algo",
"=",
"algo",
"self",
".",
"digest",
"=",
"digest"
] | Set algorithm ID and hexadecimal digest for next operation. | [
"Set",
"algorithm",
"ID",
"and",
"hexadecimal",
"digest",
"for",
"next",
"operation",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L216-L219 | train |
romanz/trezor-agent | libagent/gpg/agent.py | Handler.handle | def handle(self, conn):
"""Handle connection from GPG binary using the ASSUAN protocol."""
keyring.sendline(conn, b'OK')
for line in keyring.iterlines(conn):
parts = line.split(b' ')
command = parts[0]
args = tuple(parts[1:])
if command == b'BYE':... | python | def handle(self, conn):
"""Handle connection from GPG binary using the ASSUAN protocol."""
keyring.sendline(conn, b'OK')
for line in keyring.iterlines(conn):
parts = line.split(b' ')
command = parts[0]
args = tuple(parts[1:])
if command == b'BYE':... | [
"def",
"handle",
"(",
"self",
",",
"conn",
")",
":",
"keyring",
".",
"sendline",
"(",
"conn",
",",
"b'OK'",
")",
"for",
"line",
"in",
"keyring",
".",
"iterlines",
"(",
"conn",
")",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"b' '",
")",
"command... | Handle connection from GPG binary using the ASSUAN protocol. | [
"Handle",
"connection",
"from",
"GPG",
"binary",
"using",
"the",
"ASSUAN",
"protocol",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/agent.py#L221-L247 | train |
romanz/trezor-agent | libagent/device/fake_device.py | FakeDevice.connect | def connect(self):
"""Return "dummy" connection."""
log.critical('NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!')
log.critical('ONLY FOR DEBUGGING AND TESTING!!!')
# The code below uses HARD-CODED secret key - and should be used ONLY
# for GnuPG integration tests (e.g. when no r... | python | def connect(self):
"""Return "dummy" connection."""
log.critical('NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!')
log.critical('ONLY FOR DEBUGGING AND TESTING!!!')
# The code below uses HARD-CODED secret key - and should be used ONLY
# for GnuPG integration tests (e.g. when no r... | [
"def",
"connect",
"(",
"self",
")",
":",
"log",
".",
"critical",
"(",
"'NEVER USE THIS CODE FOR REAL-LIFE USE-CASES!!!'",
")",
"log",
".",
"critical",
"(",
"'ONLY FOR DEBUGGING AND TESTING!!!'",
")",
"self",
".",
"secexp",
"=",
"1",
"self",
".",
"sk",
"=",
"ecds... | Return "dummy" connection. | [
"Return",
"dummy",
"connection",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/fake_device.py#L29-L40 | train |
romanz/trezor-agent | libagent/gpg/client.py | create_identity | def create_identity(user_id, curve_name):
"""Create GPG identity for hardware device."""
result = interface.Identity(identity_str='gpg://', curve_name=curve_name)
result.identity_dict['host'] = user_id
return result | python | def create_identity(user_id, curve_name):
"""Create GPG identity for hardware device."""
result = interface.Identity(identity_str='gpg://', curve_name=curve_name)
result.identity_dict['host'] = user_id
return result | [
"def",
"create_identity",
"(",
"user_id",
",",
"curve_name",
")",
":",
"result",
"=",
"interface",
".",
"Identity",
"(",
"identity_str",
"=",
"'gpg://'",
",",
"curve_name",
"=",
"curve_name",
")",
"result",
".",
"identity_dict",
"[",
"'host'",
"]",
"=",
"use... | Create GPG identity for hardware device. | [
"Create",
"GPG",
"identity",
"for",
"hardware",
"device",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L11-L15 | train |
romanz/trezor-agent | libagent/gpg/client.py | Client.pubkey | def pubkey(self, identity, ecdh=False):
"""Return public key as VerifyingKey object."""
with self.device:
pubkey = self.device.pubkey(ecdh=ecdh, identity=identity)
return formats.decompress_pubkey(
pubkey=pubkey, curve_name=identity.curve_name) | python | def pubkey(self, identity, ecdh=False):
"""Return public key as VerifyingKey object."""
with self.device:
pubkey = self.device.pubkey(ecdh=ecdh, identity=identity)
return formats.decompress_pubkey(
pubkey=pubkey, curve_name=identity.curve_name) | [
"def",
"pubkey",
"(",
"self",
",",
"identity",
",",
"ecdh",
"=",
"False",
")",
":",
"with",
"self",
".",
"device",
":",
"pubkey",
"=",
"self",
".",
"device",
".",
"pubkey",
"(",
"ecdh",
"=",
"ecdh",
",",
"identity",
"=",
"identity",
")",
"return",
... | Return public key as VerifyingKey object. | [
"Return",
"public",
"key",
"as",
"VerifyingKey",
"object",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L25-L30 | train |
romanz/trezor-agent | libagent/gpg/client.py | Client.sign | def sign(self, identity, digest):
"""Sign the digest and return a serialized signature."""
log.info('please confirm GPG signature on %s for "%s"...',
self.device, identity.to_string())
if identity.curve_name == formats.CURVE_NIST256:
digest = digest[:32] # sign the ... | python | def sign(self, identity, digest):
"""Sign the digest and return a serialized signature."""
log.info('please confirm GPG signature on %s for "%s"...',
self.device, identity.to_string())
if identity.curve_name == formats.CURVE_NIST256:
digest = digest[:32] # sign the ... | [
"def",
"sign",
"(",
"self",
",",
"identity",
",",
"digest",
")",
":",
"log",
".",
"info",
"(",
"'please confirm GPG signature on %s for \"%s\"...'",
",",
"self",
".",
"device",
",",
"identity",
".",
"to_string",
"(",
")",
")",
"if",
"identity",
".",
"curve_n... | Sign the digest and return a serialized signature. | [
"Sign",
"the",
"digest",
"and",
"return",
"a",
"serialized",
"signature",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L32-L41 | train |
romanz/trezor-agent | libagent/gpg/client.py | Client.ecdh | def ecdh(self, identity, pubkey):
"""Derive shared secret using ECDH from remote public key."""
log.info('please confirm GPG decryption on %s for "%s"...',
self.device, identity.to_string())
with self.device:
return self.device.ecdh(pubkey=pubkey, identity=identity) | python | def ecdh(self, identity, pubkey):
"""Derive shared secret using ECDH from remote public key."""
log.info('please confirm GPG decryption on %s for "%s"...',
self.device, identity.to_string())
with self.device:
return self.device.ecdh(pubkey=pubkey, identity=identity) | [
"def",
"ecdh",
"(",
"self",
",",
"identity",
",",
"pubkey",
")",
":",
"log",
".",
"info",
"(",
"'please confirm GPG decryption on %s for \"%s\"...'",
",",
"self",
".",
"device",
",",
"identity",
".",
"to_string",
"(",
")",
")",
"with",
"self",
".",
"device",... | Derive shared secret using ECDH from remote public key. | [
"Derive",
"shared",
"secret",
"using",
"ECDH",
"from",
"remote",
"public",
"key",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/client.py#L43-L48 | train |
romanz/trezor-agent | libagent/device/trezor.py | Trezor.connect | def connect(self):
"""Enumerate and connect to the first available interface."""
transport = self._defs.find_device()
if not transport:
raise interface.NotFoundError('{} not connected'.format(self))
log.debug('using transport: %s', transport)
for _ in range(5): # Re... | python | def connect(self):
"""Enumerate and connect to the first available interface."""
transport = self._defs.find_device()
if not transport:
raise interface.NotFoundError('{} not connected'.format(self))
log.debug('using transport: %s', transport)
for _ in range(5): # Re... | [
"def",
"connect",
"(",
"self",
")",
":",
"transport",
"=",
"self",
".",
"_defs",
".",
"find_device",
"(",
")",
"if",
"not",
"transport",
":",
"raise",
"interface",
".",
"NotFoundError",
"(",
"'{} not connected'",
".",
"format",
"(",
"self",
")",
")",
"lo... | Enumerate and connect to the first available interface. | [
"Enumerate",
"and",
"connect",
"to",
"the",
"first",
"available",
"interface",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/trezor.py#L47-L69 | train |
romanz/trezor-agent | libagent/device/interface.py | string_to_identity | def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v} | python | def string_to_identity(identity_str):
"""Parse string into Identity dictionary."""
m = _identity_regexp.match(identity_str)
result = m.groupdict()
log.debug('parsed identity: %s', result)
return {k: v for k, v in result.items() if v} | [
"def",
"string_to_identity",
"(",
"identity_str",
")",
":",
"m",
"=",
"_identity_regexp",
".",
"match",
"(",
"identity_str",
")",
"result",
"=",
"m",
".",
"groupdict",
"(",
")",
"log",
".",
"debug",
"(",
"'parsed identity: %s'",
",",
"result",
")",
"return",... | Parse string into Identity dictionary. | [
"Parse",
"string",
"into",
"Identity",
"dictionary",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L26-L31 | train |
romanz/trezor-agent | libagent/device/interface.py | identity_to_string | def identity_to_string(identity_dict):
"""Dump Identity dictionary into its string representation."""
result = []
if identity_dict.get('proto'):
result.append(identity_dict['proto'] + '://')
if identity_dict.get('user'):
result.append(identity_dict['user'] + '@')
result.append(identi... | python | def identity_to_string(identity_dict):
"""Dump Identity dictionary into its string representation."""
result = []
if identity_dict.get('proto'):
result.append(identity_dict['proto'] + '://')
if identity_dict.get('user'):
result.append(identity_dict['user'] + '@')
result.append(identi... | [
"def",
"identity_to_string",
"(",
"identity_dict",
")",
":",
"result",
"=",
"[",
"]",
"if",
"identity_dict",
".",
"get",
"(",
"'proto'",
")",
":",
"result",
".",
"append",
"(",
"identity_dict",
"[",
"'proto'",
"]",
"+",
"'://'",
")",
"if",
"identity_dict",... | Dump Identity dictionary into its string representation. | [
"Dump",
"Identity",
"dictionary",
"into",
"its",
"string",
"representation",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L34-L47 | train |
romanz/trezor-agent | libagent/device/interface.py | Identity.items | def items(self):
"""Return a copy of identity_dict items."""
return [(k, unidecode.unidecode(v))
for k, v in self.identity_dict.items()] | python | def items(self):
"""Return a copy of identity_dict items."""
return [(k, unidecode.unidecode(v))
for k, v in self.identity_dict.items()] | [
"def",
"items",
"(",
"self",
")",
":",
"return",
"[",
"(",
"k",
",",
"unidecode",
".",
"unidecode",
"(",
"v",
")",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"identity_dict",
".",
"items",
"(",
")",
"]"
] | Return a copy of identity_dict items. | [
"Return",
"a",
"copy",
"of",
"identity_dict",
"items",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L70-L73 | train |
romanz/trezor-agent | libagent/device/interface.py | Identity.to_bytes | def to_bytes(self):
"""Transliterate Unicode into ASCII."""
s = identity_to_string(self.identity_dict)
return unidecode.unidecode(s).encode('ascii') | python | def to_bytes(self):
"""Transliterate Unicode into ASCII."""
s = identity_to_string(self.identity_dict)
return unidecode.unidecode(s).encode('ascii') | [
"def",
"to_bytes",
"(",
"self",
")",
":",
"s",
"=",
"identity_to_string",
"(",
"self",
".",
"identity_dict",
")",
"return",
"unidecode",
".",
"unidecode",
"(",
"s",
")",
".",
"encode",
"(",
"'ascii'",
")"
] | Transliterate Unicode into ASCII. | [
"Transliterate",
"Unicode",
"into",
"ASCII",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L75-L78 | train |
romanz/trezor-agent | libagent/device/interface.py | Identity.get_curve_name | def get_curve_name(self, ecdh=False):
"""Return correct curve name for device operations."""
if ecdh:
return formats.get_ecdh_curve_name(self.curve_name)
else:
return self.curve_name | python | def get_curve_name(self, ecdh=False):
"""Return correct curve name for device operations."""
if ecdh:
return formats.get_ecdh_curve_name(self.curve_name)
else:
return self.curve_name | [
"def",
"get_curve_name",
"(",
"self",
",",
"ecdh",
"=",
"False",
")",
":",
"if",
"ecdh",
":",
"return",
"formats",
".",
"get_ecdh_curve_name",
"(",
"self",
".",
"curve_name",
")",
"else",
":",
"return",
"self",
".",
"curve_name"
] | Return correct curve name for device operations. | [
"Return",
"correct",
"curve",
"name",
"for",
"device",
"operations",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/interface.py#L97-L102 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | serve | def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT):
"""
Start the ssh-agent server on a UNIX-domain socket.
If no connection is made during the specified timeout,
retry until the context is over.
"""
ssh_version = subprocess.check_output(['ssh', '-V'],
... | python | def serve(handler, sock_path, timeout=UNIX_SOCKET_TIMEOUT):
"""
Start the ssh-agent server on a UNIX-domain socket.
If no connection is made during the specified timeout,
retry until the context is over.
"""
ssh_version = subprocess.check_output(['ssh', '-V'],
... | [
"def",
"serve",
"(",
"handler",
",",
"sock_path",
",",
"timeout",
"=",
"UNIX_SOCKET_TIMEOUT",
")",
":",
"ssh_version",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'ssh'",
",",
"'-V'",
"]",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"log",... | Start the ssh-agent server on a UNIX-domain socket.
If no connection is made during the specified timeout,
retry until the context is over. | [
"Start",
"the",
"ssh",
"-",
"agent",
"server",
"on",
"a",
"UNIX",
"-",
"domain",
"socket",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L124-L150 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | run_server | def run_server(conn, command, sock_path, debug, timeout):
"""Common code for run_agent and run_git below."""
ret = 0
try:
handler = protocol.Handler(conn=conn, debug=debug)
with serve(handler=handler, sock_path=sock_path,
timeout=timeout) as env:
if command:
... | python | def run_server(conn, command, sock_path, debug, timeout):
"""Common code for run_agent and run_git below."""
ret = 0
try:
handler = protocol.Handler(conn=conn, debug=debug)
with serve(handler=handler, sock_path=sock_path,
timeout=timeout) as env:
if command:
... | [
"def",
"run_server",
"(",
"conn",
",",
"command",
",",
"sock_path",
",",
"debug",
",",
"timeout",
")",
":",
"ret",
"=",
"0",
"try",
":",
"handler",
"=",
"protocol",
".",
"Handler",
"(",
"conn",
"=",
"conn",
",",
"debug",
"=",
"debug",
")",
"with",
... | Common code for run_agent and run_git below. | [
"Common",
"code",
"for",
"run_agent",
"and",
"run_git",
"below",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L153-L166 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | handle_connection_error | def handle_connection_error(func):
"""Fail with non-zero exit code."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except device.interface.NotFoundError as e:
log.error('Connection error (try unplugging and replugging your de... | python | def handle_connection_error(func):
"""Fail with non-zero exit code."""
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except device.interface.NotFoundError as e:
log.error('Connection error (try unplugging and replugging your de... | [
"def",
"handle_connection_error",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"try",
":",
"return",
"func",
"(",
"*",
"args",
",",
"**",
"kwargs",
")",
... | Fail with non-zero exit code. | [
"Fail",
"with",
"non",
"-",
"zero",
"exit",
"code",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L169-L178 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | parse_config | def parse_config(contents):
"""Parse config file into a list of Identity objects."""
for identity_str, curve_name in re.findall(r'\<(.*?)\|(.*?)\>', contents):
yield device.interface.Identity(identity_str=identity_str,
curve_name=curve_name) | python | def parse_config(contents):
"""Parse config file into a list of Identity objects."""
for identity_str, curve_name in re.findall(r'\<(.*?)\|(.*?)\>', contents):
yield device.interface.Identity(identity_str=identity_str,
curve_name=curve_name) | [
"def",
"parse_config",
"(",
"contents",
")",
":",
"for",
"identity_str",
",",
"curve_name",
"in",
"re",
".",
"findall",
"(",
"r'\\<(.*?)\\|(.*?)\\>'",
",",
"contents",
")",
":",
"yield",
"device",
".",
"interface",
".",
"Identity",
"(",
"identity_str",
"=",
... | Parse config file into a list of Identity objects. | [
"Parse",
"config",
"file",
"into",
"a",
"list",
"of",
"Identity",
"objects",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L181-L185 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | main | def main(device_type):
"""Run ssh-agent using given hardware client factory."""
args = create_agent_parser(device_type=device_type).parse_args()
util.setup_logging(verbosity=args.verbose, filename=args.log_file)
public_keys = None
filename = None
if args.identity.startswith('/'):
filena... | python | def main(device_type):
"""Run ssh-agent using given hardware client factory."""
args = create_agent_parser(device_type=device_type).parse_args()
util.setup_logging(verbosity=args.verbose, filename=args.log_file)
public_keys = None
filename = None
if args.identity.startswith('/'):
filena... | [
"def",
"main",
"(",
"device_type",
")",
":",
"args",
"=",
"create_agent_parser",
"(",
"device_type",
"=",
"device_type",
")",
".",
"parse_args",
"(",
")",
"util",
".",
"setup_logging",
"(",
"verbosity",
"=",
"args",
".",
"verbose",
",",
"filename",
"=",
"a... | Run ssh-agent using given hardware client factory. | [
"Run",
"ssh",
"-",
"agent",
"using",
"given",
"hardware",
"client",
"factory",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L255-L313 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | JustInTimeConnection.parse_public_keys | def parse_public_keys(self):
"""Parse SSH public keys into dictionaries."""
public_keys = [formats.import_public_key(pk)
for pk in self.public_keys()]
for pk, identity in zip(public_keys, self.identities):
pk['identity'] = identity
return public_keys | python | def parse_public_keys(self):
"""Parse SSH public keys into dictionaries."""
public_keys = [formats.import_public_key(pk)
for pk in self.public_keys()]
for pk, identity in zip(public_keys, self.identities):
pk['identity'] = identity
return public_keys | [
"def",
"parse_public_keys",
"(",
"self",
")",
":",
"public_keys",
"=",
"[",
"formats",
".",
"import_public_key",
"(",
"pk",
")",
"for",
"pk",
"in",
"self",
".",
"public_keys",
"(",
")",
"]",
"for",
"pk",
",",
"identity",
"in",
"zip",
"(",
"public_keys",
... | Parse SSH public keys into dictionaries. | [
"Parse",
"SSH",
"public",
"keys",
"into",
"dictionaries",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L213-L219 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | JustInTimeConnection.public_keys_as_files | def public_keys_as_files(self):
"""Store public keys as temporary SSH identity files."""
if not self.public_keys_tempfiles:
for pk in self.public_keys():
f = tempfile.NamedTemporaryFile(prefix='trezor-ssh-pubkey-', mode='w')
f.write(pk)
f.flush... | python | def public_keys_as_files(self):
"""Store public keys as temporary SSH identity files."""
if not self.public_keys_tempfiles:
for pk in self.public_keys():
f = tempfile.NamedTemporaryFile(prefix='trezor-ssh-pubkey-', mode='w')
f.write(pk)
f.flush... | [
"def",
"public_keys_as_files",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"public_keys_tempfiles",
":",
"for",
"pk",
"in",
"self",
".",
"public_keys",
"(",
")",
":",
"f",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"'trezor-ssh-pubk... | Store public keys as temporary SSH identity files. | [
"Store",
"public",
"keys",
"as",
"temporary",
"SSH",
"identity",
"files",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L221-L230 | train |
romanz/trezor-agent | libagent/ssh/__init__.py | JustInTimeConnection.sign | def sign(self, blob, identity):
"""Sign a given blob using the specified identity on the device."""
conn = self.conn_factory()
return conn.sign_ssh_challenge(blob=blob, identity=identity) | python | def sign(self, blob, identity):
"""Sign a given blob using the specified identity on the device."""
conn = self.conn_factory()
return conn.sign_ssh_challenge(blob=blob, identity=identity) | [
"def",
"sign",
"(",
"self",
",",
"blob",
",",
"identity",
")",
":",
"conn",
"=",
"self",
".",
"conn_factory",
"(",
")",
"return",
"conn",
".",
"sign_ssh_challenge",
"(",
"blob",
"=",
"blob",
",",
"identity",
"=",
"identity",
")"
] | Sign a given blob using the specified identity on the device. | [
"Sign",
"a",
"given",
"blob",
"using",
"the",
"specified",
"identity",
"on",
"the",
"device",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/ssh/__init__.py#L232-L235 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | packet | def packet(tag, blob):
"""Create small GPG packet."""
assert len(blob) < 2**32
if len(blob) < 2**8:
length_type = 0
elif len(blob) < 2**16:
length_type = 1
else:
length_type = 2
fmt = ['>B', '>H', '>L'][length_type]
leading_byte = 0x80 | (tag << 2) | (length_type)
... | python | def packet(tag, blob):
"""Create small GPG packet."""
assert len(blob) < 2**32
if len(blob) < 2**8:
length_type = 0
elif len(blob) < 2**16:
length_type = 1
else:
length_type = 2
fmt = ['>B', '>H', '>L'][length_type]
leading_byte = 0x80 | (tag << 2) | (length_type)
... | [
"def",
"packet",
"(",
"tag",
",",
"blob",
")",
":",
"assert",
"len",
"(",
"blob",
")",
"<",
"2",
"**",
"32",
"if",
"len",
"(",
"blob",
")",
"<",
"2",
"**",
"8",
":",
"length_type",
"=",
"0",
"elif",
"len",
"(",
"blob",
")",
"<",
"2",
"**",
... | Create small GPG packet. | [
"Create",
"small",
"GPG",
"packet",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L13-L26 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | subpacket | def subpacket(subpacket_type, fmt, *values):
"""Create GPG subpacket."""
blob = struct.pack(fmt, *values) if values else fmt
return struct.pack('>B', subpacket_type) + blob | python | def subpacket(subpacket_type, fmt, *values):
"""Create GPG subpacket."""
blob = struct.pack(fmt, *values) if values else fmt
return struct.pack('>B', subpacket_type) + blob | [
"def",
"subpacket",
"(",
"subpacket_type",
",",
"fmt",
",",
"*",
"values",
")",
":",
"blob",
"=",
"struct",
".",
"pack",
"(",
"fmt",
",",
"*",
"values",
")",
"if",
"values",
"else",
"fmt",
"return",
"struct",
".",
"pack",
"(",
"'>B'",
",",
"subpacket... | Create GPG subpacket. | [
"Create",
"GPG",
"subpacket",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L29-L32 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | subpacket_prefix_len | def subpacket_prefix_len(item):
"""Prefix subpacket length according to RFC 4880 section-5.2.3.1."""
n = len(item)
if n >= 8384:
prefix = b'\xFF' + struct.pack('>L', n)
elif n >= 192:
n = n - 192
prefix = struct.pack('BB', (n // 256) + 192, n % 256)
else:
prefix = str... | python | def subpacket_prefix_len(item):
"""Prefix subpacket length according to RFC 4880 section-5.2.3.1."""
n = len(item)
if n >= 8384:
prefix = b'\xFF' + struct.pack('>L', n)
elif n >= 192:
n = n - 192
prefix = struct.pack('BB', (n // 256) + 192, n % 256)
else:
prefix = str... | [
"def",
"subpacket_prefix_len",
"(",
"item",
")",
":",
"n",
"=",
"len",
"(",
"item",
")",
"if",
"n",
">=",
"8384",
":",
"prefix",
"=",
"b'\\xFF'",
"+",
"struct",
".",
"pack",
"(",
"'>L'",
",",
"n",
")",
"elif",
"n",
">=",
"192",
":",
"n",
"=",
"... | Prefix subpacket length according to RFC 4880 section-5.2.3.1. | [
"Prefix",
"subpacket",
"length",
"according",
"to",
"RFC",
"4880",
"section",
"-",
"5",
".",
"2",
".",
"3",
".",
"1",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L55-L65 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | subpackets | def subpackets(*items):
"""Serialize several GPG subpackets."""
prefixed = [subpacket_prefix_len(item) for item in items]
return util.prefix_len('>H', b''.join(prefixed)) | python | def subpackets(*items):
"""Serialize several GPG subpackets."""
prefixed = [subpacket_prefix_len(item) for item in items]
return util.prefix_len('>H', b''.join(prefixed)) | [
"def",
"subpackets",
"(",
"*",
"items",
")",
":",
"prefixed",
"=",
"[",
"subpacket_prefix_len",
"(",
"item",
")",
"for",
"item",
"in",
"items",
"]",
"return",
"util",
".",
"prefix_len",
"(",
"'>H'",
",",
"b''",
".",
"join",
"(",
"prefixed",
")",
")"
] | Serialize several GPG subpackets. | [
"Serialize",
"several",
"GPG",
"subpackets",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L68-L71 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | mpi | def mpi(value):
"""Serialize multipresicion integer using GPG format."""
bits = value.bit_length()
data_size = (bits + 7) // 8
data_bytes = bytearray(data_size)
for i in range(data_size):
data_bytes[i] = value & 0xFF
value = value >> 8
data_bytes.reverse()
return struct.pack... | python | def mpi(value):
"""Serialize multipresicion integer using GPG format."""
bits = value.bit_length()
data_size = (bits + 7) // 8
data_bytes = bytearray(data_size)
for i in range(data_size):
data_bytes[i] = value & 0xFF
value = value >> 8
data_bytes.reverse()
return struct.pack... | [
"def",
"mpi",
"(",
"value",
")",
":",
"bits",
"=",
"value",
".",
"bit_length",
"(",
")",
"data_size",
"=",
"(",
"bits",
"+",
"7",
")",
"//",
"8",
"data_bytes",
"=",
"bytearray",
"(",
"data_size",
")",
"for",
"i",
"in",
"range",
"(",
"data_size",
")... | Serialize multipresicion integer using GPG format. | [
"Serialize",
"multipresicion",
"integer",
"using",
"GPG",
"format",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L74-L84 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | keygrip_nist256 | def keygrip_nist256(vk):
"""Compute keygrip for NIST256 curve public keys."""
curve = vk.curve.curve
gen = vk.curve.generator
g = (4 << 512) | (gen.x() << 256) | gen.y()
point = vk.pubkey.point
q = (4 << 512) | (point.x() << 256) | point.y()
return _compute_keygrip([
['p', util.num2... | python | def keygrip_nist256(vk):
"""Compute keygrip for NIST256 curve public keys."""
curve = vk.curve.curve
gen = vk.curve.generator
g = (4 << 512) | (gen.x() << 256) | gen.y()
point = vk.pubkey.point
q = (4 << 512) | (point.x() << 256) | point.y()
return _compute_keygrip([
['p', util.num2... | [
"def",
"keygrip_nist256",
"(",
"vk",
")",
":",
"curve",
"=",
"vk",
".",
"curve",
".",
"curve",
"gen",
"=",
"vk",
".",
"curve",
".",
"generator",
"g",
"=",
"(",
"4",
"<<",
"512",
")",
"|",
"(",
"gen",
".",
"x",
"(",
")",
"<<",
"256",
")",
"|",... | Compute keygrip for NIST256 curve public keys. | [
"Compute",
"keygrip",
"for",
"NIST256",
"curve",
"public",
"keys",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L107-L122 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | keygrip_ed25519 | def keygrip_ed25519(vk):
"""Compute keygrip for Ed25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01'],
['b', util.num2bytes(0x2DFC9... | python | def keygrip_ed25519(vk):
"""Compute keygrip for Ed25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01'],
['b', util.num2bytes(0x2DFC9... | [
"def",
"keygrip_ed25519",
"(",
"vk",
")",
":",
"return",
"_compute_keygrip",
"(",
"[",
"[",
"'p'",
",",
"util",
".",
"num2bytes",
"(",
"0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED",
",",
"size",
"=",
"32",
")",
"]",
",",
"[",
"'a'",
",",
... | Compute keygrip for Ed25519 public keys. | [
"Compute",
"keygrip",
"for",
"Ed25519",
"public",
"keys",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L125-L135 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | keygrip_curve25519 | def keygrip_curve25519(vk):
"""Compute keygrip for Curve25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01\xDB\x41'],
['b', b'\x01']... | python | def keygrip_curve25519(vk):
"""Compute keygrip for Curve25519 public keys."""
# pylint: disable=line-too-long
return _compute_keygrip([
['p', util.num2bytes(0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED, size=32)], # nopep8
['a', b'\x01\xDB\x41'],
['b', b'\x01']... | [
"def",
"keygrip_curve25519",
"(",
"vk",
")",
":",
"return",
"_compute_keygrip",
"(",
"[",
"[",
"'p'",
",",
"util",
".",
"num2bytes",
"(",
"0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFED",
",",
"size",
"=",
"32",
")",
"]",
",",
"[",
"'a'",
","... | Compute keygrip for Curve25519 public keys. | [
"Compute",
"keygrip",
"for",
"Curve25519",
"public",
"keys",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L138-L148 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | get_curve_name_by_oid | def get_curve_name_by_oid(oid):
"""Return curve name matching specified OID, or raise KeyError."""
for curve_name, info in SUPPORTED_CURVES.items():
if info['oid'] == oid:
return curve_name
raise KeyError('Unknown OID: {!r}'.format(oid)) | python | def get_curve_name_by_oid(oid):
"""Return curve name matching specified OID, or raise KeyError."""
for curve_name, info in SUPPORTED_CURVES.items():
if info['oid'] == oid:
return curve_name
raise KeyError('Unknown OID: {!r}'.format(oid)) | [
"def",
"get_curve_name_by_oid",
"(",
"oid",
")",
":",
"for",
"curve_name",
",",
"info",
"in",
"SUPPORTED_CURVES",
".",
"items",
"(",
")",
":",
"if",
"info",
"[",
"'oid'",
"]",
"==",
"oid",
":",
"return",
"curve_name",
"raise",
"KeyError",
"(",
"'Unknown OI... | Return curve name matching specified OID, or raise KeyError. | [
"Return",
"curve",
"name",
"matching",
"specified",
"OID",
"or",
"raise",
"KeyError",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L180-L185 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | make_signature | def make_signature(signer_func, data_to_sign, public_algo,
hashed_subpackets, unhashed_subpackets, sig_type=0):
"""Create new GPG signature."""
# pylint: disable=too-many-arguments
header = struct.pack('>BBBB',
4, # version
sig_typ... | python | def make_signature(signer_func, data_to_sign, public_algo,
hashed_subpackets, unhashed_subpackets, sig_type=0):
"""Create new GPG signature."""
# pylint: disable=too-many-arguments
header = struct.pack('>BBBB',
4, # version
sig_typ... | [
"def",
"make_signature",
"(",
"signer_func",
",",
"data_to_sign",
",",
"public_algo",
",",
"hashed_subpackets",
",",
"unhashed_subpackets",
",",
"sig_type",
"=",
"0",
")",
":",
"header",
"=",
"struct",
".",
"pack",
"(",
"'>BBBB'",
",",
"4",
",",
"sig_type",
... | Create new GPG signature. | [
"Create",
"new",
"GPG",
"signature",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L254-L276 | train |
romanz/trezor-agent | libagent/gpg/protocol.py | PublicKey.data | def data(self):
"""Data for packet creation."""
header = struct.pack('>BLB',
4, # version
self.created, # creation
self.algo_id) # public key algorithm ID
oid = util.prefix_len('>B', self.curve_i... | python | def data(self):
"""Data for packet creation."""
header = struct.pack('>BLB',
4, # version
self.created, # creation
self.algo_id) # public key algorithm ID
oid = util.prefix_len('>B', self.curve_i... | [
"def",
"data",
"(",
"self",
")",
":",
"header",
"=",
"struct",
".",
"pack",
"(",
"'>BLB'",
",",
"4",
",",
"self",
".",
"created",
",",
"self",
".",
"algo_id",
")",
"oid",
"=",
"util",
".",
"prefix_len",
"(",
"'>B'",
",",
"self",
".",
"curve_info",
... | Data for packet creation. | [
"Data",
"for",
"packet",
"creation",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/protocol.py#L209-L217 | train |
romanz/trezor-agent | libagent/gpg/encode.py | create_subkey | def create_subkey(primary_bytes, subkey, signer_func, secret_bytes=b''):
"""Export new subkey to GPG primary key."""
subkey_packet = protocol.packet(tag=(7 if secret_bytes else 14),
blob=(subkey.data() + secret_bytes))
packets = list(decode.parse_packets(io.BytesIO(primar... | python | def create_subkey(primary_bytes, subkey, signer_func, secret_bytes=b''):
"""Export new subkey to GPG primary key."""
subkey_packet = protocol.packet(tag=(7 if secret_bytes else 14),
blob=(subkey.data() + secret_bytes))
packets = list(decode.parse_packets(io.BytesIO(primar... | [
"def",
"create_subkey",
"(",
"primary_bytes",
",",
"subkey",
",",
"signer_func",
",",
"secret_bytes",
"=",
"b''",
")",
":",
"subkey_packet",
"=",
"protocol",
".",
"packet",
"(",
"tag",
"=",
"(",
"7",
"if",
"secret_bytes",
"else",
"14",
")",
",",
"blob",
... | Export new subkey to GPG primary key. | [
"Export",
"new",
"subkey",
"to",
"GPG",
"primary",
"key",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/encode.py#L51-L103 | train |
romanz/trezor-agent | libagent/gpg/__init__.py | verify_gpg_version | def verify_gpg_version():
"""Make sure that the installed GnuPG is not too old."""
existing_gpg = keyring.gpg_version().decode('ascii')
required_gpg = '>=2.1.11'
msg = 'Existing GnuPG has version "{}" ({} required)'.format(existing_gpg,
re... | python | def verify_gpg_version():
"""Make sure that the installed GnuPG is not too old."""
existing_gpg = keyring.gpg_version().decode('ascii')
required_gpg = '>=2.1.11'
msg = 'Existing GnuPG has version "{}" ({} required)'.format(existing_gpg,
re... | [
"def",
"verify_gpg_version",
"(",
")",
":",
"existing_gpg",
"=",
"keyring",
".",
"gpg_version",
"(",
")",
".",
"decode",
"(",
"'ascii'",
")",
"required_gpg",
"=",
"'>=2.1.11'",
"msg",
"=",
"'Existing GnuPG has version \"{}\" ({} required)'",
".",
"format",
"(",
"e... | Make sure that the installed GnuPG is not too old. | [
"Make",
"sure",
"that",
"the",
"installed",
"GnuPG",
"is",
"not",
"too",
"old",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L83-L90 | train |
romanz/trezor-agent | libagent/gpg/__init__.py | check_output | def check_output(args):
"""Runs command and returns the output as string."""
log.debug('run: %s', args)
out = subprocess.check_output(args=args).decode('utf-8')
log.debug('out: %r', out)
return out | python | def check_output(args):
"""Runs command and returns the output as string."""
log.debug('run: %s', args)
out = subprocess.check_output(args=args).decode('utf-8')
log.debug('out: %r', out)
return out | [
"def",
"check_output",
"(",
"args",
")",
":",
"log",
".",
"debug",
"(",
"'run: %s'",
",",
"args",
")",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"args",
"=",
"args",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"log",
".",
"debug",
"(",
"'out: ... | Runs command and returns the output as string. | [
"Runs",
"command",
"and",
"returns",
"the",
"output",
"as",
"string",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L93-L98 | train |
romanz/trezor-agent | libagent/gpg/__init__.py | check_call | def check_call(args, stdin=None, env=None):
"""Runs command and verifies its success."""
log.debug('run: %s%s', args, ' {}'.format(env) if env else '')
subprocess.check_call(args=args, stdin=stdin, env=env) | python | def check_call(args, stdin=None, env=None):
"""Runs command and verifies its success."""
log.debug('run: %s%s', args, ' {}'.format(env) if env else '')
subprocess.check_call(args=args, stdin=stdin, env=env) | [
"def",
"check_call",
"(",
"args",
",",
"stdin",
"=",
"None",
",",
"env",
"=",
"None",
")",
":",
"log",
".",
"debug",
"(",
"'run: %s%s'",
",",
"args",
",",
"' {}'",
".",
"format",
"(",
"env",
")",
"if",
"env",
"else",
"''",
")",
"subprocess",
".",
... | Runs command and verifies its success. | [
"Runs",
"command",
"and",
"verifies",
"its",
"success",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L101-L104 | train |
romanz/trezor-agent | libagent/gpg/__init__.py | write_file | def write_file(path, data):
"""Writes data to specified path."""
with open(path, 'w') as f:
log.debug('setting %s contents:\n%s', path, data)
f.write(data)
return f | python | def write_file(path, data):
"""Writes data to specified path."""
with open(path, 'w') as f:
log.debug('setting %s contents:\n%s', path, data)
f.write(data)
return f | [
"def",
"write_file",
"(",
"path",
",",
"data",
")",
":",
"with",
"open",
"(",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"log",
".",
"debug",
"(",
"'setting %s contents:\\n%s'",
",",
"path",
",",
"data",
")",
"f",
".",
"write",
"(",
"data",
")",
"ret... | Writes data to specified path. | [
"Writes",
"data",
"to",
"specified",
"path",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L107-L112 | train |
romanz/trezor-agent | libagent/gpg/__init__.py | run_agent | def run_agent(device_type):
"""Run a simple GPG-agent server."""
p = argparse.ArgumentParser()
p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
p.add_argument('-v', '--verbose', default=0, action='count')
p.add_argument('--server', default=False, action='store_true',
... | python | def run_agent(device_type):
"""Run a simple GPG-agent server."""
p = argparse.ArgumentParser()
p.add_argument('--homedir', default=os.environ.get('GNUPGHOME'))
p.add_argument('-v', '--verbose', default=0, action='count')
p.add_argument('--server', default=False, action='store_true',
... | [
"def",
"run_agent",
"(",
"device_type",
")",
":",
"p",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"p",
".",
"add_argument",
"(",
"'--homedir'",
",",
"default",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'GNUPGHOME'",
")",
")",
"p",
".",
"add_a... | Run a simple GPG-agent server. | [
"Run",
"a",
"simple",
"GPG",
"-",
"agent",
"server",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/gpg/__init__.py#L222-L276 | train |
romanz/trezor-agent | libagent/device/trezor_defs.py | find_device | def find_device():
"""Selects a transport based on `TREZOR_PATH` environment variable.
If unset, picks first connected device.
"""
try:
return get_transport(os.environ.get("TREZOR_PATH"))
except Exception as e: # pylint: disable=broad-except
log.debug("Failed to find a Trezor devic... | python | def find_device():
"""Selects a transport based on `TREZOR_PATH` environment variable.
If unset, picks first connected device.
"""
try:
return get_transport(os.environ.get("TREZOR_PATH"))
except Exception as e: # pylint: disable=broad-except
log.debug("Failed to find a Trezor devic... | [
"def",
"find_device",
"(",
")",
":",
"try",
":",
"return",
"get_transport",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"TREZOR_PATH\"",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"\"Failed to find a Trezor device: %s\"",
",... | Selects a transport based on `TREZOR_PATH` environment variable.
If unset, picks first connected device. | [
"Selects",
"a",
"transport",
"based",
"on",
"TREZOR_PATH",
"environment",
"variable",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/trezor_defs.py#L22-L30 | train |
romanz/trezor-agent | libagent/device/ledger.py | _convert_public_key | def _convert_public_key(ecdsa_curve_name, result):
"""Convert Ledger reply into PublicKey object."""
if ecdsa_curve_name == 'nist256p1':
if (result[64] & 1) != 0:
result = bytearray([0x03]) + result[1:33]
else:
result = bytearray([0x02]) + result[1:33]
else:
r... | python | def _convert_public_key(ecdsa_curve_name, result):
"""Convert Ledger reply into PublicKey object."""
if ecdsa_curve_name == 'nist256p1':
if (result[64] & 1) != 0:
result = bytearray([0x03]) + result[1:33]
else:
result = bytearray([0x02]) + result[1:33]
else:
r... | [
"def",
"_convert_public_key",
"(",
"ecdsa_curve_name",
",",
"result",
")",
":",
"if",
"ecdsa_curve_name",
"==",
"'nist256p1'",
":",
"if",
"(",
"result",
"[",
"64",
"]",
"&",
"1",
")",
"!=",
"0",
":",
"result",
"=",
"bytearray",
"(",
"[",
"0x03",
"]",
"... | Convert Ledger reply into PublicKey object. | [
"Convert",
"Ledger",
"reply",
"into",
"PublicKey",
"object",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/ledger.py#L19-L33 | train |
romanz/trezor-agent | libagent/device/ledger.py | LedgerNanoS.connect | def connect(self):
"""Enumerate and connect to the first USB HID interface."""
try:
return comm.getDongle()
except comm.CommException as e:
raise interface.NotFoundError(
'{} not connected: "{}"'.format(self, e)) | python | def connect(self):
"""Enumerate and connect to the first USB HID interface."""
try:
return comm.getDongle()
except comm.CommException as e:
raise interface.NotFoundError(
'{} not connected: "{}"'.format(self, e)) | [
"def",
"connect",
"(",
"self",
")",
":",
"try",
":",
"return",
"comm",
".",
"getDongle",
"(",
")",
"except",
"comm",
".",
"CommException",
"as",
"e",
":",
"raise",
"interface",
".",
"NotFoundError",
"(",
"'{} not connected: \"{}\"'",
".",
"format",
"(",
"s... | Enumerate and connect to the first USB HID interface. | [
"Enumerate",
"and",
"connect",
"to",
"the",
"first",
"USB",
"HID",
"interface",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/ledger.py#L44-L50 | train |
romanz/trezor-agent | libagent/device/ledger.py | LedgerNanoS.pubkey | def pubkey(self, identity, ecdh=False):
"""Get PublicKey object for specified BIP32 address and elliptic curve."""
curve_name = identity.get_curve_name(ecdh)
path = _expand_path(identity.get_bip32_address(ecdh))
if curve_name == 'nist256p1':
p2 = '01'
else:
... | python | def pubkey(self, identity, ecdh=False):
"""Get PublicKey object for specified BIP32 address and elliptic curve."""
curve_name = identity.get_curve_name(ecdh)
path = _expand_path(identity.get_bip32_address(ecdh))
if curve_name == 'nist256p1':
p2 = '01'
else:
... | [
"def",
"pubkey",
"(",
"self",
",",
"identity",
",",
"ecdh",
"=",
"False",
")",
":",
"curve_name",
"=",
"identity",
".",
"get_curve_name",
"(",
"ecdh",
")",
"path",
"=",
"_expand_path",
"(",
"identity",
".",
"get_bip32_address",
"(",
"ecdh",
")",
")",
"if... | Get PublicKey object for specified BIP32 address and elliptic curve. | [
"Get",
"PublicKey",
"object",
"for",
"specified",
"BIP32",
"address",
"and",
"elliptic",
"curve",
"."
] | 513b1259c4d7aca5f88cd958edc11828d0712f1b | https://github.com/romanz/trezor-agent/blob/513b1259c4d7aca5f88cd958edc11828d0712f1b/libagent/device/ledger.py#L52-L67 | train |
inonit/drf-haystack | ez_setup.py | download_setuptools | def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the ... | python | def download_setuptools(version=DEFAULT_VERSION, download_base=DEFAULT_URL,
to_dir=os.curdir, delay=15):
"""Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the ... | [
"def",
"download_setuptools",
"(",
"version",
"=",
"DEFAULT_VERSION",
",",
"download_base",
"=",
"DEFAULT_URL",
",",
"to_dir",
"=",
"os",
".",
"curdir",
",",
"delay",
"=",
"15",
")",
":",
"to_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"to_dir",
"... | Download distribute from a specified location and return its filename
`version` should be a valid distribute version number that is available
as an egg for download under the `download_base` URL (which should end
with a '/'). `to_dir` is the directory where the egg will be downloaded.
`delay` is the nu... | [
"Download",
"distribute",
"from",
"a",
"specified",
"location",
"and",
"return",
"its",
"filename"
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/ez_setup.py#L170-L204 | train |
inonit/drf-haystack | drf_haystack/query.py | BaseQueryBuilder.tokenize | def tokenize(stream, separator):
"""
Tokenize and yield query parameter values.
:param stream: Input value
:param separator: Character to use to separate the tokens.
:return:
"""
for value in stream:
for token in value.split(separator):
... | python | def tokenize(stream, separator):
"""
Tokenize and yield query parameter values.
:param stream: Input value
:param separator: Character to use to separate the tokens.
:return:
"""
for value in stream:
for token in value.split(separator):
... | [
"def",
"tokenize",
"(",
"stream",
",",
"separator",
")",
":",
"for",
"value",
"in",
"stream",
":",
"for",
"token",
"in",
"value",
".",
"split",
"(",
"separator",
")",
":",
"if",
"token",
":",
"yield",
"token",
".",
"strip",
"(",
")"
] | Tokenize and yield query parameter values.
:param stream: Input value
:param separator: Character to use to separate the tokens.
:return: | [
"Tokenize",
"and",
"yield",
"query",
"parameter",
"values",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L34-L45 | train |
inonit/drf-haystack | drf_haystack/query.py | FilterQueryBuilder.build_query | def build_query(self, **filters):
"""
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields
that have been "registered" in `view.fields`.
Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any
query... | python | def build_query(self, **filters):
"""
Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields
that have been "registered" in `view.fields`.
Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any
query... | [
"def",
"build_query",
"(",
"self",
",",
"**",
"filters",
")",
":",
"applicable_filters",
"=",
"[",
"]",
"applicable_exclusions",
"=",
"[",
"]",
"for",
"param",
",",
"value",
"in",
"filters",
".",
"items",
"(",
")",
":",
"excluding_term",
"=",
"False",
"p... | Creates a single SQ filter from querystring parameters that correspond to the SearchIndex fields
that have been "registered" in `view.fields`.
Default behavior is to `OR` terms for the same parameters, and `AND` between parameters. Any
querystring parameters that are not registered in `view.fie... | [
"Creates",
"a",
"single",
"SQ",
"filter",
"from",
"querystring",
"parameters",
"that",
"correspond",
"to",
"the",
"SearchIndex",
"fields",
"that",
"have",
"been",
"registered",
"in",
"view",
".",
"fields",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L89-L151 | train |
inonit/drf-haystack | drf_haystack/query.py | FacetQueryBuilder.build_query | def build_query(self, **filters):
"""
Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an ex... | python | def build_query(self, **filters):
"""
Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an ex... | [
"def",
"build_query",
"(",
"self",
",",
"**",
"filters",
")",
":",
"field_facets",
"=",
"{",
"}",
"date_facets",
"=",
"{",
"}",
"query_facets",
"=",
"{",
"}",
"facet_serializer_cls",
"=",
"self",
".",
"view",
".",
"get_facet_serializer_class",
"(",
")",
"i... | Creates a dict of dictionaries suitable for passing to the SearchQuerySet `facet`,
`date_facet` or `query_facet` method. All key word arguments should be wrapped in a list.
:param view: API View
:param dict[str, list[str]] filters: is an expanded QueryDict or a mapping
of keys to a lis... | [
"Creates",
"a",
"dict",
"of",
"dictionaries",
"suitable",
"for",
"passing",
"to",
"the",
"SearchQuerySet",
"facet",
"date_facet",
"or",
"query_facet",
"method",
".",
"All",
"key",
"word",
"arguments",
"should",
"be",
"wrapped",
"in",
"a",
"list",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L159-L210 | train |
inonit/drf-haystack | drf_haystack/query.py | FacetQueryBuilder.parse_field_options | def parse_field_options(self, *options):
"""
Parse the field options query string and return it as a dictionary.
"""
defaults = {}
for option in options:
if isinstance(option, six.text_type):
tokens = [token.strip() for token in option.split(self.view.... | python | def parse_field_options(self, *options):
"""
Parse the field options query string and return it as a dictionary.
"""
defaults = {}
for option in options:
if isinstance(option, six.text_type):
tokens = [token.strip() for token in option.split(self.view.... | [
"def",
"parse_field_options",
"(",
"self",
",",
"*",
"options",
")",
":",
"defaults",
"=",
"{",
"}",
"for",
"option",
"in",
"options",
":",
"if",
"isinstance",
"(",
"option",
",",
"six",
".",
"text_type",
")",
":",
"tokens",
"=",
"[",
"token",
".",
"... | Parse the field options query string and return it as a dictionary. | [
"Parse",
"the",
"field",
"options",
"query",
"string",
"and",
"return",
"it",
"as",
"a",
"dictionary",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L212-L239 | train |
inonit/drf-haystack | drf_haystack/query.py | SpatialQueryBuilder.build_query | def build_query(self, **filters):
"""
Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latit... | python | def build_query(self, **filters):
"""
Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latit... | [
"def",
"build_query",
"(",
"self",
",",
"**",
"filters",
")",
":",
"applicable_filters",
"=",
"None",
"filters",
"=",
"dict",
"(",
"(",
"k",
",",
"filters",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"chain",
"(",
"self",
".",
"D",
".",
"UNITS",
".",
... | Build queries for geo spatial filtering.
Expected query parameters are:
- a `unit=value` parameter where the unit is a valid UNIT in the
`django.contrib.gis.measure.Distance` class.
- `from` which must be a comma separated latitude and longitude.
Example query:
... | [
"Build",
"queries",
"for",
"geo",
"spatial",
"filtering",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/query.py#L266-L318 | train |
inonit/drf-haystack | drf_haystack/utils.py | merge_dict | def merge_dict(a, b):
"""
Recursively merges and returns dict a with dict b.
Any list values will be combined and returned sorted.
:param a: dictionary object
:param b: dictionary object
:return: merged dictionary object
"""
if not isinstance(b, dict):
return b
result = de... | python | def merge_dict(a, b):
"""
Recursively merges and returns dict a with dict b.
Any list values will be combined and returned sorted.
:param a: dictionary object
:param b: dictionary object
:return: merged dictionary object
"""
if not isinstance(b, dict):
return b
result = de... | [
"def",
"merge_dict",
"(",
"a",
",",
"b",
")",
":",
"if",
"not",
"isinstance",
"(",
"b",
",",
"dict",
")",
":",
"return",
"b",
"result",
"=",
"deepcopy",
"(",
"a",
")",
"for",
"key",
",",
"val",
"in",
"six",
".",
"iteritems",
"(",
"b",
")",
":",... | Recursively merges and returns dict a with dict b.
Any list values will be combined and returned sorted.
:param a: dictionary object
:param b: dictionary object
:return: merged dictionary object | [
"Recursively",
"merges",
"and",
"returns",
"dict",
"a",
"with",
"dict",
"b",
".",
"Any",
"list",
"values",
"will",
"be",
"combined",
"and",
"returned",
"sorted",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/utils.py#L9-L31 | train |
inonit/drf-haystack | drf_haystack/generics.py | HaystackGenericAPIView.get_queryset | def get_queryset(self, index_models=[]):
"""
Get the list of items for this view.
Returns ``self.queryset`` if defined and is a ``self.object_class``
instance.
@:param index_models: override `self.index_models`
"""
if self.queryset is not None and isinstance(self... | python | def get_queryset(self, index_models=[]):
"""
Get the list of items for this view.
Returns ``self.queryset`` if defined and is a ``self.object_class``
instance.
@:param index_models: override `self.index_models`
"""
if self.queryset is not None and isinstance(self... | [
"def",
"get_queryset",
"(",
"self",
",",
"index_models",
"=",
"[",
"]",
")",
":",
"if",
"self",
".",
"queryset",
"is",
"not",
"None",
"and",
"isinstance",
"(",
"self",
".",
"queryset",
",",
"self",
".",
"object_class",
")",
":",
"queryset",
"=",
"self"... | Get the list of items for this view.
Returns ``self.queryset`` if defined and is a ``self.object_class``
instance.
@:param index_models: override `self.index_models` | [
"Get",
"the",
"list",
"of",
"items",
"for",
"this",
"view",
".",
"Returns",
"self",
".",
"queryset",
"if",
"defined",
"and",
"is",
"a",
"self",
".",
"object_class",
"instance",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/generics.py#L40-L56 | train |
inonit/drf-haystack | drf_haystack/generics.py | HaystackGenericAPIView.get_object | def get_object(self):
"""
Fetch a single document from the data store according to whatever
unique identifier is available for that document in the
SearchIndex.
In cases where the view has multiple ``index_models``, add a ``model`` query
parameter containing a single `ap... | python | def get_object(self):
"""
Fetch a single document from the data store according to whatever
unique identifier is available for that document in the
SearchIndex.
In cases where the view has multiple ``index_models``, add a ``model`` query
parameter containing a single `ap... | [
"def",
"get_object",
"(",
"self",
")",
":",
"queryset",
"=",
"self",
".",
"get_queryset",
"(",
")",
"if",
"\"model\"",
"in",
"self",
".",
"request",
".",
"query_params",
":",
"try",
":",
"app_label",
",",
"model",
"=",
"map",
"(",
"six",
".",
"text_typ... | Fetch a single document from the data store according to whatever
unique identifier is available for that document in the
SearchIndex.
In cases where the view has multiple ``index_models``, add a ``model`` query
parameter containing a single `app_label.model` name to the request in orde... | [
"Fetch",
"a",
"single",
"document",
"from",
"the",
"data",
"store",
"according",
"to",
"whatever",
"unique",
"identifier",
"is",
"available",
"for",
"that",
"document",
"in",
"the",
"SearchIndex",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/generics.py#L58-L95 | train |
inonit/drf-haystack | drf_haystack/mixins.py | MoreLikeThisMixin.more_like_this | def more_like_this(self, request, pk=None):
"""
Sets up a detail route for ``more-like-this`` results.
Note that you'll need backend support in order to take advantage of this.
This will add ie. ^search/{pk}/more-like-this/$ to your existing ^search pattern.
"""
obj = se... | python | def more_like_this(self, request, pk=None):
"""
Sets up a detail route for ``more-like-this`` results.
Note that you'll need backend support in order to take advantage of this.
This will add ie. ^search/{pk}/more-like-this/$ to your existing ^search pattern.
"""
obj = se... | [
"def",
"more_like_this",
"(",
"self",
",",
"request",
",",
"pk",
"=",
"None",
")",
":",
"obj",
"=",
"self",
".",
"get_object",
"(",
")",
".",
"object",
"queryset",
"=",
"self",
".",
"filter_queryset",
"(",
"self",
".",
"get_queryset",
"(",
")",
")",
... | Sets up a detail route for ``more-like-this`` results.
Note that you'll need backend support in order to take advantage of this.
This will add ie. ^search/{pk}/more-like-this/$ to your existing ^search pattern. | [
"Sets",
"up",
"a",
"detail",
"route",
"for",
"more",
"-",
"like",
"-",
"this",
"results",
".",
"Note",
"that",
"you",
"ll",
"need",
"backend",
"support",
"in",
"order",
"to",
"take",
"advantage",
"of",
"this",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/mixins.py#L17-L33 | train |
inonit/drf-haystack | drf_haystack/mixins.py | FacetMixin.filter_facet_queryset | def filter_facet_queryset(self, queryset):
"""
Given a search queryset, filter it with whichever facet filter backends
in use.
"""
for backend in list(self.facet_filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
if self.load... | python | def filter_facet_queryset(self, queryset):
"""
Given a search queryset, filter it with whichever facet filter backends
in use.
"""
for backend in list(self.facet_filter_backends):
queryset = backend().filter_queryset(self.request, queryset, self)
if self.load... | [
"def",
"filter_facet_queryset",
"(",
"self",
",",
"queryset",
")",
":",
"for",
"backend",
"in",
"list",
"(",
"self",
".",
"facet_filter_backends",
")",
":",
"queryset",
"=",
"backend",
"(",
")",
".",
"filter_queryset",
"(",
"self",
".",
"request",
",",
"qu... | Given a search queryset, filter it with whichever facet filter backends
in use. | [
"Given",
"a",
"search",
"queryset",
"filter",
"it",
"with",
"whichever",
"facet",
"filter",
"backends",
"in",
"use",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/mixins.py#L66-L77 | train |
inonit/drf-haystack | drf_haystack/mixins.py | FacetMixin.get_facet_serializer | def get_facet_serializer(self, *args, **kwargs):
"""
Return the facet serializer instance that should be used for
serializing faceted output.
"""
assert "objects" in kwargs, "`objects` is a required argument to `get_facet_serializer()`"
facet_serializer_class = self.get_... | python | def get_facet_serializer(self, *args, **kwargs):
"""
Return the facet serializer instance that should be used for
serializing faceted output.
"""
assert "objects" in kwargs, "`objects` is a required argument to `get_facet_serializer()`"
facet_serializer_class = self.get_... | [
"def",
"get_facet_serializer",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"assert",
"\"objects\"",
"in",
"kwargs",
",",
"\"`objects` is a required argument to `get_facet_serializer()`\"",
"facet_serializer_class",
"=",
"self",
".",
"get_facet_serializer... | Return the facet serializer instance that should be used for
serializing faceted output. | [
"Return",
"the",
"facet",
"serializer",
"instance",
"that",
"should",
"be",
"used",
"for",
"serializing",
"faceted",
"output",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/mixins.py#L79-L92 | train |
inonit/drf-haystack | drf_haystack/mixins.py | FacetMixin.get_facet_serializer_class | def get_facet_serializer_class(self):
"""
Return the class to use for serializing facets.
Defaults to using ``self.facet_serializer_class``.
"""
if self.facet_serializer_class is None:
raise AttributeError(
"%(cls)s should either include a `facet_seria... | python | def get_facet_serializer_class(self):
"""
Return the class to use for serializing facets.
Defaults to using ``self.facet_serializer_class``.
"""
if self.facet_serializer_class is None:
raise AttributeError(
"%(cls)s should either include a `facet_seria... | [
"def",
"get_facet_serializer_class",
"(",
"self",
")",
":",
"if",
"self",
".",
"facet_serializer_class",
"is",
"None",
":",
"raise",
"AttributeError",
"(",
"\"%(cls)s should either include a `facet_serializer_class` attribute, \"",
"\"or override %(cls)s.get_facet_serializer_class(... | Return the class to use for serializing facets.
Defaults to using ``self.facet_serializer_class``. | [
"Return",
"the",
"class",
"to",
"use",
"for",
"serializing",
"facets",
".",
"Defaults",
"to",
"using",
"self",
".",
"facet_serializer_class",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/mixins.py#L94-L105 | train |
inonit/drf-haystack | drf_haystack/mixins.py | FacetMixin.get_facet_objects_serializer | def get_facet_objects_serializer(self, *args, **kwargs):
"""
Return the serializer instance which should be used for
serializing faceted objects.
"""
facet_objects_serializer_class = self.get_facet_objects_serializer_class()
kwargs["context"] = self.get_serializer_context... | python | def get_facet_objects_serializer(self, *args, **kwargs):
"""
Return the serializer instance which should be used for
serializing faceted objects.
"""
facet_objects_serializer_class = self.get_facet_objects_serializer_class()
kwargs["context"] = self.get_serializer_context... | [
"def",
"get_facet_objects_serializer",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"facet_objects_serializer_class",
"=",
"self",
".",
"get_facet_objects_serializer_class",
"(",
")",
"kwargs",
"[",
"\"context\"",
"]",
"=",
"self",
".",
"get_seria... | Return the serializer instance which should be used for
serializing faceted objects. | [
"Return",
"the",
"serializer",
"instance",
"which",
"should",
"be",
"used",
"for",
"serializing",
"faceted",
"objects",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/mixins.py#L107-L114 | train |
inonit/drf-haystack | drf_haystack/fields.py | DRFHaystackFieldMixin.bind | def bind(self, field_name, parent):
"""
Initializes the field name and parent for the field instance.
Called when a field is added to the parent serializer instance.
Taken from DRF and modified to support drf_haystack multiple index
functionality.
"""
# In order ... | python | def bind(self, field_name, parent):
"""
Initializes the field name and parent for the field instance.
Called when a field is added to the parent serializer instance.
Taken from DRF and modified to support drf_haystack multiple index
functionality.
"""
# In order ... | [
"def",
"bind",
"(",
"self",
",",
"field_name",
",",
"parent",
")",
":",
"assert",
"self",
".",
"source",
"!=",
"field_name",
",",
"(",
"\"It is redundant to specify `source='%s'` on field '%s' in \"",
"\"serializer '%s', because it is the same as the field name. \"",
"\"Remov... | Initializes the field name and parent for the field instance.
Called when a field is added to the parent serializer instance.
Taken from DRF and modified to support drf_haystack multiple index
functionality. | [
"Initializes",
"the",
"field",
"name",
"and",
"parent",
"for",
"the",
"field",
"instance",
".",
"Called",
"when",
"a",
"field",
"is",
"added",
"to",
"the",
"parent",
"serializer",
"instance",
".",
"Taken",
"from",
"DRF",
"and",
"modified",
"to",
"support",
... | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/fields.py#L16-L50 | train |
inonit/drf-haystack | drf_haystack/serializers.py | HaystackSerializer._get_default_field_kwargs | def _get_default_field_kwargs(model, field):
"""
Get the required attributes from the model field in order
to instantiate a REST Framework serializer field.
"""
kwargs = {}
try:
field_name = field.model_attr or field.index_fieldname
model_field = m... | python | def _get_default_field_kwargs(model, field):
"""
Get the required attributes from the model field in order
to instantiate a REST Framework serializer field.
"""
kwargs = {}
try:
field_name = field.model_attr or field.index_fieldname
model_field = m... | [
"def",
"_get_default_field_kwargs",
"(",
"model",
",",
"field",
")",
":",
"kwargs",
"=",
"{",
"}",
"try",
":",
"field_name",
"=",
"field",
".",
"model_attr",
"or",
"field",
".",
"index_fieldname",
"model_field",
"=",
"model",
".",
"_meta",
".",
"get_field",
... | Get the required attributes from the model field in order
to instantiate a REST Framework serializer field. | [
"Get",
"the",
"required",
"attributes",
"from",
"the",
"model",
"field",
"in",
"order",
"to",
"instantiate",
"a",
"REST",
"Framework",
"serializer",
"field",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L124-L148 | train |
inonit/drf-haystack | drf_haystack/serializers.py | HaystackSerializer._get_index_class_name | def _get_index_class_name(self, index_cls):
"""
Converts in index model class to a name suitable for use as a field name prefix. A user
may optionally specify custom aliases via an 'index_aliases' attribute on the Meta class
"""
cls_name = index_cls.__name__
aliases = sel... | python | def _get_index_class_name(self, index_cls):
"""
Converts in index model class to a name suitable for use as a field name prefix. A user
may optionally specify custom aliases via an 'index_aliases' attribute on the Meta class
"""
cls_name = index_cls.__name__
aliases = sel... | [
"def",
"_get_index_class_name",
"(",
"self",
",",
"index_cls",
")",
":",
"cls_name",
"=",
"index_cls",
".",
"__name__",
"aliases",
"=",
"self",
".",
"Meta",
".",
"index_aliases",
"return",
"aliases",
".",
"get",
"(",
"cls_name",
",",
"cls_name",
".",
"split"... | Converts in index model class to a name suitable for use as a field name prefix. A user
may optionally specify custom aliases via an 'index_aliases' attribute on the Meta class | [
"Converts",
"in",
"index",
"model",
"class",
"to",
"a",
"name",
"suitable",
"for",
"use",
"as",
"a",
"field",
"name",
"prefix",
".",
"A",
"user",
"may",
"optionally",
"specify",
"custom",
"aliases",
"via",
"an",
"index_aliases",
"attribute",
"on",
"the",
"... | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L156-L163 | train |
inonit/drf-haystack | drf_haystack/serializers.py | HaystackSerializer.get_fields | def get_fields(self):
"""
Get the required fields for serializing the result.
"""
fields = self.Meta.fields
exclude = self.Meta.exclude
ignore_fields = self.Meta.ignore_fields
indices = self.Meta.index_classes
declared_fields = copy.deepcopy(self._declar... | python | def get_fields(self):
"""
Get the required fields for serializing the result.
"""
fields = self.Meta.fields
exclude = self.Meta.exclude
ignore_fields = self.Meta.ignore_fields
indices = self.Meta.index_classes
declared_fields = copy.deepcopy(self._declar... | [
"def",
"get_fields",
"(",
"self",
")",
":",
"fields",
"=",
"self",
".",
"Meta",
".",
"fields",
"exclude",
"=",
"self",
".",
"Meta",
".",
"exclude",
"ignore_fields",
"=",
"self",
".",
"Meta",
".",
"ignore_fields",
"indices",
"=",
"self",
".",
"Meta",
".... | Get the required fields for serializing the result. | [
"Get",
"the",
"required",
"fields",
"for",
"serializing",
"the",
"result",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L165-L214 | train |
inonit/drf-haystack | drf_haystack/serializers.py | HaystackSerializer.to_representation | def to_representation(self, instance):
"""
If we have a serializer mapping, use that. Otherwise, use standard serializer behavior
Since we might be dealing with multiple indexes, some fields might
not be valid for all results. Do not render the fields which don't belong
to the s... | python | def to_representation(self, instance):
"""
If we have a serializer mapping, use that. Otherwise, use standard serializer behavior
Since we might be dealing with multiple indexes, some fields might
not be valid for all results. Do not render the fields which don't belong
to the s... | [
"def",
"to_representation",
"(",
"self",
",",
"instance",
")",
":",
"if",
"self",
".",
"Meta",
".",
"serializers",
":",
"ret",
"=",
"self",
".",
"multi_serializer_representation",
"(",
"instance",
")",
"else",
":",
"ret",
"=",
"super",
"(",
"HaystackSerializ... | If we have a serializer mapping, use that. Otherwise, use standard serializer behavior
Since we might be dealing with multiple indexes, some fields might
not be valid for all results. Do not render the fields which don't belong
to the search result. | [
"If",
"we",
"have",
"a",
"serializer",
"mapping",
"use",
"that",
".",
"Otherwise",
"use",
"standard",
"serializer",
"behavior",
"Since",
"we",
"might",
"be",
"dealing",
"with",
"multiple",
"indexes",
"some",
"fields",
"might",
"not",
"be",
"valid",
"for",
"a... | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L216-L251 | train |
inonit/drf-haystack | drf_haystack/serializers.py | FacetFieldSerializer.get_narrow_url | def get_narrow_url(self, instance):
"""
Return a link suitable for narrowing on the current item.
"""
text = instance[0]
request = self.context["request"]
query_params = request.GET.copy()
# Never keep the page query parameter in narrowing urls.
# It will... | python | def get_narrow_url(self, instance):
"""
Return a link suitable for narrowing on the current item.
"""
text = instance[0]
request = self.context["request"]
query_params = request.GET.copy()
# Never keep the page query parameter in narrowing urls.
# It will... | [
"def",
"get_narrow_url",
"(",
"self",
",",
"instance",
")",
":",
"text",
"=",
"instance",
"[",
"0",
"]",
"request",
"=",
"self",
".",
"context",
"[",
"\"request\"",
"]",
"query_params",
"=",
"request",
".",
"GET",
".",
"copy",
"(",
")",
"page_query_param... | Return a link suitable for narrowing on the current item. | [
"Return",
"a",
"link",
"suitable",
"for",
"narrowing",
"on",
"the",
"current",
"item",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L340-L360 | train |
inonit/drf-haystack | drf_haystack/serializers.py | FacetFieldSerializer.to_representation | def to_representation(self, field, instance):
"""
Set the ``parent_field`` property equal to the current field on the serializer class,
so that each field can query it to see what kind of attribute they are processing.
"""
self.parent_field = field
return super(FacetField... | python | def to_representation(self, field, instance):
"""
Set the ``parent_field`` property equal to the current field on the serializer class,
so that each field can query it to see what kind of attribute they are processing.
"""
self.parent_field = field
return super(FacetField... | [
"def",
"to_representation",
"(",
"self",
",",
"field",
",",
"instance",
")",
":",
"self",
".",
"parent_field",
"=",
"field",
"return",
"super",
"(",
"FacetFieldSerializer",
",",
"self",
")",
".",
"to_representation",
"(",
"instance",
")"
] | Set the ``parent_field`` property equal to the current field on the serializer class,
so that each field can query it to see what kind of attribute they are processing. | [
"Set",
"the",
"parent_field",
"property",
"equal",
"to",
"the",
"current",
"field",
"on",
"the",
"serializer",
"class",
"so",
"that",
"each",
"field",
"can",
"query",
"it",
"to",
"see",
"what",
"kind",
"of",
"attribute",
"they",
"are",
"processing",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L362-L368 | train |
inonit/drf-haystack | drf_haystack/serializers.py | HaystackFacetSerializer.get_fields | def get_fields(self):
"""
This returns a dictionary containing the top most fields,
``dates``, ``fields`` and ``queries``.
"""
field_mapping = OrderedDict()
for field, data in self.instance.items():
field_mapping.update(
{field: self.facet_dict... | python | def get_fields(self):
"""
This returns a dictionary containing the top most fields,
``dates``, ``fields`` and ``queries``.
"""
field_mapping = OrderedDict()
for field, data in self.instance.items():
field_mapping.update(
{field: self.facet_dict... | [
"def",
"get_fields",
"(",
"self",
")",
":",
"field_mapping",
"=",
"OrderedDict",
"(",
")",
"for",
"field",
",",
"data",
"in",
"self",
".",
"instance",
".",
"items",
"(",
")",
":",
"field_mapping",
".",
"update",
"(",
"{",
"field",
":",
"self",
".",
"... | This returns a dictionary containing the top most fields,
``dates``, ``fields`` and ``queries``. | [
"This",
"returns",
"a",
"dictionary",
"containing",
"the",
"top",
"most",
"fields",
"dates",
"fields",
"and",
"queries",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L384-L399 | train |
inonit/drf-haystack | drf_haystack/serializers.py | HaystackFacetSerializer.get_objects | def get_objects(self, instance):
"""
Return a list of objects matching the faceted result.
"""
view = self.context["view"]
queryset = self.context["objects"]
page = view.paginate_queryset(queryset)
if page is not None:
serializer = view.get_facet_obje... | python | def get_objects(self, instance):
"""
Return a list of objects matching the faceted result.
"""
view = self.context["view"]
queryset = self.context["objects"]
page = view.paginate_queryset(queryset)
if page is not None:
serializer = view.get_facet_obje... | [
"def",
"get_objects",
"(",
"self",
",",
"instance",
")",
":",
"view",
"=",
"self",
".",
"context",
"[",
"\"view\"",
"]",
"queryset",
"=",
"self",
".",
"context",
"[",
"\"objects\"",
"]",
"page",
"=",
"view",
".",
"paginate_queryset",
"(",
"queryset",
")"... | Return a list of objects matching the faceted result. | [
"Return",
"a",
"list",
"of",
"objects",
"matching",
"the",
"faceted",
"result",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L401-L419 | train |
inonit/drf-haystack | drf_haystack/serializers.py | HighlighterMixin.get_document_field | def get_document_field(instance):
"""
Returns which field the search index has marked as it's
`document=True` field.
"""
for name, field in instance.searchindex.fields.items():
if field.document is True:
return name | python | def get_document_field(instance):
"""
Returns which field the search index has marked as it's
`document=True` field.
"""
for name, field in instance.searchindex.fields.items():
if field.document is True:
return name | [
"def",
"get_document_field",
"(",
"instance",
")",
":",
"for",
"name",
",",
"field",
"in",
"instance",
".",
"searchindex",
".",
"fields",
".",
"items",
"(",
")",
":",
"if",
"field",
".",
"document",
"is",
"True",
":",
"return",
"name"
] | Returns which field the search index has marked as it's
`document=True` field. | [
"Returns",
"which",
"field",
"the",
"search",
"index",
"has",
"marked",
"as",
"it",
"s",
"document",
"=",
"True",
"field",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/serializers.py#L470-L477 | train |
inonit/drf-haystack | drf_haystack/filters.py | BaseHaystackFilterBackend.apply_filters | def apply_filters(self, queryset, applicable_filters=None, applicable_exclusions=None):
"""
Apply constructed filters and excludes and return the queryset
:param queryset: queryset to filter
:param applicable_filters: filters which are passed directly to queryset.filter()
:param... | python | def apply_filters(self, queryset, applicable_filters=None, applicable_exclusions=None):
"""
Apply constructed filters and excludes and return the queryset
:param queryset: queryset to filter
:param applicable_filters: filters which are passed directly to queryset.filter()
:param... | [
"def",
"apply_filters",
"(",
"self",
",",
"queryset",
",",
"applicable_filters",
"=",
"None",
",",
"applicable_exclusions",
"=",
"None",
")",
":",
"if",
"applicable_filters",
":",
"queryset",
"=",
"queryset",
".",
"filter",
"(",
"applicable_filters",
")",
"if",
... | Apply constructed filters and excludes and return the queryset
:param queryset: queryset to filter
:param applicable_filters: filters which are passed directly to queryset.filter()
:param applicable_exclusions: filters which are passed directly to queryset.exclude()
:returns filtered qu... | [
"Apply",
"constructed",
"filters",
"and",
"excludes",
"and",
"return",
"the",
"queryset"
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/filters.py#L27-L40 | train |
inonit/drf-haystack | drf_haystack/filters.py | BaseHaystackFilterBackend.build_filters | def build_filters(self, view, filters=None):
"""
Get the query builder instance and return constructed query filters.
"""
query_builder = self.get_query_builder(backend=self, view=view)
return query_builder.build_query(**(filters if filters else {})) | python | def build_filters(self, view, filters=None):
"""
Get the query builder instance and return constructed query filters.
"""
query_builder = self.get_query_builder(backend=self, view=view)
return query_builder.build_query(**(filters if filters else {})) | [
"def",
"build_filters",
"(",
"self",
",",
"view",
",",
"filters",
"=",
"None",
")",
":",
"query_builder",
"=",
"self",
".",
"get_query_builder",
"(",
"backend",
"=",
"self",
",",
"view",
"=",
"view",
")",
"return",
"query_builder",
".",
"build_query",
"(",... | Get the query builder instance and return constructed query filters. | [
"Get",
"the",
"query",
"builder",
"instance",
"and",
"return",
"constructed",
"query",
"filters",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/filters.py#L42-L47 | train |
inonit/drf-haystack | drf_haystack/filters.py | BaseHaystackFilterBackend.filter_queryset | def filter_queryset(self, request, queryset, view):
"""
Return the filtered queryset.
"""
applicable_filters, applicable_exclusions = self.build_filters(view, filters=self.get_request_filters(request))
return self.apply_filters(
queryset=queryset,
applicab... | python | def filter_queryset(self, request, queryset, view):
"""
Return the filtered queryset.
"""
applicable_filters, applicable_exclusions = self.build_filters(view, filters=self.get_request_filters(request))
return self.apply_filters(
queryset=queryset,
applicab... | [
"def",
"filter_queryset",
"(",
"self",
",",
"request",
",",
"queryset",
",",
"view",
")",
":",
"applicable_filters",
",",
"applicable_exclusions",
"=",
"self",
".",
"build_filters",
"(",
"view",
",",
"filters",
"=",
"self",
".",
"get_request_filters",
"(",
"re... | Return the filtered queryset. | [
"Return",
"the",
"filtered",
"queryset",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/filters.py#L56-L65 | train |
inonit/drf-haystack | drf_haystack/filters.py | BaseHaystackFilterBackend.get_query_builder | def get_query_builder(self, *args, **kwargs):
"""
Return the query builder class instance that should be used to
build the query which is passed to the search engine backend.
"""
query_builder = self.get_query_builder_class()
return query_builder(*args, **kwargs) | python | def get_query_builder(self, *args, **kwargs):
"""
Return the query builder class instance that should be used to
build the query which is passed to the search engine backend.
"""
query_builder = self.get_query_builder_class()
return query_builder(*args, **kwargs) | [
"def",
"get_query_builder",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"query_builder",
"=",
"self",
".",
"get_query_builder_class",
"(",
")",
"return",
"query_builder",
"(",
"*",
"args",
",",
"**",
"kwargs",
")"
] | Return the query builder class instance that should be used to
build the query which is passed to the search engine backend. | [
"Return",
"the",
"query",
"builder",
"class",
"instance",
"that",
"should",
"be",
"used",
"to",
"build",
"the",
"query",
"which",
"is",
"passed",
"to",
"the",
"search",
"engine",
"backend",
"."
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/filters.py#L67-L73 | train |
inonit/drf-haystack | drf_haystack/filters.py | HaystackFacetFilter.apply_filters | def apply_filters(self, queryset, applicable_filters=None, applicable_exclusions=None):
"""
Apply faceting to the queryset
"""
for field, options in applicable_filters["field_facets"].items():
queryset = queryset.facet(field, **options)
for field, options in applicab... | python | def apply_filters(self, queryset, applicable_filters=None, applicable_exclusions=None):
"""
Apply faceting to the queryset
"""
for field, options in applicable_filters["field_facets"].items():
queryset = queryset.facet(field, **options)
for field, options in applicab... | [
"def",
"apply_filters",
"(",
"self",
",",
"queryset",
",",
"applicable_filters",
"=",
"None",
",",
"applicable_exclusions",
"=",
"None",
")",
":",
"for",
"field",
",",
"options",
"in",
"applicable_filters",
"[",
"\"field_facets\"",
"]",
".",
"items",
"(",
")",... | Apply faceting to the queryset | [
"Apply",
"faceting",
"to",
"the",
"queryset"
] | ceabd0f6318f129758341ab08292a20205d6f4cd | https://github.com/inonit/drf-haystack/blob/ceabd0f6318f129758341ab08292a20205d6f4cd/drf_haystack/filters.py#L202-L215 | train |
maximtrp/scikit-posthocs | scikit_posthocs/_posthocs.py | __convert_to_df | def __convert_to_df(a, val_col=None, group_col=None, val_id=None, group_id=None):
'''Hidden helper method to create a DataFrame with input data for further
processing.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pan... | python | def __convert_to_df(a, val_col=None, group_col=None, val_id=None, group_id=None):
'''Hidden helper method to create a DataFrame with input data for further
processing.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pan... | [
"def",
"__convert_to_df",
"(",
"a",
",",
"val_col",
"=",
"None",
",",
"group_col",
"=",
"None",
",",
"val_id",
"=",
"None",
",",
"group_id",
"=",
"None",
")",
":",
"if",
"not",
"group_col",
":",
"group_col",
"=",
"'groups'",
"if",
"not",
"val_col",
":"... | Hidden helper method to create a DataFrame with input data for further
processing.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pandas DataFrame.
Array must be two-dimensional. Second dimension may vary,
i... | [
"Hidden",
"helper",
"method",
"to",
"create",
"a",
"DataFrame",
"with",
"input",
"data",
"for",
"further",
"processing",
"."
] | 5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d | https://github.com/maximtrp/scikit-posthocs/blob/5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d/scikit_posthocs/_posthocs.py#L11-L106 | train |
maximtrp/scikit-posthocs | scikit_posthocs/_posthocs.py | posthoc_tukey_hsd | def posthoc_tukey_hsd(x, g, alpha=0.05):
'''Pairwise comparisons with TukeyHSD confidence intervals. This is a
convenience function to make statsmodels `pairwise_tukeyhsd` method more
applicable for further use.
Parameters
----------
x : array_like or pandas Series object, 1d
An array,... | python | def posthoc_tukey_hsd(x, g, alpha=0.05):
'''Pairwise comparisons with TukeyHSD confidence intervals. This is a
convenience function to make statsmodels `pairwise_tukeyhsd` method more
applicable for further use.
Parameters
----------
x : array_like or pandas Series object, 1d
An array,... | [
"def",
"posthoc_tukey_hsd",
"(",
"x",
",",
"g",
",",
"alpha",
"=",
"0.05",
")",
":",
"result",
"=",
"pairwise_tukeyhsd",
"(",
"x",
",",
"g",
",",
"alpha",
"=",
"0.05",
")",
"groups",
"=",
"np",
".",
"array",
"(",
"result",
".",
"groupsunique",
",",
... | Pairwise comparisons with TukeyHSD confidence intervals. This is a
convenience function to make statsmodels `pairwise_tukeyhsd` method more
applicable for further use.
Parameters
----------
x : array_like or pandas Series object, 1d
An array, any object exposing the array interface, contain... | [
"Pairwise",
"comparisons",
"with",
"TukeyHSD",
"confidence",
"intervals",
".",
"This",
"is",
"a",
"convenience",
"function",
"to",
"make",
"statsmodels",
"pairwise_tukeyhsd",
"method",
"more",
"applicable",
"for",
"further",
"use",
"."
] | 5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d | https://github.com/maximtrp/scikit-posthocs/blob/5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d/scikit_posthocs/_posthocs.py#L1845-L1897 | train |
maximtrp/scikit-posthocs | scikit_posthocs/_posthocs.py | posthoc_mannwhitney | def posthoc_mannwhitney(a, val_col=None, group_col=None, use_continuity=True, alternative='two-sided', p_adjust=None, sort=True):
'''Pairwise comparisons with Mann-Whitney rank test.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interfa... | python | def posthoc_mannwhitney(a, val_col=None, group_col=None, use_continuity=True, alternative='two-sided', p_adjust=None, sort=True):
'''Pairwise comparisons with Mann-Whitney rank test.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interfa... | [
"def",
"posthoc_mannwhitney",
"(",
"a",
",",
"val_col",
"=",
"None",
",",
"group_col",
"=",
"None",
",",
"use_continuity",
"=",
"True",
",",
"alternative",
"=",
"'two-sided'",
",",
"p_adjust",
"=",
"None",
",",
"sort",
"=",
"True",
")",
":",
"x",
",",
... | Pairwise comparisons with Mann-Whitney rank test.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pandas
DataFrame. Array must be two-dimensional.
val_col : str, optional
Name of a DataFrame column that cont... | [
"Pairwise",
"comparisons",
"with",
"Mann",
"-",
"Whitney",
"rank",
"test",
"."
] | 5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d | https://github.com/maximtrp/scikit-posthocs/blob/5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d/scikit_posthocs/_posthocs.py#L1900-L1991 | train |
maximtrp/scikit-posthocs | scikit_posthocs/_posthocs.py | posthoc_wilcoxon | def posthoc_wilcoxon(a, val_col=None, group_col=None, zero_method='wilcox', correction=False, p_adjust=None, sort=False):
'''Pairwise comparisons with Wilcoxon signed-rank test. It is a non-parametric
version of the paired T-test for use with non-parametric ANOVA.
Parameters
----------
a : array_l... | python | def posthoc_wilcoxon(a, val_col=None, group_col=None, zero_method='wilcox', correction=False, p_adjust=None, sort=False):
'''Pairwise comparisons with Wilcoxon signed-rank test. It is a non-parametric
version of the paired T-test for use with non-parametric ANOVA.
Parameters
----------
a : array_l... | [
"def",
"posthoc_wilcoxon",
"(",
"a",
",",
"val_col",
"=",
"None",
",",
"group_col",
"=",
"None",
",",
"zero_method",
"=",
"'wilcox'",
",",
"correction",
"=",
"False",
",",
"p_adjust",
"=",
"None",
",",
"sort",
"=",
"False",
")",
":",
"x",
",",
"_val_co... | Pairwise comparisons with Wilcoxon signed-rank test. It is a non-parametric
version of the paired T-test for use with non-parametric ANOVA.
Parameters
----------
a : array_like or pandas DataFrame object
An array, any object exposing the array interface or a pandas
DataFrame. Array must... | [
"Pairwise",
"comparisons",
"with",
"Wilcoxon",
"signed",
"-",
"rank",
"test",
".",
"It",
"is",
"a",
"non",
"-",
"parametric",
"version",
"of",
"the",
"paired",
"T",
"-",
"test",
"for",
"use",
"with",
"non",
"-",
"parametric",
"ANOVA",
"."
] | 5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d | https://github.com/maximtrp/scikit-posthocs/blob/5476b09e2a325cd4e31c0b0bc6906ab5cd77fc5d/scikit_posthocs/_posthocs.py#L1994-L2086 | train |
cjrh/aiorun | aiorun.py | shutdown_waits_for | def shutdown_waits_for(coro, loop=None):
"""Prevent coro from being cancelled during the shutdown sequence.
The trick here is that we add this coro to the global
"DO_NOT_CANCEL" collection, and then later during the shutdown
sequence we make sure that the task that wraps this coro will NOT
be cance... | python | def shutdown_waits_for(coro, loop=None):
"""Prevent coro from being cancelled during the shutdown sequence.
The trick here is that we add this coro to the global
"DO_NOT_CANCEL" collection, and then later during the shutdown
sequence we make sure that the task that wraps this coro will NOT
be cance... | [
"def",
"shutdown_waits_for",
"(",
"coro",
",",
"loop",
"=",
"None",
")",
":",
"loop",
"=",
"loop",
"or",
"get_event_loop",
"(",
")",
"fut",
"=",
"loop",
".",
"create_future",
"(",
")",
"async",
"def",
"coro_proxy",
"(",
")",
":",
"try",
":",
"result",
... | Prevent coro from being cancelled during the shutdown sequence.
The trick here is that we add this coro to the global
"DO_NOT_CANCEL" collection, and then later during the shutdown
sequence we make sure that the task that wraps this coro will NOT
be cancelled.
To make this work, we have to create ... | [
"Prevent",
"coro",
"from",
"being",
"cancelled",
"during",
"the",
"shutdown",
"sequence",
"."
] | 23c73318447f578a4a24845c5f43574ac7b414e4 | https://github.com/cjrh/aiorun/blob/23c73318447f578a4a24845c5f43574ac7b414e4/aiorun.py#L43-L117 | train |
cjrh/aiorun | aiorun.py | run | def run(coro: 'Optional[Coroutine]' = None, *,
loop: Optional[AbstractEventLoop] = None,
shutdown_handler: Optional[Callable[[AbstractEventLoop], None]] = None,
executor_workers: int = 10,
executor: Optional[Executor] = None,
use_uvloop: bool = False) -> None:
"""
Start u... | python | def run(coro: 'Optional[Coroutine]' = None, *,
loop: Optional[AbstractEventLoop] = None,
shutdown_handler: Optional[Callable[[AbstractEventLoop], None]] = None,
executor_workers: int = 10,
executor: Optional[Executor] = None,
use_uvloop: bool = False) -> None:
"""
Start u... | [
"def",
"run",
"(",
"coro",
":",
"'Optional[Coroutine]'",
"=",
"None",
",",
"*",
",",
"loop",
":",
"Optional",
"[",
"AbstractEventLoop",
"]",
"=",
"None",
",",
"shutdown_handler",
":",
"Optional",
"[",
"Callable",
"[",
"[",
"AbstractEventLoop",
"]",
",",
"N... | Start up the event loop, and wait for a signal to shut down.
:param coro: Optionally supply a coroutine. The loop will still
run if missing. The loop will continue to run after the supplied
coroutine finishes. The supplied coroutine is typically
a "main" coroutine from which all other work ... | [
"Start",
"up",
"the",
"event",
"loop",
"and",
"wait",
"for",
"a",
"signal",
"to",
"shut",
"down",
"."
] | 23c73318447f578a4a24845c5f43574ac7b414e4 | https://github.com/cjrh/aiorun/blob/23c73318447f578a4a24845c5f43574ac7b414e4/aiorun.py#L120-L255 | train |
emre/storm | storm/kommandr.py | prog.command | def command(self, *args, **kwargs):
"""Convenient decorator simply creates corresponding command"""
if len(args) == 1 and isinstance(args[0], collections.Callable):
return self._generate_command(args[0])
else:
def _command(func):
return self._generate_comm... | python | def command(self, *args, **kwargs):
"""Convenient decorator simply creates corresponding command"""
if len(args) == 1 and isinstance(args[0], collections.Callable):
return self._generate_command(args[0])
else:
def _command(func):
return self._generate_comm... | [
"def",
"command",
"(",
"self",
",",
"*",
"args",
",",
"**",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"isinstance",
"(",
"args",
"[",
"0",
"]",
",",
"collections",
".",
"Callable",
")",
":",
"return",
"self",
".",
"_gen... | Convenient decorator simply creates corresponding command | [
"Convenient",
"decorator",
"simply",
"creates",
"corresponding",
"command"
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/kommandr.py#L96-L103 | train |
emre/storm | storm/kommandr.py | prog._generate_command | def _generate_command(self, func, name=None, **kwargs):
"""Generates a command parser for given func.
:param func: func to generate related command parser
:param type: function
:param name: command name
:param type: str
:param **kwargs: keyword arguments those passed t... | python | def _generate_command(self, func, name=None, **kwargs):
"""Generates a command parser for given func.
:param func: func to generate related command parser
:param type: function
:param name: command name
:param type: str
:param **kwargs: keyword arguments those passed t... | [
"def",
"_generate_command",
"(",
"self",
",",
"func",
",",
"name",
"=",
"None",
",",
"**",
"kwargs",
")",
":",
"func_pointer",
"=",
"name",
"or",
"func",
".",
"__name__",
"storm_config",
"=",
"get_storm_config",
"(",
")",
"aliases",
",",
"additional_kwarg",
... | Generates a command parser for given func.
:param func: func to generate related command parser
:param type: function
:param name: command name
:param type: str
:param **kwargs: keyword arguments those passed through to
:py:class:``argparse.ArgumentPar... | [
"Generates",
"a",
"command",
"parser",
"for",
"given",
"func",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/kommandr.py#L121-L177 | train |
emre/storm | storm/kommandr.py | prog.execute | def execute(self, arg_list):
"""Main function to parse and dispatch commands by given ``arg_list``
:param arg_list: all arguments provided by the command line
:param type: list
"""
arg_map = self.parser.parse_args(arg_list).__dict__
command = arg_map.pop(self._COMMAND_F... | python | def execute(self, arg_list):
"""Main function to parse and dispatch commands by given ``arg_list``
:param arg_list: all arguments provided by the command line
:param type: list
"""
arg_map = self.parser.parse_args(arg_list).__dict__
command = arg_map.pop(self._COMMAND_F... | [
"def",
"execute",
"(",
"self",
",",
"arg_list",
")",
":",
"arg_map",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"arg_list",
")",
".",
"__dict__",
"command",
"=",
"arg_map",
".",
"pop",
"(",
"self",
".",
"_COMMAND_FLAG",
")",
"return",
"command",... | Main function to parse and dispatch commands by given ``arg_list``
:param arg_list: all arguments provided by the command line
:param type: list | [
"Main",
"function",
"to",
"parse",
"and",
"dispatch",
"commands",
"by",
"given",
"arg_list"
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/kommandr.py#L179-L188 | train |
emre/storm | storm/__main__.py | add | def add(name, connection_uri, id_file="", o=[], config=None):
"""
Adds a new entry to sshconfig.
"""
storm_ = get_storm_instance(config)
try:
# validate name
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
user, host, port = parse... | python | def add(name, connection_uri, id_file="", o=[], config=None):
"""
Adds a new entry to sshconfig.
"""
storm_ = get_storm_instance(config)
try:
# validate name
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
user, host, port = parse... | [
"def",
"add",
"(",
"name",
",",
"connection_uri",
",",
"id_file",
"=",
"\"\"",
",",
"o",
"=",
"[",
"]",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"if",
"'@'",
"in",
"name",
":",
"rais... | Adds a new entry to sshconfig. | [
"Adds",
"a",
"new",
"entry",
"to",
"sshconfig",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L34-L63 | train |
emre/storm | storm/__main__.py | clone | def clone(name, clone_name, config=None):
"""
Clone an entry to the sshconfig.
"""
storm_ = get_storm_instance(config)
try:
# validate name
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
storm_.clone_entry(name, clone_name)
... | python | def clone(name, clone_name, config=None):
"""
Clone an entry to the sshconfig.
"""
storm_ = get_storm_instance(config)
try:
# validate name
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
storm_.clone_entry(name, clone_name)
... | [
"def",
"clone",
"(",
"name",
",",
"clone_name",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"if",
"'@'",
"in",
"name",
":",
"raise",
"ValueError",
"(",
"'invalid value: \"@\" cannot be used in name... | Clone an entry to the sshconfig. | [
"Clone",
"an",
"entry",
"to",
"the",
"sshconfig",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L67-L90 | train |
emre/storm | storm/__main__.py | move | def move(name, entry_name, config=None):
"""
Move an entry to the sshconfig.
"""
storm_ = get_storm_instance(config)
try:
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
storm_.clone_entry(name, entry_name, keep_original=False)
p... | python | def move(name, entry_name, config=None):
"""
Move an entry to the sshconfig.
"""
storm_ = get_storm_instance(config)
try:
if '@' in name:
raise ValueError('invalid value: "@" cannot be used in name.')
storm_.clone_entry(name, entry_name, keep_original=False)
p... | [
"def",
"move",
"(",
"name",
",",
"entry_name",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"if",
"'@'",
"in",
"name",
":",
"raise",
"ValueError",
"(",
"'invalid value: \"@\" cannot be used in name.... | Move an entry to the sshconfig. | [
"Move",
"an",
"entry",
"to",
"the",
"sshconfig",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L93-L117 | train |
emre/storm | storm/__main__.py | edit | def edit(name, connection_uri, id_file="", o=[], config=None):
"""
Edits the related entry in ssh config.
"""
storm_ = get_storm_instance(config)
try:
if ',' in name:
name = " ".join(name.split(","))
user, host, port = parse(
connection_uri,
user... | python | def edit(name, connection_uri, id_file="", o=[], config=None):
"""
Edits the related entry in ssh config.
"""
storm_ = get_storm_instance(config)
try:
if ',' in name:
name = " ".join(name.split(","))
user, host, port = parse(
connection_uri,
user... | [
"def",
"edit",
"(",
"name",
",",
"connection_uri",
",",
"id_file",
"=",
"\"\"",
",",
"o",
"=",
"[",
"]",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"if",
"','",
"in",
"name",
":",
"nam... | Edits the related entry in ssh config. | [
"Edits",
"the",
"related",
"entry",
"in",
"ssh",
"config",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L120-L143 | train |
emre/storm | storm/__main__.py | update | def update(name, connection_uri="", id_file="", o=[], config=None):
"""
Enhanced version of the edit command featuring multiple
edits using regular expressions to match entries
"""
storm_ = get_storm_instance(config)
settings = {}
if id_file != "":
settings['identityfile'] = id_fil... | python | def update(name, connection_uri="", id_file="", o=[], config=None):
"""
Enhanced version of the edit command featuring multiple
edits using regular expressions to match entries
"""
storm_ = get_storm_instance(config)
settings = {}
if id_file != "":
settings['identityfile'] = id_fil... | [
"def",
"update",
"(",
"name",
",",
"connection_uri",
"=",
"\"\"",
",",
"id_file",
"=",
"\"\"",
",",
"o",
"=",
"[",
"]",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"settings",
"=",
"{",
"}",
"if",
... | Enhanced version of the edit command featuring multiple
edits using regular expressions to match entries | [
"Enhanced",
"version",
"of",
"the",
"edit",
"command",
"featuring",
"multiple",
"edits",
"using",
"regular",
"expressions",
"to",
"match",
"entries"
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L146-L169 | train |
emre/storm | storm/__main__.py | delete | def delete(name, config=None):
"""
Deletes a single host.
"""
storm_ = get_storm_instance(config)
try:
storm_.delete_entry(name)
print(
get_formatted_message(
'hostname "{0}" deleted successfully.'.format(name),
'success')
)
except... | python | def delete(name, config=None):
"""
Deletes a single host.
"""
storm_ = get_storm_instance(config)
try:
storm_.delete_entry(name)
print(
get_formatted_message(
'hostname "{0}" deleted successfully.'.format(name),
'success')
)
except... | [
"def",
"delete",
"(",
"name",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"storm_",
".",
"delete_entry",
"(",
"name",
")",
"print",
"(",
"get_formatted_message",
"(",
"'hostname \"{0}\" deleted suc... | Deletes a single host. | [
"Deletes",
"a",
"single",
"host",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L172-L187 | train |
emre/storm | storm/__main__.py | list | def list(config=None):
"""
Lists all hosts from ssh config.
"""
storm_ = get_storm_instance(config)
try:
result = colored('Listing entries:', 'white', attrs=["bold", ]) + "\n\n"
result_stack = ""
for host in storm_.list_entries(True):
if host.get("type") == 'ent... | python | def list(config=None):
"""
Lists all hosts from ssh config.
"""
storm_ = get_storm_instance(config)
try:
result = colored('Listing entries:', 'white', attrs=["bold", ]) + "\n\n"
result_stack = ""
for host in storm_.list_entries(True):
if host.get("type") == 'ent... | [
"def",
"list",
"(",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"result",
"=",
"colored",
"(",
"'Listing entries:'",
",",
"'white'",
",",
"attrs",
"=",
"[",
"\"bold\"",
",",
"]",
")",
"+",
"\"\\... | Lists all hosts from ssh config. | [
"Lists",
"all",
"hosts",
"from",
"ssh",
"config",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L190-L258 | train |
emre/storm | storm/__main__.py | search | def search(search_text, config=None):
"""
Searches entries by given search text.
"""
storm_ = get_storm_instance(config)
try:
results = storm_.search_host(search_text)
if len(results) == 0:
print ('no results found.')
if len(results) > 0:
message = '... | python | def search(search_text, config=None):
"""
Searches entries by given search text.
"""
storm_ = get_storm_instance(config)
try:
results = storm_.search_host(search_text)
if len(results) == 0:
print ('no results found.')
if len(results) > 0:
message = '... | [
"def",
"search",
"(",
"search_text",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"results",
"=",
"storm_",
".",
"search_host",
"(",
"search_text",
")",
"if",
"len",
"(",
"results",
")",
"==",... | Searches entries by given search text. | [
"Searches",
"entries",
"by",
"given",
"search",
"text",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L261-L278 | train |
emre/storm | storm/__main__.py | delete_all | def delete_all(config=None):
"""
Deletes all hosts from ssh config.
"""
storm_ = get_storm_instance(config)
try:
storm_.delete_all_entries()
print(get_formatted_message('all entries deleted.', 'success'))
except Exception as error:
print(get_formatted_message(str(error),... | python | def delete_all(config=None):
"""
Deletes all hosts from ssh config.
"""
storm_ = get_storm_instance(config)
try:
storm_.delete_all_entries()
print(get_formatted_message('all entries deleted.', 'success'))
except Exception as error:
print(get_formatted_message(str(error),... | [
"def",
"delete_all",
"(",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"storm_",
".",
"delete_all_entries",
"(",
")",
"print",
"(",
"get_formatted_message",
"(",
"'all entries deleted.'",
",",
"'success'",... | Deletes all hosts from ssh config. | [
"Deletes",
"all",
"hosts",
"from",
"ssh",
"config",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L281-L292 | train |
emre/storm | storm/__main__.py | backup | def backup(target_file, config=None):
"""
Backups the main ssh configuration into target file.
"""
storm_ = get_storm_instance(config)
try:
storm_.backup(target_file)
except Exception as error:
print(get_formatted_message(str(error), 'error'), file=sys.stderr)
sys.exit(1) | python | def backup(target_file, config=None):
"""
Backups the main ssh configuration into target file.
"""
storm_ = get_storm_instance(config)
try:
storm_.backup(target_file)
except Exception as error:
print(get_formatted_message(str(error), 'error'), file=sys.stderr)
sys.exit(1) | [
"def",
"backup",
"(",
"target_file",
",",
"config",
"=",
"None",
")",
":",
"storm_",
"=",
"get_storm_instance",
"(",
"config",
")",
"try",
":",
"storm_",
".",
"backup",
"(",
"target_file",
")",
"except",
"Exception",
"as",
"error",
":",
"print",
"(",
"ge... | Backups the main ssh configuration into target file. | [
"Backups",
"the",
"main",
"ssh",
"configuration",
"into",
"target",
"file",
"."
] | c752defc1b718cfffbf0e0e15532fa1d7840bf6d | https://github.com/emre/storm/blob/c752defc1b718cfffbf0e0e15532fa1d7840bf6d/storm/__main__.py#L295-L304 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.