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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | encode_caveat | def encode_caveat(condition, root_key, third_party_info, key, ns):
'''Encrypt a third-party caveat.
The third_party_info key holds information about the
third party we're encrypting the caveat for; the key is the
public/private key pair of the party that's adding the caveat.
The caveat will be encoded according to the version information
found in third_party_info.
@param condition string
@param root_key bytes
@param third_party_info object
@param key nacl key
@param ns not used yet
@return bytes
'''
if third_party_info.version == VERSION_1:
return _encode_caveat_v1(condition, root_key,
third_party_info.public_key, key)
if (third_party_info.version == VERSION_2 or
third_party_info.version == VERSION_3):
return _encode_caveat_v2_v3(third_party_info.version, condition,
root_key, third_party_info.public_key,
key, ns)
raise NotImplementedError('only bakery v1, v2, v3 supported') | python | def encode_caveat(condition, root_key, third_party_info, key, ns):
'''Encrypt a third-party caveat.
The third_party_info key holds information about the
third party we're encrypting the caveat for; the key is the
public/private key pair of the party that's adding the caveat.
The caveat will be encoded according to the version information
found in third_party_info.
@param condition string
@param root_key bytes
@param third_party_info object
@param key nacl key
@param ns not used yet
@return bytes
'''
if third_party_info.version == VERSION_1:
return _encode_caveat_v1(condition, root_key,
third_party_info.public_key, key)
if (third_party_info.version == VERSION_2 or
third_party_info.version == VERSION_3):
return _encode_caveat_v2_v3(third_party_info.version, condition,
root_key, third_party_info.public_key,
key, ns)
raise NotImplementedError('only bakery v1, v2, v3 supported') | [
"def",
"encode_caveat",
"(",
"condition",
",",
"root_key",
",",
"third_party_info",
",",
"key",
",",
"ns",
")",
":",
"if",
"third_party_info",
".",
"version",
"==",
"VERSION_1",
":",
"return",
"_encode_caveat_v1",
"(",
"condition",
",",
"root_key",
",",
"third_party_info",
".",
"public_key",
",",
"key",
")",
"if",
"(",
"third_party_info",
".",
"version",
"==",
"VERSION_2",
"or",
"third_party_info",
".",
"version",
"==",
"VERSION_3",
")",
":",
"return",
"_encode_caveat_v2_v3",
"(",
"third_party_info",
".",
"version",
",",
"condition",
",",
"root_key",
",",
"third_party_info",
".",
"public_key",
",",
"key",
",",
"ns",
")",
"raise",
"NotImplementedError",
"(",
"'only bakery v1, v2, v3 supported'",
")"
] | Encrypt a third-party caveat.
The third_party_info key holds information about the
third party we're encrypting the caveat for; the key is the
public/private key pair of the party that's adding the caveat.
The caveat will be encoded according to the version information
found in third_party_info.
@param condition string
@param root_key bytes
@param third_party_info object
@param key nacl key
@param ns not used yet
@return bytes | [
"Encrypt",
"a",
"third",
"-",
"party",
"caveat",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L21-L46 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | _encode_caveat_v1 | def _encode_caveat_v1(condition, root_key, third_party_pub_key, key):
'''Create a JSON-encoded third-party caveat.
The third_party_pub_key key represents the PublicKey of the third party
we're encrypting the caveat for; the key is the public/private key pair of
the party that's adding the caveat.
@param condition string
@param root_key bytes
@param third_party_pub_key (PublicKey)
@param key (PrivateKey)
@return a base64 encoded bytes
'''
plain_data = json.dumps({
'RootKey': base64.b64encode(root_key).decode('ascii'),
'Condition': condition
})
box = nacl.public.Box(key.key, third_party_pub_key.key)
encrypted = box.encrypt(six.b(plain_data))
nonce = encrypted[0:nacl.public.Box.NONCE_SIZE]
encrypted = encrypted[nacl.public.Box.NONCE_SIZE:]
return base64.b64encode(six.b(json.dumps({
'ThirdPartyPublicKey': str(third_party_pub_key),
'FirstPartyPublicKey': str(key.public_key),
'Nonce': base64.b64encode(nonce).decode('ascii'),
'Id': base64.b64encode(encrypted).decode('ascii')
}))) | python | def _encode_caveat_v1(condition, root_key, third_party_pub_key, key):
'''Create a JSON-encoded third-party caveat.
The third_party_pub_key key represents the PublicKey of the third party
we're encrypting the caveat for; the key is the public/private key pair of
the party that's adding the caveat.
@param condition string
@param root_key bytes
@param third_party_pub_key (PublicKey)
@param key (PrivateKey)
@return a base64 encoded bytes
'''
plain_data = json.dumps({
'RootKey': base64.b64encode(root_key).decode('ascii'),
'Condition': condition
})
box = nacl.public.Box(key.key, third_party_pub_key.key)
encrypted = box.encrypt(six.b(plain_data))
nonce = encrypted[0:nacl.public.Box.NONCE_SIZE]
encrypted = encrypted[nacl.public.Box.NONCE_SIZE:]
return base64.b64encode(six.b(json.dumps({
'ThirdPartyPublicKey': str(third_party_pub_key),
'FirstPartyPublicKey': str(key.public_key),
'Nonce': base64.b64encode(nonce).decode('ascii'),
'Id': base64.b64encode(encrypted).decode('ascii')
}))) | [
"def",
"_encode_caveat_v1",
"(",
"condition",
",",
"root_key",
",",
"third_party_pub_key",
",",
"key",
")",
":",
"plain_data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'RootKey'",
":",
"base64",
".",
"b64encode",
"(",
"root_key",
")",
".",
"decode",
"(",
"'ascii'",
")",
",",
"'Condition'",
":",
"condition",
"}",
")",
"box",
"=",
"nacl",
".",
"public",
".",
"Box",
"(",
"key",
".",
"key",
",",
"third_party_pub_key",
".",
"key",
")",
"encrypted",
"=",
"box",
".",
"encrypt",
"(",
"six",
".",
"b",
"(",
"plain_data",
")",
")",
"nonce",
"=",
"encrypted",
"[",
"0",
":",
"nacl",
".",
"public",
".",
"Box",
".",
"NONCE_SIZE",
"]",
"encrypted",
"=",
"encrypted",
"[",
"nacl",
".",
"public",
".",
"Box",
".",
"NONCE_SIZE",
":",
"]",
"return",
"base64",
".",
"b64encode",
"(",
"six",
".",
"b",
"(",
"json",
".",
"dumps",
"(",
"{",
"'ThirdPartyPublicKey'",
":",
"str",
"(",
"third_party_pub_key",
")",
",",
"'FirstPartyPublicKey'",
":",
"str",
"(",
"key",
".",
"public_key",
")",
",",
"'Nonce'",
":",
"base64",
".",
"b64encode",
"(",
"nonce",
")",
".",
"decode",
"(",
"'ascii'",
")",
",",
"'Id'",
":",
"base64",
".",
"b64encode",
"(",
"encrypted",
")",
".",
"decode",
"(",
"'ascii'",
")",
"}",
")",
")",
")"
] | Create a JSON-encoded third-party caveat.
The third_party_pub_key key represents the PublicKey of the third party
we're encrypting the caveat for; the key is the public/private key pair of
the party that's adding the caveat.
@param condition string
@param root_key bytes
@param third_party_pub_key (PublicKey)
@param key (PrivateKey)
@return a base64 encoded bytes | [
"Create",
"a",
"JSON",
"-",
"encoded",
"third",
"-",
"party",
"caveat",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L49-L76 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | _encode_caveat_v2_v3 | def _encode_caveat_v2_v3(version, condition, root_key, third_party_pub_key,
key, ns):
'''Create a version 2 or version 3 third-party caveat.
The format has the following packed binary fields (note
that all fields up to and including the nonce are the same
as the v2 format):
version 2 or 3 [1 byte]
first 4 bytes of third-party Curve25519 public key [4 bytes]
first-party Curve25519 public key [32 bytes]
nonce [24 bytes]
encrypted secret part [rest of message]
The encrypted part encrypts the following fields
with box.Seal:
version 2 or 3 [1 byte]
length of root key [n: uvarint]
root key [n bytes]
length of encoded namespace [n: uvarint] (Version 3 only)
encoded namespace [n bytes] (Version 3 only)
condition [rest of encrypted part]
'''
ns_data = bytearray()
if version >= VERSION_3:
ns_data = ns.serialize_text()
data = bytearray()
data.append(version)
data.extend(third_party_pub_key.serialize(raw=True)[:_PUBLIC_KEY_PREFIX_LEN])
data.extend(key.public_key.serialize(raw=True)[:])
secret = _encode_secret_part_v2_v3(version, condition, root_key, ns_data)
box = nacl.public.Box(key.key, third_party_pub_key.key)
encrypted = box.encrypt(secret)
nonce = encrypted[0:nacl.public.Box.NONCE_SIZE]
encrypted = encrypted[nacl.public.Box.NONCE_SIZE:]
data.extend(nonce[:])
data.extend(encrypted)
return bytes(data) | python | def _encode_caveat_v2_v3(version, condition, root_key, third_party_pub_key,
key, ns):
'''Create a version 2 or version 3 third-party caveat.
The format has the following packed binary fields (note
that all fields up to and including the nonce are the same
as the v2 format):
version 2 or 3 [1 byte]
first 4 bytes of third-party Curve25519 public key [4 bytes]
first-party Curve25519 public key [32 bytes]
nonce [24 bytes]
encrypted secret part [rest of message]
The encrypted part encrypts the following fields
with box.Seal:
version 2 or 3 [1 byte]
length of root key [n: uvarint]
root key [n bytes]
length of encoded namespace [n: uvarint] (Version 3 only)
encoded namespace [n bytes] (Version 3 only)
condition [rest of encrypted part]
'''
ns_data = bytearray()
if version >= VERSION_3:
ns_data = ns.serialize_text()
data = bytearray()
data.append(version)
data.extend(third_party_pub_key.serialize(raw=True)[:_PUBLIC_KEY_PREFIX_LEN])
data.extend(key.public_key.serialize(raw=True)[:])
secret = _encode_secret_part_v2_v3(version, condition, root_key, ns_data)
box = nacl.public.Box(key.key, third_party_pub_key.key)
encrypted = box.encrypt(secret)
nonce = encrypted[0:nacl.public.Box.NONCE_SIZE]
encrypted = encrypted[nacl.public.Box.NONCE_SIZE:]
data.extend(nonce[:])
data.extend(encrypted)
return bytes(data) | [
"def",
"_encode_caveat_v2_v3",
"(",
"version",
",",
"condition",
",",
"root_key",
",",
"third_party_pub_key",
",",
"key",
",",
"ns",
")",
":",
"ns_data",
"=",
"bytearray",
"(",
")",
"if",
"version",
">=",
"VERSION_3",
":",
"ns_data",
"=",
"ns",
".",
"serialize_text",
"(",
")",
"data",
"=",
"bytearray",
"(",
")",
"data",
".",
"append",
"(",
"version",
")",
"data",
".",
"extend",
"(",
"third_party_pub_key",
".",
"serialize",
"(",
"raw",
"=",
"True",
")",
"[",
":",
"_PUBLIC_KEY_PREFIX_LEN",
"]",
")",
"data",
".",
"extend",
"(",
"key",
".",
"public_key",
".",
"serialize",
"(",
"raw",
"=",
"True",
")",
"[",
":",
"]",
")",
"secret",
"=",
"_encode_secret_part_v2_v3",
"(",
"version",
",",
"condition",
",",
"root_key",
",",
"ns_data",
")",
"box",
"=",
"nacl",
".",
"public",
".",
"Box",
"(",
"key",
".",
"key",
",",
"third_party_pub_key",
".",
"key",
")",
"encrypted",
"=",
"box",
".",
"encrypt",
"(",
"secret",
")",
"nonce",
"=",
"encrypted",
"[",
"0",
":",
"nacl",
".",
"public",
".",
"Box",
".",
"NONCE_SIZE",
"]",
"encrypted",
"=",
"encrypted",
"[",
"nacl",
".",
"public",
".",
"Box",
".",
"NONCE_SIZE",
":",
"]",
"data",
".",
"extend",
"(",
"nonce",
"[",
":",
"]",
")",
"data",
".",
"extend",
"(",
"encrypted",
")",
"return",
"bytes",
"(",
"data",
")"
] | Create a version 2 or version 3 third-party caveat.
The format has the following packed binary fields (note
that all fields up to and including the nonce are the same
as the v2 format):
version 2 or 3 [1 byte]
first 4 bytes of third-party Curve25519 public key [4 bytes]
first-party Curve25519 public key [32 bytes]
nonce [24 bytes]
encrypted secret part [rest of message]
The encrypted part encrypts the following fields
with box.Seal:
version 2 or 3 [1 byte]
length of root key [n: uvarint]
root key [n bytes]
length of encoded namespace [n: uvarint] (Version 3 only)
encoded namespace [n bytes] (Version 3 only)
condition [rest of encrypted part] | [
"Create",
"a",
"version",
"2",
"or",
"version",
"3",
"third",
"-",
"party",
"caveat",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L79-L117 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | _encode_secret_part_v2_v3 | def _encode_secret_part_v2_v3(version, condition, root_key, ns):
'''Creates a version 2 or version 3 secret part of the third party
caveat. The returned data is not encrypted.
The format has the following packed binary fields:
version 2 or 3 [1 byte]
root key length [n: uvarint]
root key [n bytes]
namespace length [n: uvarint] (v3 only)
namespace [n bytes] (v3 only)
predicate [rest of message]
'''
data = bytearray()
data.append(version)
encode_uvarint(len(root_key), data)
data.extend(root_key)
if version >= VERSION_3:
encode_uvarint(len(ns), data)
data.extend(ns)
data.extend(condition.encode('utf-8'))
return bytes(data) | python | def _encode_secret_part_v2_v3(version, condition, root_key, ns):
'''Creates a version 2 or version 3 secret part of the third party
caveat. The returned data is not encrypted.
The format has the following packed binary fields:
version 2 or 3 [1 byte]
root key length [n: uvarint]
root key [n bytes]
namespace length [n: uvarint] (v3 only)
namespace [n bytes] (v3 only)
predicate [rest of message]
'''
data = bytearray()
data.append(version)
encode_uvarint(len(root_key), data)
data.extend(root_key)
if version >= VERSION_3:
encode_uvarint(len(ns), data)
data.extend(ns)
data.extend(condition.encode('utf-8'))
return bytes(data) | [
"def",
"_encode_secret_part_v2_v3",
"(",
"version",
",",
"condition",
",",
"root_key",
",",
"ns",
")",
":",
"data",
"=",
"bytearray",
"(",
")",
"data",
".",
"append",
"(",
"version",
")",
"encode_uvarint",
"(",
"len",
"(",
"root_key",
")",
",",
"data",
")",
"data",
".",
"extend",
"(",
"root_key",
")",
"if",
"version",
">=",
"VERSION_3",
":",
"encode_uvarint",
"(",
"len",
"(",
"ns",
")",
",",
"data",
")",
"data",
".",
"extend",
"(",
"ns",
")",
"data",
".",
"extend",
"(",
"condition",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"return",
"bytes",
"(",
"data",
")"
] | Creates a version 2 or version 3 secret part of the third party
caveat. The returned data is not encrypted.
The format has the following packed binary fields:
version 2 or 3 [1 byte]
root key length [n: uvarint]
root key [n bytes]
namespace length [n: uvarint] (v3 only)
namespace [n bytes] (v3 only)
predicate [rest of message] | [
"Creates",
"a",
"version",
"2",
"or",
"version",
"3",
"secret",
"part",
"of",
"the",
"third",
"party",
"caveat",
".",
"The",
"returned",
"data",
"is",
"not",
"encrypted",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L120-L140 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | decode_caveat | def decode_caveat(key, caveat):
'''Decode caveat by decrypting the encrypted part using key.
@param key the nacl private key to decode.
@param caveat bytes.
@return ThirdPartyCaveatInfo
'''
if len(caveat) == 0:
raise VerificationError('empty third party caveat')
first = caveat[:1]
if first == b'e':
# 'e' will be the first byte if the caveatid is a base64
# encoded JSON object.
return _decode_caveat_v1(key, caveat)
first_as_int = six.byte2int(first)
if (first_as_int == VERSION_2 or
first_as_int == VERSION_3):
if (len(caveat) < _VERSION3_CAVEAT_MIN_LEN
and first_as_int == VERSION_3):
# If it has the version 3 caveat tag and it's too short, it's
# almost certainly an id, not an encrypted payload.
raise VerificationError(
'caveat id payload not provided for caveat id {}'.format(
caveat))
return _decode_caveat_v2_v3(first_as_int, key, caveat)
raise VerificationError('unknown version for caveat') | python | def decode_caveat(key, caveat):
'''Decode caveat by decrypting the encrypted part using key.
@param key the nacl private key to decode.
@param caveat bytes.
@return ThirdPartyCaveatInfo
'''
if len(caveat) == 0:
raise VerificationError('empty third party caveat')
first = caveat[:1]
if first == b'e':
# 'e' will be the first byte if the caveatid is a base64
# encoded JSON object.
return _decode_caveat_v1(key, caveat)
first_as_int = six.byte2int(first)
if (first_as_int == VERSION_2 or
first_as_int == VERSION_3):
if (len(caveat) < _VERSION3_CAVEAT_MIN_LEN
and first_as_int == VERSION_3):
# If it has the version 3 caveat tag and it's too short, it's
# almost certainly an id, not an encrypted payload.
raise VerificationError(
'caveat id payload not provided for caveat id {}'.format(
caveat))
return _decode_caveat_v2_v3(first_as_int, key, caveat)
raise VerificationError('unknown version for caveat') | [
"def",
"decode_caveat",
"(",
"key",
",",
"caveat",
")",
":",
"if",
"len",
"(",
"caveat",
")",
"==",
"0",
":",
"raise",
"VerificationError",
"(",
"'empty third party caveat'",
")",
"first",
"=",
"caveat",
"[",
":",
"1",
"]",
"if",
"first",
"==",
"b'e'",
":",
"# 'e' will be the first byte if the caveatid is a base64",
"# encoded JSON object.",
"return",
"_decode_caveat_v1",
"(",
"key",
",",
"caveat",
")",
"first_as_int",
"=",
"six",
".",
"byte2int",
"(",
"first",
")",
"if",
"(",
"first_as_int",
"==",
"VERSION_2",
"or",
"first_as_int",
"==",
"VERSION_3",
")",
":",
"if",
"(",
"len",
"(",
"caveat",
")",
"<",
"_VERSION3_CAVEAT_MIN_LEN",
"and",
"first_as_int",
"==",
"VERSION_3",
")",
":",
"# If it has the version 3 caveat tag and it's too short, it's",
"# almost certainly an id, not an encrypted payload.",
"raise",
"VerificationError",
"(",
"'caveat id payload not provided for caveat id {}'",
".",
"format",
"(",
"caveat",
")",
")",
"return",
"_decode_caveat_v2_v3",
"(",
"first_as_int",
",",
"key",
",",
"caveat",
")",
"raise",
"VerificationError",
"(",
"'unknown version for caveat'",
")"
] | Decode caveat by decrypting the encrypted part using key.
@param key the nacl private key to decode.
@param caveat bytes.
@return ThirdPartyCaveatInfo | [
"Decode",
"caveat",
"by",
"decrypting",
"the",
"encrypted",
"part",
"using",
"key",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L143-L169 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | _decode_caveat_v1 | def _decode_caveat_v1(key, caveat):
'''Decode a base64 encoded JSON id.
@param key the nacl private key to decode.
@param caveat a base64 encoded JSON string.
'''
data = base64.b64decode(caveat).decode('utf-8')
wrapper = json.loads(data)
tp_public_key = nacl.public.PublicKey(
base64.b64decode(wrapper['ThirdPartyPublicKey']))
if key.public_key.key != tp_public_key:
raise Exception('public key mismatch') # TODO
if wrapper.get('FirstPartyPublicKey', None) is None:
raise Exception('target service public key not specified')
# The encrypted string is base64 encoded in the JSON representation.
secret = base64.b64decode(wrapper.get('Id'))
nonce = base64.b64decode(wrapper.get('Nonce'))
fp_public_key = nacl.public.PublicKey(base64.b64decode(
wrapper.get('FirstPartyPublicKey')))
box = nacl.public.Box(key.key, fp_public_key)
c = box.decrypt(secret, nonce)
record = json.loads(c.decode('utf-8'))
fp_key = nacl.public.PublicKey(
base64.b64decode(wrapper.get('FirstPartyPublicKey')))
return ThirdPartyCaveatInfo(
condition=record.get('Condition'),
first_party_public_key=PublicKey(fp_key),
third_party_key_pair=key,
root_key=base64.b64decode(record.get('RootKey')),
caveat=caveat,
id=None,
version=VERSION_1,
namespace=legacy_namespace()
) | python | def _decode_caveat_v1(key, caveat):
'''Decode a base64 encoded JSON id.
@param key the nacl private key to decode.
@param caveat a base64 encoded JSON string.
'''
data = base64.b64decode(caveat).decode('utf-8')
wrapper = json.loads(data)
tp_public_key = nacl.public.PublicKey(
base64.b64decode(wrapper['ThirdPartyPublicKey']))
if key.public_key.key != tp_public_key:
raise Exception('public key mismatch') # TODO
if wrapper.get('FirstPartyPublicKey', None) is None:
raise Exception('target service public key not specified')
# The encrypted string is base64 encoded in the JSON representation.
secret = base64.b64decode(wrapper.get('Id'))
nonce = base64.b64decode(wrapper.get('Nonce'))
fp_public_key = nacl.public.PublicKey(base64.b64decode(
wrapper.get('FirstPartyPublicKey')))
box = nacl.public.Box(key.key, fp_public_key)
c = box.decrypt(secret, nonce)
record = json.loads(c.decode('utf-8'))
fp_key = nacl.public.PublicKey(
base64.b64decode(wrapper.get('FirstPartyPublicKey')))
return ThirdPartyCaveatInfo(
condition=record.get('Condition'),
first_party_public_key=PublicKey(fp_key),
third_party_key_pair=key,
root_key=base64.b64decode(record.get('RootKey')),
caveat=caveat,
id=None,
version=VERSION_1,
namespace=legacy_namespace()
) | [
"def",
"_decode_caveat_v1",
"(",
"key",
",",
"caveat",
")",
":",
"data",
"=",
"base64",
".",
"b64decode",
"(",
"caveat",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"wrapper",
"=",
"json",
".",
"loads",
"(",
"data",
")",
"tp_public_key",
"=",
"nacl",
".",
"public",
".",
"PublicKey",
"(",
"base64",
".",
"b64decode",
"(",
"wrapper",
"[",
"'ThirdPartyPublicKey'",
"]",
")",
")",
"if",
"key",
".",
"public_key",
".",
"key",
"!=",
"tp_public_key",
":",
"raise",
"Exception",
"(",
"'public key mismatch'",
")",
"# TODO",
"if",
"wrapper",
".",
"get",
"(",
"'FirstPartyPublicKey'",
",",
"None",
")",
"is",
"None",
":",
"raise",
"Exception",
"(",
"'target service public key not specified'",
")",
"# The encrypted string is base64 encoded in the JSON representation.",
"secret",
"=",
"base64",
".",
"b64decode",
"(",
"wrapper",
".",
"get",
"(",
"'Id'",
")",
")",
"nonce",
"=",
"base64",
".",
"b64decode",
"(",
"wrapper",
".",
"get",
"(",
"'Nonce'",
")",
")",
"fp_public_key",
"=",
"nacl",
".",
"public",
".",
"PublicKey",
"(",
"base64",
".",
"b64decode",
"(",
"wrapper",
".",
"get",
"(",
"'FirstPartyPublicKey'",
")",
")",
")",
"box",
"=",
"nacl",
".",
"public",
".",
"Box",
"(",
"key",
".",
"key",
",",
"fp_public_key",
")",
"c",
"=",
"box",
".",
"decrypt",
"(",
"secret",
",",
"nonce",
")",
"record",
"=",
"json",
".",
"loads",
"(",
"c",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"fp_key",
"=",
"nacl",
".",
"public",
".",
"PublicKey",
"(",
"base64",
".",
"b64decode",
"(",
"wrapper",
".",
"get",
"(",
"'FirstPartyPublicKey'",
")",
")",
")",
"return",
"ThirdPartyCaveatInfo",
"(",
"condition",
"=",
"record",
".",
"get",
"(",
"'Condition'",
")",
",",
"first_party_public_key",
"=",
"PublicKey",
"(",
"fp_key",
")",
",",
"third_party_key_pair",
"=",
"key",
",",
"root_key",
"=",
"base64",
".",
"b64decode",
"(",
"record",
".",
"get",
"(",
"'RootKey'",
")",
")",
",",
"caveat",
"=",
"caveat",
",",
"id",
"=",
"None",
",",
"version",
"=",
"VERSION_1",
",",
"namespace",
"=",
"legacy_namespace",
"(",
")",
")"
] | Decode a base64 encoded JSON id.
@param key the nacl private key to decode.
@param caveat a base64 encoded JSON string. | [
"Decode",
"a",
"base64",
"encoded",
"JSON",
"id",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L172-L210 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | _decode_caveat_v2_v3 | def _decode_caveat_v2_v3(version, key, caveat):
'''Decodes a version 2 or version 3 caveat.
'''
if (len(caveat) < 1 + _PUBLIC_KEY_PREFIX_LEN +
_KEY_LEN + nacl.public.Box.NONCE_SIZE + 16):
raise VerificationError('caveat id too short')
original_caveat = caveat
caveat = caveat[1:] # skip version (already checked)
pk_prefix = caveat[:_PUBLIC_KEY_PREFIX_LEN]
caveat = caveat[_PUBLIC_KEY_PREFIX_LEN:]
if key.public_key.serialize(raw=True)[:_PUBLIC_KEY_PREFIX_LEN] != pk_prefix:
raise VerificationError('public key mismatch')
first_party_pub = caveat[:_KEY_LEN]
caveat = caveat[_KEY_LEN:]
nonce = caveat[:nacl.public.Box.NONCE_SIZE]
caveat = caveat[nacl.public.Box.NONCE_SIZE:]
fp_public_key = nacl.public.PublicKey(first_party_pub)
box = nacl.public.Box(key.key, fp_public_key)
data = box.decrypt(caveat, nonce)
root_key, condition, ns = _decode_secret_part_v2_v3(version, data)
return ThirdPartyCaveatInfo(
condition=condition.decode('utf-8'),
first_party_public_key=PublicKey(fp_public_key),
third_party_key_pair=key,
root_key=root_key,
caveat=original_caveat,
version=version,
id=None,
namespace=ns
) | python | def _decode_caveat_v2_v3(version, key, caveat):
'''Decodes a version 2 or version 3 caveat.
'''
if (len(caveat) < 1 + _PUBLIC_KEY_PREFIX_LEN +
_KEY_LEN + nacl.public.Box.NONCE_SIZE + 16):
raise VerificationError('caveat id too short')
original_caveat = caveat
caveat = caveat[1:] # skip version (already checked)
pk_prefix = caveat[:_PUBLIC_KEY_PREFIX_LEN]
caveat = caveat[_PUBLIC_KEY_PREFIX_LEN:]
if key.public_key.serialize(raw=True)[:_PUBLIC_KEY_PREFIX_LEN] != pk_prefix:
raise VerificationError('public key mismatch')
first_party_pub = caveat[:_KEY_LEN]
caveat = caveat[_KEY_LEN:]
nonce = caveat[:nacl.public.Box.NONCE_SIZE]
caveat = caveat[nacl.public.Box.NONCE_SIZE:]
fp_public_key = nacl.public.PublicKey(first_party_pub)
box = nacl.public.Box(key.key, fp_public_key)
data = box.decrypt(caveat, nonce)
root_key, condition, ns = _decode_secret_part_v2_v3(version, data)
return ThirdPartyCaveatInfo(
condition=condition.decode('utf-8'),
first_party_public_key=PublicKey(fp_public_key),
third_party_key_pair=key,
root_key=root_key,
caveat=original_caveat,
version=version,
id=None,
namespace=ns
) | [
"def",
"_decode_caveat_v2_v3",
"(",
"version",
",",
"key",
",",
"caveat",
")",
":",
"if",
"(",
"len",
"(",
"caveat",
")",
"<",
"1",
"+",
"_PUBLIC_KEY_PREFIX_LEN",
"+",
"_KEY_LEN",
"+",
"nacl",
".",
"public",
".",
"Box",
".",
"NONCE_SIZE",
"+",
"16",
")",
":",
"raise",
"VerificationError",
"(",
"'caveat id too short'",
")",
"original_caveat",
"=",
"caveat",
"caveat",
"=",
"caveat",
"[",
"1",
":",
"]",
"# skip version (already checked)",
"pk_prefix",
"=",
"caveat",
"[",
":",
"_PUBLIC_KEY_PREFIX_LEN",
"]",
"caveat",
"=",
"caveat",
"[",
"_PUBLIC_KEY_PREFIX_LEN",
":",
"]",
"if",
"key",
".",
"public_key",
".",
"serialize",
"(",
"raw",
"=",
"True",
")",
"[",
":",
"_PUBLIC_KEY_PREFIX_LEN",
"]",
"!=",
"pk_prefix",
":",
"raise",
"VerificationError",
"(",
"'public key mismatch'",
")",
"first_party_pub",
"=",
"caveat",
"[",
":",
"_KEY_LEN",
"]",
"caveat",
"=",
"caveat",
"[",
"_KEY_LEN",
":",
"]",
"nonce",
"=",
"caveat",
"[",
":",
"nacl",
".",
"public",
".",
"Box",
".",
"NONCE_SIZE",
"]",
"caveat",
"=",
"caveat",
"[",
"nacl",
".",
"public",
".",
"Box",
".",
"NONCE_SIZE",
":",
"]",
"fp_public_key",
"=",
"nacl",
".",
"public",
".",
"PublicKey",
"(",
"first_party_pub",
")",
"box",
"=",
"nacl",
".",
"public",
".",
"Box",
"(",
"key",
".",
"key",
",",
"fp_public_key",
")",
"data",
"=",
"box",
".",
"decrypt",
"(",
"caveat",
",",
"nonce",
")",
"root_key",
",",
"condition",
",",
"ns",
"=",
"_decode_secret_part_v2_v3",
"(",
"version",
",",
"data",
")",
"return",
"ThirdPartyCaveatInfo",
"(",
"condition",
"=",
"condition",
".",
"decode",
"(",
"'utf-8'",
")",
",",
"first_party_public_key",
"=",
"PublicKey",
"(",
"fp_public_key",
")",
",",
"third_party_key_pair",
"=",
"key",
",",
"root_key",
"=",
"root_key",
",",
"caveat",
"=",
"original_caveat",
",",
"version",
"=",
"version",
",",
"id",
"=",
"None",
",",
"namespace",
"=",
"ns",
")"
] | Decodes a version 2 or version 3 caveat. | [
"Decodes",
"a",
"version",
"2",
"or",
"version",
"3",
"caveat",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L213-L244 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | encode_uvarint | def encode_uvarint(n, data):
'''encodes integer into variable-length format into data.'''
if n < 0:
raise ValueError('only support positive integer')
while True:
this_byte = n & 127
n >>= 7
if n == 0:
data.append(this_byte)
break
data.append(this_byte | 128) | python | def encode_uvarint(n, data):
'''encodes integer into variable-length format into data.'''
if n < 0:
raise ValueError('only support positive integer')
while True:
this_byte = n & 127
n >>= 7
if n == 0:
data.append(this_byte)
break
data.append(this_byte | 128) | [
"def",
"encode_uvarint",
"(",
"n",
",",
"data",
")",
":",
"if",
"n",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'only support positive integer'",
")",
"while",
"True",
":",
"this_byte",
"=",
"n",
"&",
"127",
"n",
">>=",
"7",
"if",
"n",
"==",
"0",
":",
"data",
".",
"append",
"(",
"this_byte",
")",
"break",
"data",
".",
"append",
"(",
"this_byte",
"|",
"128",
")"
] | encodes integer into variable-length format into data. | [
"encodes",
"integer",
"into",
"variable",
"-",
"length",
"format",
"into",
"data",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L271-L281 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_codec.py | decode_uvarint | def decode_uvarint(data):
'''Decode a variable-length integer.
Reads a sequence of unsigned integer byte and decodes them into an integer
in variable-length format and returns it and the length read.
'''
n = 0
shift = 0
length = 0
for b in data:
if not isinstance(b, int):
b = six.byte2int(b)
n |= (b & 0x7f) << shift
length += 1
if (b & 0x80) == 0:
break
shift += 7
return n, length | python | def decode_uvarint(data):
'''Decode a variable-length integer.
Reads a sequence of unsigned integer byte and decodes them into an integer
in variable-length format and returns it and the length read.
'''
n = 0
shift = 0
length = 0
for b in data:
if not isinstance(b, int):
b = six.byte2int(b)
n |= (b & 0x7f) << shift
length += 1
if (b & 0x80) == 0:
break
shift += 7
return n, length | [
"def",
"decode_uvarint",
"(",
"data",
")",
":",
"n",
"=",
"0",
"shift",
"=",
"0",
"length",
"=",
"0",
"for",
"b",
"in",
"data",
":",
"if",
"not",
"isinstance",
"(",
"b",
",",
"int",
")",
":",
"b",
"=",
"six",
".",
"byte2int",
"(",
"b",
")",
"n",
"|=",
"(",
"b",
"&",
"0x7f",
")",
"<<",
"shift",
"length",
"+=",
"1",
"if",
"(",
"b",
"&",
"0x80",
")",
"==",
"0",
":",
"break",
"shift",
"+=",
"7",
"return",
"n",
",",
"length"
] | Decode a variable-length integer.
Reads a sequence of unsigned integer byte and decodes them into an integer
in variable-length format and returns it and the length read. | [
"Decode",
"a",
"variable",
"-",
"length",
"integer",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_codec.py#L284-L301 | train |
jenisys/parse_type | parse_type/builder.py | TypeBuilder.make_enum | def make_enum(enum_mappings):
"""
Creates a type converter for an enumeration or text-to-value mapping.
:param enum_mappings: Defines enumeration names and values.
:return: Type converter function object for the enum/mapping.
"""
if (inspect.isclass(enum_mappings) and
issubclass(enum_mappings, enum.Enum)):
enum_class = enum_mappings
enum_mappings = enum_class.__members__
def convert_enum(text):
if text not in convert_enum.mappings:
text = text.lower() # REQUIRED-BY: parse re.IGNORECASE
return convert_enum.mappings[text] #< text.lower() ???
convert_enum.pattern = r"|".join(enum_mappings.keys())
convert_enum.mappings = enum_mappings
return convert_enum | python | def make_enum(enum_mappings):
"""
Creates a type converter for an enumeration or text-to-value mapping.
:param enum_mappings: Defines enumeration names and values.
:return: Type converter function object for the enum/mapping.
"""
if (inspect.isclass(enum_mappings) and
issubclass(enum_mappings, enum.Enum)):
enum_class = enum_mappings
enum_mappings = enum_class.__members__
def convert_enum(text):
if text not in convert_enum.mappings:
text = text.lower() # REQUIRED-BY: parse re.IGNORECASE
return convert_enum.mappings[text] #< text.lower() ???
convert_enum.pattern = r"|".join(enum_mappings.keys())
convert_enum.mappings = enum_mappings
return convert_enum | [
"def",
"make_enum",
"(",
"enum_mappings",
")",
":",
"if",
"(",
"inspect",
".",
"isclass",
"(",
"enum_mappings",
")",
"and",
"issubclass",
"(",
"enum_mappings",
",",
"enum",
".",
"Enum",
")",
")",
":",
"enum_class",
"=",
"enum_mappings",
"enum_mappings",
"=",
"enum_class",
".",
"__members__",
"def",
"convert_enum",
"(",
"text",
")",
":",
"if",
"text",
"not",
"in",
"convert_enum",
".",
"mappings",
":",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"# REQUIRED-BY: parse re.IGNORECASE",
"return",
"convert_enum",
".",
"mappings",
"[",
"text",
"]",
"#< text.lower() ???",
"convert_enum",
".",
"pattern",
"=",
"r\"|\"",
".",
"join",
"(",
"enum_mappings",
".",
"keys",
"(",
")",
")",
"convert_enum",
".",
"mappings",
"=",
"enum_mappings",
"return",
"convert_enum"
] | Creates a type converter for an enumeration or text-to-value mapping.
:param enum_mappings: Defines enumeration names and values.
:return: Type converter function object for the enum/mapping. | [
"Creates",
"a",
"type",
"converter",
"for",
"an",
"enumeration",
"or",
"text",
"-",
"to",
"-",
"value",
"mapping",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/builder.py#L98-L116 | train |
jenisys/parse_type | parse_type/builder.py | TypeBuilder.make_variant | def make_variant(cls, converters, re_opts=None, compiled=False, strict=True):
"""
Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:param re_opts: Regular expression options zu use (=default_re_opts).
:param compiled: Use compiled regexp matcher, if true (=False).
:param strict: Enable assertion checks.
:return: Type converter function object.
.. note::
Works only with named fields in :class:`parse.Parser`.
Parser needs group_index delta for unnamed/fixed fields.
This is not supported for user-defined types.
Otherwise, you need to use :class:`parse_type.parse.Parser`
(patched version of the :mod:`parse` module).
"""
# -- NOTE: Uses double-dispatch with regex pattern rematch because
# match is not passed through to primary type converter.
assert converters, "REQUIRE: Non-empty list."
if len(converters) == 1:
return converters[0]
if re_opts is None:
re_opts = cls.default_re_opts
pattern = r")|(".join([tc.pattern for tc in converters])
pattern = r"("+ pattern + ")"
group_count = len(converters)
for converter in converters:
group_count += pattern_group_count(converter.pattern)
if compiled:
convert_variant = cls.__create_convert_variant_compiled(converters,
re_opts, strict)
else:
convert_variant = cls.__create_convert_variant(re_opts, strict)
convert_variant.pattern = pattern
convert_variant.converters = tuple(converters)
# OLD: convert_variant.group_count = group_count
convert_variant.regex_group_count = group_count
return convert_variant | python | def make_variant(cls, converters, re_opts=None, compiled=False, strict=True):
"""
Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:param re_opts: Regular expression options zu use (=default_re_opts).
:param compiled: Use compiled regexp matcher, if true (=False).
:param strict: Enable assertion checks.
:return: Type converter function object.
.. note::
Works only with named fields in :class:`parse.Parser`.
Parser needs group_index delta for unnamed/fixed fields.
This is not supported for user-defined types.
Otherwise, you need to use :class:`parse_type.parse.Parser`
(patched version of the :mod:`parse` module).
"""
# -- NOTE: Uses double-dispatch with regex pattern rematch because
# match is not passed through to primary type converter.
assert converters, "REQUIRE: Non-empty list."
if len(converters) == 1:
return converters[0]
if re_opts is None:
re_opts = cls.default_re_opts
pattern = r")|(".join([tc.pattern for tc in converters])
pattern = r"("+ pattern + ")"
group_count = len(converters)
for converter in converters:
group_count += pattern_group_count(converter.pattern)
if compiled:
convert_variant = cls.__create_convert_variant_compiled(converters,
re_opts, strict)
else:
convert_variant = cls.__create_convert_variant(re_opts, strict)
convert_variant.pattern = pattern
convert_variant.converters = tuple(converters)
# OLD: convert_variant.group_count = group_count
convert_variant.regex_group_count = group_count
return convert_variant | [
"def",
"make_variant",
"(",
"cls",
",",
"converters",
",",
"re_opts",
"=",
"None",
",",
"compiled",
"=",
"False",
",",
"strict",
"=",
"True",
")",
":",
"# -- NOTE: Uses double-dispatch with regex pattern rematch because",
"# match is not passed through to primary type converter.",
"assert",
"converters",
",",
"\"REQUIRE: Non-empty list.\"",
"if",
"len",
"(",
"converters",
")",
"==",
"1",
":",
"return",
"converters",
"[",
"0",
"]",
"if",
"re_opts",
"is",
"None",
":",
"re_opts",
"=",
"cls",
".",
"default_re_opts",
"pattern",
"=",
"r\")|(\"",
".",
"join",
"(",
"[",
"tc",
".",
"pattern",
"for",
"tc",
"in",
"converters",
"]",
")",
"pattern",
"=",
"r\"(\"",
"+",
"pattern",
"+",
"\")\"",
"group_count",
"=",
"len",
"(",
"converters",
")",
"for",
"converter",
"in",
"converters",
":",
"group_count",
"+=",
"pattern_group_count",
"(",
"converter",
".",
"pattern",
")",
"if",
"compiled",
":",
"convert_variant",
"=",
"cls",
".",
"__create_convert_variant_compiled",
"(",
"converters",
",",
"re_opts",
",",
"strict",
")",
"else",
":",
"convert_variant",
"=",
"cls",
".",
"__create_convert_variant",
"(",
"re_opts",
",",
"strict",
")",
"convert_variant",
".",
"pattern",
"=",
"pattern",
"convert_variant",
".",
"converters",
"=",
"tuple",
"(",
"converters",
")",
"# OLD: convert_variant.group_count = group_count",
"convert_variant",
".",
"regex_group_count",
"=",
"group_count",
"return",
"convert_variant"
] | Creates a type converter for a number of type converter alternatives.
The first matching type converter is used.
REQUIRES: type_converter.pattern attribute
:param converters: List of type converters as alternatives.
:param re_opts: Regular expression options zu use (=default_re_opts).
:param compiled: Use compiled regexp matcher, if true (=False).
:param strict: Enable assertion checks.
:return: Type converter function object.
.. note::
Works only with named fields in :class:`parse.Parser`.
Parser needs group_index delta for unnamed/fixed fields.
This is not supported for user-defined types.
Otherwise, you need to use :class:`parse_type.parse.Parser`
(patched version of the :mod:`parse` module). | [
"Creates",
"a",
"type",
"converter",
"for",
"a",
"number",
"of",
"type",
"converter",
"alternatives",
".",
"The",
"first",
"matching",
"type",
"converter",
"is",
"used",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/builder.py#L183-L227 | train |
crm416/semantic | semantic/units.py | ConversionService.isValidUnit | def isValidUnit(self, w):
"""Checks if a string represents a valid quantities unit.
Args:
w (str): A string to be tested against the set of valid
quantities units.
Returns:
True if the string can be used as a unit in the quantities
module.
"""
bad = set(['point', 'a'])
if w in bad:
return False
try:
pq.Quantity(0.0, w)
return True
except:
return w == '/' | python | def isValidUnit(self, w):
"""Checks if a string represents a valid quantities unit.
Args:
w (str): A string to be tested against the set of valid
quantities units.
Returns:
True if the string can be used as a unit in the quantities
module.
"""
bad = set(['point', 'a'])
if w in bad:
return False
try:
pq.Quantity(0.0, w)
return True
except:
return w == '/' | [
"def",
"isValidUnit",
"(",
"self",
",",
"w",
")",
":",
"bad",
"=",
"set",
"(",
"[",
"'point'",
",",
"'a'",
"]",
")",
"if",
"w",
"in",
"bad",
":",
"return",
"False",
"try",
":",
"pq",
".",
"Quantity",
"(",
"0.0",
",",
"w",
")",
"return",
"True",
"except",
":",
"return",
"w",
"==",
"'/'"
] | Checks if a string represents a valid quantities unit.
Args:
w (str): A string to be tested against the set of valid
quantities units.
Returns:
True if the string can be used as a unit in the quantities
module. | [
"Checks",
"if",
"a",
"string",
"represents",
"a",
"valid",
"quantities",
"unit",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/units.py#L73-L92 | train |
crm416/semantic | semantic/units.py | ConversionService.extractUnits | def extractUnits(self, inp):
"""Collects all the valid units from an inp string. Works by
appending consecutive words from the string and cross-referncing
them with a set of valid units.
Args:
inp (str): Some text which hopefully contains descriptions
of different units.
Returns:
A list of strings, each entry in which is a valid quantities
unit.
"""
inp = self._preprocess(inp)
units = []
description = ""
for w in inp.split(' '):
if self.isValidUnit(w) or w == '/':
if description:
description += " "
description += w
else:
if description:
units.append(description)
description = ""
if description:
units.append(description)
return units | python | def extractUnits(self, inp):
"""Collects all the valid units from an inp string. Works by
appending consecutive words from the string and cross-referncing
them with a set of valid units.
Args:
inp (str): Some text which hopefully contains descriptions
of different units.
Returns:
A list of strings, each entry in which is a valid quantities
unit.
"""
inp = self._preprocess(inp)
units = []
description = ""
for w in inp.split(' '):
if self.isValidUnit(w) or w == '/':
if description:
description += " "
description += w
else:
if description:
units.append(description)
description = ""
if description:
units.append(description)
return units | [
"def",
"extractUnits",
"(",
"self",
",",
"inp",
")",
":",
"inp",
"=",
"self",
".",
"_preprocess",
"(",
"inp",
")",
"units",
"=",
"[",
"]",
"description",
"=",
"\"\"",
"for",
"w",
"in",
"inp",
".",
"split",
"(",
"' '",
")",
":",
"if",
"self",
".",
"isValidUnit",
"(",
"w",
")",
"or",
"w",
"==",
"'/'",
":",
"if",
"description",
":",
"description",
"+=",
"\" \"",
"description",
"+=",
"w",
"else",
":",
"if",
"description",
":",
"units",
".",
"append",
"(",
"description",
")",
"description",
"=",
"\"\"",
"if",
"description",
":",
"units",
".",
"append",
"(",
"description",
")",
"return",
"units"
] | Collects all the valid units from an inp string. Works by
appending consecutive words from the string and cross-referncing
them with a set of valid units.
Args:
inp (str): Some text which hopefully contains descriptions
of different units.
Returns:
A list of strings, each entry in which is a valid quantities
unit. | [
"Collects",
"all",
"the",
"valid",
"units",
"from",
"an",
"inp",
"string",
".",
"Works",
"by",
"appending",
"consecutive",
"words",
"from",
"the",
"string",
"and",
"cross",
"-",
"referncing",
"them",
"with",
"a",
"set",
"of",
"valid",
"units",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/units.py#L94-L123 | train |
crm416/semantic | semantic/units.py | ConversionService.convert | def convert(self, inp):
"""Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representing the described quantity and its
units.
"""
inp = self._preprocess(inp)
n = NumberService().longestNumber(inp)
units = self.extractUnits(inp)
# Convert to quantity object, attempt conversion
quantity = pq.Quantity(float(n), units[0])
quantity.units = units[1]
return quantity | python | def convert(self, inp):
"""Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representing the described quantity and its
units.
"""
inp = self._preprocess(inp)
n = NumberService().longestNumber(inp)
units = self.extractUnits(inp)
# Convert to quantity object, attempt conversion
quantity = pq.Quantity(float(n), units[0])
quantity.units = units[1]
return quantity | [
"def",
"convert",
"(",
"self",
",",
"inp",
")",
":",
"inp",
"=",
"self",
".",
"_preprocess",
"(",
"inp",
")",
"n",
"=",
"NumberService",
"(",
")",
".",
"longestNumber",
"(",
"inp",
")",
"units",
"=",
"self",
".",
"extractUnits",
"(",
"inp",
")",
"# Convert to quantity object, attempt conversion",
"quantity",
"=",
"pq",
".",
"Quantity",
"(",
"float",
"(",
"n",
")",
",",
"units",
"[",
"0",
"]",
")",
"quantity",
".",
"units",
"=",
"units",
"[",
"1",
"]",
"return",
"quantity"
] | Converts a string representation of some quantity of units into a
quantities object.
Args:
inp (str): A textual representation of some quantity of units,
e.g., "fifty kilograms".
Returns:
A quantities object representing the described quantity and its
units. | [
"Converts",
"a",
"string",
"representation",
"of",
"some",
"quantity",
"of",
"units",
"into",
"a",
"quantities",
"object",
"."
] | 46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe | https://github.com/crm416/semantic/blob/46deb8fefb3ea58aad2fedc8d0d62f3ee254b8fe/semantic/units.py#L125-L146 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_identity.py | SimpleIdentity.allow | def allow(self, ctx, acls):
'''Allow access to any ACL members that was equal to the user name.
That is, some user u is considered a member of group u and no other.
'''
for acl in acls:
if self._identity == acl:
return True
return False | python | def allow(self, ctx, acls):
'''Allow access to any ACL members that was equal to the user name.
That is, some user u is considered a member of group u and no other.
'''
for acl in acls:
if self._identity == acl:
return True
return False | [
"def",
"allow",
"(",
"self",
",",
"ctx",
",",
"acls",
")",
":",
"for",
"acl",
"in",
"acls",
":",
"if",
"self",
".",
"_identity",
"==",
"acl",
":",
"return",
"True",
"return",
"False"
] | Allow access to any ACL members that was equal to the user name.
That is, some user u is considered a member of group u and no other. | [
"Allow",
"access",
"to",
"any",
"ACL",
"members",
"that",
"was",
"equal",
"to",
"the",
"user",
"name",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_identity.py#L68-L76 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/command.py | expand_paths | def expand_paths(paths=None, predicate=None, filters=None, parent_uuid=None):
"""Return an unique list of resources or collections from a list of paths.
Supports fq_name and wilcards resolution.
>>> expand_paths(['virtual-network',
'floating-ip/2a0a54b4-a420-485e-8372-42f70a627ec9'])
[Collection('virtual-network'),
Resource('floating-ip', uuid='2a0a54b4-a420-485e-8372-42f70a627ec9')]
:param paths: list of paths relative to the current path
that may contain wildcards (*, ?) or fq_names
:type paths: [str]
:param predicate: function to filter found resources
:type predicate: f(resource) -> bool
:param filters: list of filters for Collections
:type filters: [(name, value), ...]
:rtype: [Resource or Collection]
:raises BadPath: path cannot be resolved
"""
if not paths:
paths = [Context().shell.current_path]
else:
paths = [Context().shell.current_path / res for res in paths]
# use a dict to have unique paths
# but keep them ordered
result = OrderedDict()
for res in parallel_map(_path_to_resources, paths,
kwargs={'predicate': predicate,
'filters': filters,
'parent_uuid': parent_uuid},
workers=50):
for r in res:
result[r.path] = r
resources = list(result.values())
if not resources:
raise NotFound()
return resources | python | def expand_paths(paths=None, predicate=None, filters=None, parent_uuid=None):
"""Return an unique list of resources or collections from a list of paths.
Supports fq_name and wilcards resolution.
>>> expand_paths(['virtual-network',
'floating-ip/2a0a54b4-a420-485e-8372-42f70a627ec9'])
[Collection('virtual-network'),
Resource('floating-ip', uuid='2a0a54b4-a420-485e-8372-42f70a627ec9')]
:param paths: list of paths relative to the current path
that may contain wildcards (*, ?) or fq_names
:type paths: [str]
:param predicate: function to filter found resources
:type predicate: f(resource) -> bool
:param filters: list of filters for Collections
:type filters: [(name, value), ...]
:rtype: [Resource or Collection]
:raises BadPath: path cannot be resolved
"""
if not paths:
paths = [Context().shell.current_path]
else:
paths = [Context().shell.current_path / res for res in paths]
# use a dict to have unique paths
# but keep them ordered
result = OrderedDict()
for res in parallel_map(_path_to_resources, paths,
kwargs={'predicate': predicate,
'filters': filters,
'parent_uuid': parent_uuid},
workers=50):
for r in res:
result[r.path] = r
resources = list(result.values())
if not resources:
raise NotFound()
return resources | [
"def",
"expand_paths",
"(",
"paths",
"=",
"None",
",",
"predicate",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"parent_uuid",
"=",
"None",
")",
":",
"if",
"not",
"paths",
":",
"paths",
"=",
"[",
"Context",
"(",
")",
".",
"shell",
".",
"current_path",
"]",
"else",
":",
"paths",
"=",
"[",
"Context",
"(",
")",
".",
"shell",
".",
"current_path",
"/",
"res",
"for",
"res",
"in",
"paths",
"]",
"# use a dict to have unique paths",
"# but keep them ordered",
"result",
"=",
"OrderedDict",
"(",
")",
"for",
"res",
"in",
"parallel_map",
"(",
"_path_to_resources",
",",
"paths",
",",
"kwargs",
"=",
"{",
"'predicate'",
":",
"predicate",
",",
"'filters'",
":",
"filters",
",",
"'parent_uuid'",
":",
"parent_uuid",
"}",
",",
"workers",
"=",
"50",
")",
":",
"for",
"r",
"in",
"res",
":",
"result",
"[",
"r",
".",
"path",
"]",
"=",
"r",
"resources",
"=",
"list",
"(",
"result",
".",
"values",
"(",
")",
")",
"if",
"not",
"resources",
":",
"raise",
"NotFound",
"(",
")",
"return",
"resources"
] | Return an unique list of resources or collections from a list of paths.
Supports fq_name and wilcards resolution.
>>> expand_paths(['virtual-network',
'floating-ip/2a0a54b4-a420-485e-8372-42f70a627ec9'])
[Collection('virtual-network'),
Resource('floating-ip', uuid='2a0a54b4-a420-485e-8372-42f70a627ec9')]
:param paths: list of paths relative to the current path
that may contain wildcards (*, ?) or fq_names
:type paths: [str]
:param predicate: function to filter found resources
:type predicate: f(resource) -> bool
:param filters: list of filters for Collections
:type filters: [(name, value), ...]
:rtype: [Resource or Collection]
:raises BadPath: path cannot be resolved | [
"Return",
"an",
"unique",
"list",
"of",
"resources",
"or",
"collections",
"from",
"a",
"list",
"of",
"paths",
".",
"Supports",
"fq_name",
"and",
"wilcards",
"resolution",
"."
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/command.py#L136-L174 | train |
dbarsam/python-vsgen | vsgen/writer.py | VSGJinjaRenderer.render | def render(self, template, filename, context={}, filters={}):
"""
Renders a Jinja2 template to text.
"""
filename = os.path.normpath(filename)
path, file = os.path.split(filename)
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
path, file = os.path.split(template)
loader = jinja2.FileSystemLoader(path)
env = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)
env.filters.update(filters)
template = env.get_template(file)
text = template.render(context)
with open(filename, 'wt') as f:
f.write(text) | python | def render(self, template, filename, context={}, filters={}):
"""
Renders a Jinja2 template to text.
"""
filename = os.path.normpath(filename)
path, file = os.path.split(filename)
try:
os.makedirs(path)
except OSError as exception:
if exception.errno != errno.EEXIST:
raise
path, file = os.path.split(template)
loader = jinja2.FileSystemLoader(path)
env = jinja2.Environment(loader=loader, trim_blocks=True, lstrip_blocks=True)
env.filters.update(filters)
template = env.get_template(file)
text = template.render(context)
with open(filename, 'wt') as f:
f.write(text) | [
"def",
"render",
"(",
"self",
",",
"template",
",",
"filename",
",",
"context",
"=",
"{",
"}",
",",
"filters",
"=",
"{",
"}",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"filename",
")",
"path",
",",
"file",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"exception",
":",
"if",
"exception",
".",
"errno",
"!=",
"errno",
".",
"EEXIST",
":",
"raise",
"path",
",",
"file",
"=",
"os",
".",
"path",
".",
"split",
"(",
"template",
")",
"loader",
"=",
"jinja2",
".",
"FileSystemLoader",
"(",
"path",
")",
"env",
"=",
"jinja2",
".",
"Environment",
"(",
"loader",
"=",
"loader",
",",
"trim_blocks",
"=",
"True",
",",
"lstrip_blocks",
"=",
"True",
")",
"env",
".",
"filters",
".",
"update",
"(",
"filters",
")",
"template",
"=",
"env",
".",
"get_template",
"(",
"file",
")",
"text",
"=",
"template",
".",
"render",
"(",
"context",
")",
"with",
"open",
"(",
"filename",
",",
"'wt'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"text",
")"
] | Renders a Jinja2 template to text. | [
"Renders",
"a",
"Jinja2",
"template",
"to",
"text",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/writer.py#L19-L38 | train |
dbarsam/python-vsgen | vsgen/writer.py | VSGWriter.write | def write(pylist, parallel=True):
"""
Utility method to spawn a VSGWriter for each element in a collection.
:param list pylist: A list of VSG objects (PrProjects, VSGSolutions, etc)
:param bool parallel: Flag to enable asynchronous writing.
"""
threads = [VSGWriter(o) for o in pylist]
if parallel:
for t in threads:
t.start()
for t in threads:
t.join()
else:
for t in threads:
t.run() | python | def write(pylist, parallel=True):
"""
Utility method to spawn a VSGWriter for each element in a collection.
:param list pylist: A list of VSG objects (PrProjects, VSGSolutions, etc)
:param bool parallel: Flag to enable asynchronous writing.
"""
threads = [VSGWriter(o) for o in pylist]
if parallel:
for t in threads:
t.start()
for t in threads:
t.join()
else:
for t in threads:
t.run() | [
"def",
"write",
"(",
"pylist",
",",
"parallel",
"=",
"True",
")",
":",
"threads",
"=",
"[",
"VSGWriter",
"(",
"o",
")",
"for",
"o",
"in",
"pylist",
"]",
"if",
"parallel",
":",
"for",
"t",
"in",
"threads",
":",
"t",
".",
"start",
"(",
")",
"for",
"t",
"in",
"threads",
":",
"t",
".",
"join",
"(",
")",
"else",
":",
"for",
"t",
"in",
"threads",
":",
"t",
".",
"run",
"(",
")"
] | Utility method to spawn a VSGWriter for each element in a collection.
:param list pylist: A list of VSG objects (PrProjects, VSGSolutions, etc)
:param bool parallel: Flag to enable asynchronous writing. | [
"Utility",
"method",
"to",
"spawn",
"a",
"VSGWriter",
"for",
"each",
"element",
"in",
"a",
"collection",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/writer.py#L156-L171 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_browser.py | WebBrowserInteractor.interact | def interact(self, ctx, location, ir_err):
'''Implement Interactor.interact by opening the browser window
and waiting for the discharge token'''
p = ir_err.interaction_method(self.kind(), WebBrowserInteractionInfo)
if not location.endswith('/'):
location += '/'
visit_url = urljoin(location, p.visit_url)
wait_token_url = urljoin(location, p.wait_token_url)
self._open_web_browser(visit_url)
return self._wait_for_token(ctx, wait_token_url) | python | def interact(self, ctx, location, ir_err):
'''Implement Interactor.interact by opening the browser window
and waiting for the discharge token'''
p = ir_err.interaction_method(self.kind(), WebBrowserInteractionInfo)
if not location.endswith('/'):
location += '/'
visit_url = urljoin(location, p.visit_url)
wait_token_url = urljoin(location, p.wait_token_url)
self._open_web_browser(visit_url)
return self._wait_for_token(ctx, wait_token_url) | [
"def",
"interact",
"(",
"self",
",",
"ctx",
",",
"location",
",",
"ir_err",
")",
":",
"p",
"=",
"ir_err",
".",
"interaction_method",
"(",
"self",
".",
"kind",
"(",
")",
",",
"WebBrowserInteractionInfo",
")",
"if",
"not",
"location",
".",
"endswith",
"(",
"'/'",
")",
":",
"location",
"+=",
"'/'",
"visit_url",
"=",
"urljoin",
"(",
"location",
",",
"p",
".",
"visit_url",
")",
"wait_token_url",
"=",
"urljoin",
"(",
"location",
",",
"p",
".",
"wait_token_url",
")",
"self",
".",
"_open_web_browser",
"(",
"visit_url",
")",
"return",
"self",
".",
"_wait_for_token",
"(",
"ctx",
",",
"wait_token_url",
")"
] | Implement Interactor.interact by opening the browser window
and waiting for the discharge token | [
"Implement",
"Interactor",
".",
"interact",
"by",
"opening",
"the",
"browser",
"window",
"and",
"waiting",
"for",
"the",
"discharge",
"token"
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_browser.py#L38-L47 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_browser.py | WebBrowserInteractor._wait_for_token | def _wait_for_token(self, ctx, wait_token_url):
''' Returns a token from a the wait token URL
@param wait_token_url URL to wait for (string)
:return DischargeToken
'''
resp = requests.get(wait_token_url)
if resp.status_code != 200:
raise InteractionError('cannot get {}'.format(wait_token_url))
json_resp = resp.json()
kind = json_resp.get('kind')
if kind is None:
raise InteractionError(
'cannot get kind token from {}'.format(wait_token_url))
token_val = json_resp.get('token')
if token_val is None:
token_val = json_resp.get('token64')
if token_val is None:
raise InteractionError(
'cannot get token from {}'.format(wait_token_url))
token_val = base64.b64decode(token_val)
return DischargeToken(kind=kind, value=token_val) | python | def _wait_for_token(self, ctx, wait_token_url):
''' Returns a token from a the wait token URL
@param wait_token_url URL to wait for (string)
:return DischargeToken
'''
resp = requests.get(wait_token_url)
if resp.status_code != 200:
raise InteractionError('cannot get {}'.format(wait_token_url))
json_resp = resp.json()
kind = json_resp.get('kind')
if kind is None:
raise InteractionError(
'cannot get kind token from {}'.format(wait_token_url))
token_val = json_resp.get('token')
if token_val is None:
token_val = json_resp.get('token64')
if token_val is None:
raise InteractionError(
'cannot get token from {}'.format(wait_token_url))
token_val = base64.b64decode(token_val)
return DischargeToken(kind=kind, value=token_val) | [
"def",
"_wait_for_token",
"(",
"self",
",",
"ctx",
",",
"wait_token_url",
")",
":",
"resp",
"=",
"requests",
".",
"get",
"(",
"wait_token_url",
")",
"if",
"resp",
".",
"status_code",
"!=",
"200",
":",
"raise",
"InteractionError",
"(",
"'cannot get {}'",
".",
"format",
"(",
"wait_token_url",
")",
")",
"json_resp",
"=",
"resp",
".",
"json",
"(",
")",
"kind",
"=",
"json_resp",
".",
"get",
"(",
"'kind'",
")",
"if",
"kind",
"is",
"None",
":",
"raise",
"InteractionError",
"(",
"'cannot get kind token from {}'",
".",
"format",
"(",
"wait_token_url",
")",
")",
"token_val",
"=",
"json_resp",
".",
"get",
"(",
"'token'",
")",
"if",
"token_val",
"is",
"None",
":",
"token_val",
"=",
"json_resp",
".",
"get",
"(",
"'token64'",
")",
"if",
"token_val",
"is",
"None",
":",
"raise",
"InteractionError",
"(",
"'cannot get token from {}'",
".",
"format",
"(",
"wait_token_url",
")",
")",
"token_val",
"=",
"base64",
".",
"b64decode",
"(",
"token_val",
")",
"return",
"DischargeToken",
"(",
"kind",
"=",
"kind",
",",
"value",
"=",
"token_val",
")"
] | Returns a token from a the wait token URL
@param wait_token_url URL to wait for (string)
:return DischargeToken | [
"Returns",
"a",
"token",
"from",
"a",
"the",
"wait",
"token",
"URL"
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_browser.py#L49-L69 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_browser.py | WebBrowserInteractionInfo.from_dict | def from_dict(cls, info_dict):
'''Create a new instance of WebBrowserInteractionInfo, as expected
by the Error.interaction_method method.
@param info_dict The deserialized JSON object
@return a new WebBrowserInteractionInfo object.
'''
return WebBrowserInteractionInfo(
visit_url=info_dict.get('VisitURL'),
wait_token_url=info_dict.get('WaitTokenURL')) | python | def from_dict(cls, info_dict):
'''Create a new instance of WebBrowserInteractionInfo, as expected
by the Error.interaction_method method.
@param info_dict The deserialized JSON object
@return a new WebBrowserInteractionInfo object.
'''
return WebBrowserInteractionInfo(
visit_url=info_dict.get('VisitURL'),
wait_token_url=info_dict.get('WaitTokenURL')) | [
"def",
"from_dict",
"(",
"cls",
",",
"info_dict",
")",
":",
"return",
"WebBrowserInteractionInfo",
"(",
"visit_url",
"=",
"info_dict",
".",
"get",
"(",
"'VisitURL'",
")",
",",
"wait_token_url",
"=",
"info_dict",
".",
"get",
"(",
"'WaitTokenURL'",
")",
")"
] | Create a new instance of WebBrowserInteractionInfo, as expected
by the Error.interaction_method method.
@param info_dict The deserialized JSON object
@return a new WebBrowserInteractionInfo object. | [
"Create",
"a",
"new",
"instance",
"of",
"WebBrowserInteractionInfo",
"as",
"expected",
"by",
"the",
"Error",
".",
"interaction_method",
"method",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_browser.py#L82-L90 | train |
useblocks/groundwork | groundwork/configuration/config.py | Config.set | def set(self, name, value, overwrite=False):
"""
Sets a new value for a given configuration parameter.
If it already exists, an Exception is thrown.
To overwrite an existing value, set overwrite to True.
:param name: Unique name of the parameter
:param value: Value of the configuration parameter
:param overwrite: If true, an existing parameter of *name* gets overwritten without warning or exception.
:type overwrite: boolean
"""
if hasattr(self, name):
if overwrite:
setattr(self, name, value)
else:
self._log.warning("Configuration parameter %s exists and overwrite not allowed" % name)
raise Exception("Configuration parameter %s exists and overwrite not allowed" % name)
else:
setattr(self, name, value)
return getattr(self, name) | python | def set(self, name, value, overwrite=False):
"""
Sets a new value for a given configuration parameter.
If it already exists, an Exception is thrown.
To overwrite an existing value, set overwrite to True.
:param name: Unique name of the parameter
:param value: Value of the configuration parameter
:param overwrite: If true, an existing parameter of *name* gets overwritten without warning or exception.
:type overwrite: boolean
"""
if hasattr(self, name):
if overwrite:
setattr(self, name, value)
else:
self._log.warning("Configuration parameter %s exists and overwrite not allowed" % name)
raise Exception("Configuration parameter %s exists and overwrite not allowed" % name)
else:
setattr(self, name, value)
return getattr(self, name) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"name",
")",
":",
"if",
"overwrite",
":",
"setattr",
"(",
"self",
",",
"name",
",",
"value",
")",
"else",
":",
"self",
".",
"_log",
".",
"warning",
"(",
"\"Configuration parameter %s exists and overwrite not allowed\"",
"%",
"name",
")",
"raise",
"Exception",
"(",
"\"Configuration parameter %s exists and overwrite not allowed\"",
"%",
"name",
")",
"else",
":",
"setattr",
"(",
"self",
",",
"name",
",",
"value",
")",
"return",
"getattr",
"(",
"self",
",",
"name",
")"
] | Sets a new value for a given configuration parameter.
If it already exists, an Exception is thrown.
To overwrite an existing value, set overwrite to True.
:param name: Unique name of the parameter
:param value: Value of the configuration parameter
:param overwrite: If true, an existing parameter of *name* gets overwritten without warning or exception.
:type overwrite: boolean | [
"Sets",
"a",
"new",
"value",
"for",
"a",
"given",
"configuration",
"parameter",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/configuration/config.py#L30-L50 | train |
jenisys/parse_type | parse_type/cfparse.py | Parser.create_missing_types | def create_missing_types(cls, schema, type_dict, type_builder=None):
"""Creates missing types for fields with a CardinalityField part.
It is assumed that the primary type converter for cardinality=1
is registered in the type dictionary.
:param schema: Parse schema (or format) for parser (as string).
:param type_dict: Type dictionary with type converters.
:param type_builder: Type builder to use for missing types.
:return: Type dictionary with missing types. Empty, if none.
:raises: MissingTypeError,
if a primary type converter with cardinality=1 is missing.
"""
if not type_builder:
type_builder = cls.type_builder
missing = cls.extract_missing_special_type_names(schema, type_dict)
return type_builder.create_type_variants(missing, type_dict) | python | def create_missing_types(cls, schema, type_dict, type_builder=None):
"""Creates missing types for fields with a CardinalityField part.
It is assumed that the primary type converter for cardinality=1
is registered in the type dictionary.
:param schema: Parse schema (or format) for parser (as string).
:param type_dict: Type dictionary with type converters.
:param type_builder: Type builder to use for missing types.
:return: Type dictionary with missing types. Empty, if none.
:raises: MissingTypeError,
if a primary type converter with cardinality=1 is missing.
"""
if not type_builder:
type_builder = cls.type_builder
missing = cls.extract_missing_special_type_names(schema, type_dict)
return type_builder.create_type_variants(missing, type_dict) | [
"def",
"create_missing_types",
"(",
"cls",
",",
"schema",
",",
"type_dict",
",",
"type_builder",
"=",
"None",
")",
":",
"if",
"not",
"type_builder",
":",
"type_builder",
"=",
"cls",
".",
"type_builder",
"missing",
"=",
"cls",
".",
"extract_missing_special_type_names",
"(",
"schema",
",",
"type_dict",
")",
"return",
"type_builder",
".",
"create_type_variants",
"(",
"missing",
",",
"type_dict",
")"
] | Creates missing types for fields with a CardinalityField part.
It is assumed that the primary type converter for cardinality=1
is registered in the type dictionary.
:param schema: Parse schema (or format) for parser (as string).
:param type_dict: Type dictionary with type converters.
:param type_builder: Type builder to use for missing types.
:return: Type dictionary with missing types. Empty, if none.
:raises: MissingTypeError,
if a primary type converter with cardinality=1 is missing. | [
"Creates",
"missing",
"types",
"for",
"fields",
"with",
"a",
"CardinalityField",
"part",
".",
"It",
"is",
"assumed",
"that",
"the",
"primary",
"type",
"converter",
"for",
"cardinality",
"=",
"1",
"is",
"registered",
"in",
"the",
"type",
"dictionary",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cfparse.py#L56-L72 | train |
jenisys/parse_type | parse_type/cfparse.py | Parser.extract_missing_special_type_names | def extract_missing_special_type_names(schema, type_dict):
"""Extract the type names for fields with CardinalityField part.
Selects only the missing type names that are not in the type dictionary.
:param schema: Parse schema to use (as string).
:param type_dict: Type dictionary with type converters.
:return: Generator with missing type names (as string).
"""
for name in FieldParser.extract_types(schema):
if CardinalityField.matches_type(name) and (name not in type_dict):
yield name | python | def extract_missing_special_type_names(schema, type_dict):
"""Extract the type names for fields with CardinalityField part.
Selects only the missing type names that are not in the type dictionary.
:param schema: Parse schema to use (as string).
:param type_dict: Type dictionary with type converters.
:return: Generator with missing type names (as string).
"""
for name in FieldParser.extract_types(schema):
if CardinalityField.matches_type(name) and (name not in type_dict):
yield name | [
"def",
"extract_missing_special_type_names",
"(",
"schema",
",",
"type_dict",
")",
":",
"for",
"name",
"in",
"FieldParser",
".",
"extract_types",
"(",
"schema",
")",
":",
"if",
"CardinalityField",
".",
"matches_type",
"(",
"name",
")",
"and",
"(",
"name",
"not",
"in",
"type_dict",
")",
":",
"yield",
"name"
] | Extract the type names for fields with CardinalityField part.
Selects only the missing type names that are not in the type dictionary.
:param schema: Parse schema to use (as string).
:param type_dict: Type dictionary with type converters.
:return: Generator with missing type names (as string). | [
"Extract",
"the",
"type",
"names",
"for",
"fields",
"with",
"CardinalityField",
"part",
".",
"Selects",
"only",
"the",
"missing",
"type",
"names",
"that",
"are",
"not",
"in",
"the",
"type",
"dictionary",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cfparse.py#L75-L85 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_checkers.py | _check_operations | def _check_operations(ctx, need_ops, arg):
''' Checks an allow or a deny caveat. The need_ops parameter specifies
whether we require all the operations in the caveat to be declared in
the context.
'''
ctx_ops = ctx.get(OP_KEY, [])
if len(ctx_ops) == 0:
if need_ops:
f = arg.split()
if len(f) == 0:
return 'no operations allowed'
return '{} not allowed'.format(f[0])
return None
fields = arg.split()
for op in ctx_ops:
err = _check_op(op, need_ops, fields)
if err is not None:
return err
return None | python | def _check_operations(ctx, need_ops, arg):
''' Checks an allow or a deny caveat. The need_ops parameter specifies
whether we require all the operations in the caveat to be declared in
the context.
'''
ctx_ops = ctx.get(OP_KEY, [])
if len(ctx_ops) == 0:
if need_ops:
f = arg.split()
if len(f) == 0:
return 'no operations allowed'
return '{} not allowed'.format(f[0])
return None
fields = arg.split()
for op in ctx_ops:
err = _check_op(op, need_ops, fields)
if err is not None:
return err
return None | [
"def",
"_check_operations",
"(",
"ctx",
",",
"need_ops",
",",
"arg",
")",
":",
"ctx_ops",
"=",
"ctx",
".",
"get",
"(",
"OP_KEY",
",",
"[",
"]",
")",
"if",
"len",
"(",
"ctx_ops",
")",
"==",
"0",
":",
"if",
"need_ops",
":",
"f",
"=",
"arg",
".",
"split",
"(",
")",
"if",
"len",
"(",
"f",
")",
"==",
"0",
":",
"return",
"'no operations allowed'",
"return",
"'{} not allowed'",
".",
"format",
"(",
"f",
"[",
"0",
"]",
")",
"return",
"None",
"fields",
"=",
"arg",
".",
"split",
"(",
")",
"for",
"op",
"in",
"ctx_ops",
":",
"err",
"=",
"_check_op",
"(",
"op",
",",
"need_ops",
",",
"fields",
")",
"if",
"err",
"is",
"not",
"None",
":",
"return",
"err",
"return",
"None"
] | Checks an allow or a deny caveat. The need_ops parameter specifies
whether we require all the operations in the caveat to be declared in
the context. | [
"Checks",
"an",
"allow",
"or",
"a",
"deny",
"caveat",
".",
"The",
"need_ops",
"parameter",
"specifies",
"whether",
"we",
"require",
"all",
"the",
"operations",
"in",
"the",
"caveat",
"to",
"be",
"declared",
"in",
"the",
"context",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_checkers.py#L210-L229 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_checkers.py | Checker.info | def info(self):
''' Returns information on all the registered checkers.
Sorted by namespace and then name
:returns a list of CheckerInfo
'''
return sorted(self._checkers.values(), key=lambda x: (x.ns, x.name)) | python | def info(self):
''' Returns information on all the registered checkers.
Sorted by namespace and then name
:returns a list of CheckerInfo
'''
return sorted(self._checkers.values(), key=lambda x: (x.ns, x.name)) | [
"def",
"info",
"(",
"self",
")",
":",
"return",
"sorted",
"(",
"self",
".",
"_checkers",
".",
"values",
"(",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"(",
"x",
".",
"ns",
",",
"x",
".",
"name",
")",
")"
] | Returns information on all the registered checkers.
Sorted by namespace and then name
:returns a list of CheckerInfo | [
"Returns",
"information",
"on",
"all",
"the",
"registered",
"checkers",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_checkers.py#L90-L96 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/checkers/_checkers.py | Checker.register_std | def register_std(self):
''' Registers all the standard checkers in the given checker.
If not present already, the standard checkers schema (STD_NAMESPACE) is
added to the checker's namespace with an empty prefix.
'''
self._namespace.register(STD_NAMESPACE, '')
for cond in _ALL_CHECKERS:
self.register(cond, STD_NAMESPACE, _ALL_CHECKERS[cond]) | python | def register_std(self):
''' Registers all the standard checkers in the given checker.
If not present already, the standard checkers schema (STD_NAMESPACE) is
added to the checker's namespace with an empty prefix.
'''
self._namespace.register(STD_NAMESPACE, '')
for cond in _ALL_CHECKERS:
self.register(cond, STD_NAMESPACE, _ALL_CHECKERS[cond]) | [
"def",
"register_std",
"(",
"self",
")",
":",
"self",
".",
"_namespace",
".",
"register",
"(",
"STD_NAMESPACE",
",",
"''",
")",
"for",
"cond",
"in",
"_ALL_CHECKERS",
":",
"self",
".",
"register",
"(",
"cond",
",",
"STD_NAMESPACE",
",",
"_ALL_CHECKERS",
"[",
"cond",
"]",
")"
] | Registers all the standard checkers in the given checker.
If not present already, the standard checkers schema (STD_NAMESPACE) is
added to the checker's namespace with an empty prefix. | [
"Registers",
"all",
"the",
"standard",
"checkers",
"in",
"the",
"given",
"checker",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/checkers/_checkers.py#L137-L145 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_authorizer.py | AuthorizerFunc.authorize | def authorize(self, ctx, identity, ops):
'''Implements Authorizer.authorize by calling f with the given identity
for each operation.
'''
allowed = []
caveats = []
for op in ops:
ok, fcaveats = self._f(ctx, identity, op)
allowed.append(ok)
if fcaveats is not None:
caveats.extend(fcaveats)
return allowed, caveats | python | def authorize(self, ctx, identity, ops):
'''Implements Authorizer.authorize by calling f with the given identity
for each operation.
'''
allowed = []
caveats = []
for op in ops:
ok, fcaveats = self._f(ctx, identity, op)
allowed.append(ok)
if fcaveats is not None:
caveats.extend(fcaveats)
return allowed, caveats | [
"def",
"authorize",
"(",
"self",
",",
"ctx",
",",
"identity",
",",
"ops",
")",
":",
"allowed",
"=",
"[",
"]",
"caveats",
"=",
"[",
"]",
"for",
"op",
"in",
"ops",
":",
"ok",
",",
"fcaveats",
"=",
"self",
".",
"_f",
"(",
"ctx",
",",
"identity",
",",
"op",
")",
"allowed",
".",
"append",
"(",
"ok",
")",
"if",
"fcaveats",
"is",
"not",
"None",
":",
"caveats",
".",
"extend",
"(",
"fcaveats",
")",
"return",
"allowed",
",",
"caveats"
] | Implements Authorizer.authorize by calling f with the given identity
for each operation. | [
"Implements",
"Authorizer",
".",
"authorize",
"by",
"calling",
"f",
"with",
"the",
"given",
"identity",
"for",
"each",
"operation",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_authorizer.py#L50-L61 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_authorizer.py | ACLAuthorizer.authorize | def authorize(self, ctx, identity, ops):
'''Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations.
'''
if len(ops) == 0:
# Anyone is allowed to do nothing.
return [], []
allowed = [False] * len(ops)
has_allow = isinstance(identity, ACLIdentity)
for i, op in enumerate(ops):
acl = self._get_acl(ctx, op)
if has_allow:
allowed[i] = identity.allow(ctx, acl)
else:
allowed[i] = self._allow_public and EVERYONE in acl
return allowed, [] | python | def authorize(self, ctx, identity, ops):
'''Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations.
'''
if len(ops) == 0:
# Anyone is allowed to do nothing.
return [], []
allowed = [False] * len(ops)
has_allow = isinstance(identity, ACLIdentity)
for i, op in enumerate(ops):
acl = self._get_acl(ctx, op)
if has_allow:
allowed[i] = identity.allow(ctx, acl)
else:
allowed[i] = self._allow_public and EVERYONE in acl
return allowed, [] | [
"def",
"authorize",
"(",
"self",
",",
"ctx",
",",
"identity",
",",
"ops",
")",
":",
"if",
"len",
"(",
"ops",
")",
"==",
"0",
":",
"# Anyone is allowed to do nothing.",
"return",
"[",
"]",
",",
"[",
"]",
"allowed",
"=",
"[",
"False",
"]",
"*",
"len",
"(",
"ops",
")",
"has_allow",
"=",
"isinstance",
"(",
"identity",
",",
"ACLIdentity",
")",
"for",
"i",
",",
"op",
"in",
"enumerate",
"(",
"ops",
")",
":",
"acl",
"=",
"self",
".",
"_get_acl",
"(",
"ctx",
",",
"op",
")",
"if",
"has_allow",
":",
"allowed",
"[",
"i",
"]",
"=",
"identity",
".",
"allow",
"(",
"ctx",
",",
"acl",
")",
"else",
":",
"allowed",
"[",
"i",
"]",
"=",
"self",
".",
"_allow_public",
"and",
"EVERYONE",
"in",
"acl",
"return",
"allowed",
",",
"[",
"]"
] | Implements Authorizer.authorize by calling identity.allow to
determine whether the identity is a member of the ACLs associated with
the given operations. | [
"Implements",
"Authorizer",
".",
"authorize",
"by",
"calling",
"identity",
".",
"allow",
"to",
"determine",
"whether",
"the",
"identity",
"is",
"a",
"member",
"of",
"the",
"ACLs",
"associated",
"with",
"the",
"given",
"operations",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_authorizer.py#L83-L99 | train |
cocoakekeyu/cancan | cancan/rule.py | Rule.is_relevant | def is_relevant(self, action, subject):
"""
Matches both the subject and action, not necessarily the conditions.
"""
return self.matches_action(action) and self.matches_subject(subject) | python | def is_relevant(self, action, subject):
"""
Matches both the subject and action, not necessarily the conditions.
"""
return self.matches_action(action) and self.matches_subject(subject) | [
"def",
"is_relevant",
"(",
"self",
",",
"action",
",",
"subject",
")",
":",
"return",
"self",
".",
"matches_action",
"(",
"action",
")",
"and",
"self",
".",
"matches_subject",
"(",
"subject",
")"
] | Matches both the subject and action, not necessarily the conditions. | [
"Matches",
"both",
"the",
"subject",
"and",
"action",
"not",
"necessarily",
"the",
"conditions",
"."
] | f198d560e6e008e6c5580ba55581a939a5d544ed | https://github.com/cocoakekeyu/cancan/blob/f198d560e6e008e6c5580ba55581a939a5d544ed/cancan/rule.py#L42-L46 | train |
Phyks/libbmc | libbmc/repositories/hal.py | is_valid | def is_valid(hal_id):
"""
Check that a given HAL id is a valid one.
:param hal_id: The HAL id to be checked.
:returns: Boolean indicating whether the HAL id is valid or not.
>>> is_valid("hal-01258754, version 1")
True
>>> is_valid("hal-01258754")
True
>>> is_valid("hal-01258754v2")
True
>>> is_valid("foobar")
False
"""
match = REGEX.match(hal_id)
return (match is not None) and (match.group(0) == hal_id) | python | def is_valid(hal_id):
"""
Check that a given HAL id is a valid one.
:param hal_id: The HAL id to be checked.
:returns: Boolean indicating whether the HAL id is valid or not.
>>> is_valid("hal-01258754, version 1")
True
>>> is_valid("hal-01258754")
True
>>> is_valid("hal-01258754v2")
True
>>> is_valid("foobar")
False
"""
match = REGEX.match(hal_id)
return (match is not None) and (match.group(0) == hal_id) | [
"def",
"is_valid",
"(",
"hal_id",
")",
":",
"match",
"=",
"REGEX",
".",
"match",
"(",
"hal_id",
")",
"return",
"(",
"match",
"is",
"not",
"None",
")",
"and",
"(",
"match",
".",
"group",
"(",
"0",
")",
"==",
"hal_id",
")"
] | Check that a given HAL id is a valid one.
:param hal_id: The HAL id to be checked.
:returns: Boolean indicating whether the HAL id is valid or not.
>>> is_valid("hal-01258754, version 1")
True
>>> is_valid("hal-01258754")
True
>>> is_valid("hal-01258754v2")
True
>>> is_valid("foobar")
False | [
"Check",
"that",
"a",
"given",
"HAL",
"id",
"is",
"a",
"valid",
"one",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/hal.py#L16-L36 | train |
Phyks/libbmc | libbmc/repositories/hal.py | extract_from_text | def extract_from_text(text):
"""
Extract HAL ids from a text.
:param text: The text to extract HAL ids from.
:returns: A list of matching HAL ids.
>>> sorted(extract_from_text("hal-01258754 hal-01258754v2 foobar"))
['hal-01258754', 'hal-01258754v2']
"""
return tools.remove_duplicates([i[0]
for i in REGEX.findall(text) if i != '']) | python | def extract_from_text(text):
"""
Extract HAL ids from a text.
:param text: The text to extract HAL ids from.
:returns: A list of matching HAL ids.
>>> sorted(extract_from_text("hal-01258754 hal-01258754v2 foobar"))
['hal-01258754', 'hal-01258754v2']
"""
return tools.remove_duplicates([i[0]
for i in REGEX.findall(text) if i != '']) | [
"def",
"extract_from_text",
"(",
"text",
")",
":",
"return",
"tools",
".",
"remove_duplicates",
"(",
"[",
"i",
"[",
"0",
"]",
"for",
"i",
"in",
"REGEX",
".",
"findall",
"(",
"text",
")",
"if",
"i",
"!=",
"''",
"]",
")"
] | Extract HAL ids from a text.
:param text: The text to extract HAL ids from.
:returns: A list of matching HAL ids.
>>> sorted(extract_from_text("hal-01258754 hal-01258754v2 foobar"))
['hal-01258754', 'hal-01258754v2'] | [
"Extract",
"HAL",
"ids",
"from",
"a",
"text",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/repositories/hal.py#L39-L50 | train |
dbarsam/python-vsgen | vsgen/suite.py | VSGSuite._getsolution | def _getsolution(self, config, section, **kwargs):
"""
Creates a VSG solution from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSolution.
:return: A valid VSGSolution instance if succesful; None otherwise.
"""
if section not in config:
raise ValueError('Section [{}] not found in [{}]'.format(section, ', '.join(config.sections())))
s = VSGSolution(**kwargs)
s.Name = config.get(section, 'name', fallback=s.Name)
s.FileName = os.path.normpath(config.get(section, 'filename', fallback=s.FileName))
s.VSVersion = config.getfloat(section, 'visual_studio_version', fallback=s.VSVersion)
if not s.VSVersion:
raise ValueError('Solution section [%s] requires a value for Visual Studio Version (visual_studio_version)' % section)
project_sections = config.getlist(section, 'projects', fallback=[])
for project_section in project_sections:
project = self._getproject(config, project_section, VSVersion=s.VSVersion)
s.Projects.append(project)
return s | python | def _getsolution(self, config, section, **kwargs):
"""
Creates a VSG solution from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSolution.
:return: A valid VSGSolution instance if succesful; None otherwise.
"""
if section not in config:
raise ValueError('Section [{}] not found in [{}]'.format(section, ', '.join(config.sections())))
s = VSGSolution(**kwargs)
s.Name = config.get(section, 'name', fallback=s.Name)
s.FileName = os.path.normpath(config.get(section, 'filename', fallback=s.FileName))
s.VSVersion = config.getfloat(section, 'visual_studio_version', fallback=s.VSVersion)
if not s.VSVersion:
raise ValueError('Solution section [%s] requires a value for Visual Studio Version (visual_studio_version)' % section)
project_sections = config.getlist(section, 'projects', fallback=[])
for project_section in project_sections:
project = self._getproject(config, project_section, VSVersion=s.VSVersion)
s.Projects.append(project)
return s | [
"def",
"_getsolution",
"(",
"self",
",",
"config",
",",
"section",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"section",
"not",
"in",
"config",
":",
"raise",
"ValueError",
"(",
"'Section [{}] not found in [{}]'",
".",
"format",
"(",
"section",
",",
"', '",
".",
"join",
"(",
"config",
".",
"sections",
"(",
")",
")",
")",
")",
"s",
"=",
"VSGSolution",
"(",
"*",
"*",
"kwargs",
")",
"s",
".",
"Name",
"=",
"config",
".",
"get",
"(",
"section",
",",
"'name'",
",",
"fallback",
"=",
"s",
".",
"Name",
")",
"s",
".",
"FileName",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"config",
".",
"get",
"(",
"section",
",",
"'filename'",
",",
"fallback",
"=",
"s",
".",
"FileName",
")",
")",
"s",
".",
"VSVersion",
"=",
"config",
".",
"getfloat",
"(",
"section",
",",
"'visual_studio_version'",
",",
"fallback",
"=",
"s",
".",
"VSVersion",
")",
"if",
"not",
"s",
".",
"VSVersion",
":",
"raise",
"ValueError",
"(",
"'Solution section [%s] requires a value for Visual Studio Version (visual_studio_version)'",
"%",
"section",
")",
"project_sections",
"=",
"config",
".",
"getlist",
"(",
"section",
",",
"'projects'",
",",
"fallback",
"=",
"[",
"]",
")",
"for",
"project_section",
"in",
"project_sections",
":",
"project",
"=",
"self",
".",
"_getproject",
"(",
"config",
",",
"project_section",
",",
"VSVersion",
"=",
"s",
".",
"VSVersion",
")",
"s",
".",
"Projects",
".",
"append",
"(",
"project",
")",
"return",
"s"
] | Creates a VSG solution from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSolution.
:return: A valid VSGSolution instance if succesful; None otherwise. | [
"Creates",
"a",
"VSG",
"solution",
"from",
"a",
"configparser",
"instance",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L43-L68 | train |
dbarsam/python-vsgen | vsgen/suite.py | VSGSuite._getproject | def _getproject(self, config, section, **kwargs):
"""
Creates a VSG project from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGProject.
:return: A valid VSGProject instance if succesful; None otherwise.
"""
if section not in config:
raise ValueError('Section [{}] not found in [{}]'.format(section, ', '.join(config.sections())))
type = config.get(section, 'type', fallback=None)
if not type:
raise ValueError('Section [{}] mandatory option "{}" not found'.format(section, "type"))
project_class = entrypoint('vsgen.projects', type)
return project_class.from_section(config, section, **kwargs) | python | def _getproject(self, config, section, **kwargs):
"""
Creates a VSG project from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGProject.
:return: A valid VSGProject instance if succesful; None otherwise.
"""
if section not in config:
raise ValueError('Section [{}] not found in [{}]'.format(section, ', '.join(config.sections())))
type = config.get(section, 'type', fallback=None)
if not type:
raise ValueError('Section [{}] mandatory option "{}" not found'.format(section, "type"))
project_class = entrypoint('vsgen.projects', type)
return project_class.from_section(config, section, **kwargs) | [
"def",
"_getproject",
"(",
"self",
",",
"config",
",",
"section",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"section",
"not",
"in",
"config",
":",
"raise",
"ValueError",
"(",
"'Section [{}] not found in [{}]'",
".",
"format",
"(",
"section",
",",
"', '",
".",
"join",
"(",
"config",
".",
"sections",
"(",
")",
")",
")",
")",
"type",
"=",
"config",
".",
"get",
"(",
"section",
",",
"'type'",
",",
"fallback",
"=",
"None",
")",
"if",
"not",
"type",
":",
"raise",
"ValueError",
"(",
"'Section [{}] mandatory option \"{}\" not found'",
".",
"format",
"(",
"section",
",",
"\"type\"",
")",
")",
"project_class",
"=",
"entrypoint",
"(",
"'vsgen.projects'",
",",
"type",
")",
"return",
"project_class",
".",
"from_section",
"(",
"config",
",",
"section",
",",
"*",
"*",
"kwargs",
")"
] | Creates a VSG project from a configparser instance.
:param object config: The instance of the configparser class
:param str section: The section name to read.
:param kwargs: List of additional keyworded arguments to be passed into the VSGProject.
:return: A valid VSGProject instance if succesful; None otherwise. | [
"Creates",
"a",
"VSG",
"project",
"from",
"a",
"configparser",
"instance",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L70-L87 | train |
dbarsam/python-vsgen | vsgen/suite.py | VSGSuite.from_args | def from_args(cls, **kwargs):
"""
Generates one or more VSGSuite instances from command line arguments.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method.
"""
# Create a VSGSuite for each filename on the command line.
if kwargs.get('suite_commands', None) == 'generate':
filenames = kwargs.pop('configuration_filenames', [])
return [cls.from_file(f) for f in filenames]
# Create a VSGSuit from the target directory and override commands
if kwargs.get('suite_commands', None) == 'auto':
type = kwargs.get('suite_type', None)
return [cls.from_directory('', type, **kwargs)]
# Create nothing.
return [] | python | def from_args(cls, **kwargs):
"""
Generates one or more VSGSuite instances from command line arguments.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method.
"""
# Create a VSGSuite for each filename on the command line.
if kwargs.get('suite_commands', None) == 'generate':
filenames = kwargs.pop('configuration_filenames', [])
return [cls.from_file(f) for f in filenames]
# Create a VSGSuit from the target directory and override commands
if kwargs.get('suite_commands', None) == 'auto':
type = kwargs.get('suite_type', None)
return [cls.from_directory('', type, **kwargs)]
# Create nothing.
return [] | [
"def",
"from_args",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create a VSGSuite for each filename on the command line.",
"if",
"kwargs",
".",
"get",
"(",
"'suite_commands'",
",",
"None",
")",
"==",
"'generate'",
":",
"filenames",
"=",
"kwargs",
".",
"pop",
"(",
"'configuration_filenames'",
",",
"[",
"]",
")",
"return",
"[",
"cls",
".",
"from_file",
"(",
"f",
")",
"for",
"f",
"in",
"filenames",
"]",
"# Create a VSGSuit from the target directory and override commands",
"if",
"kwargs",
".",
"get",
"(",
"'suite_commands'",
",",
"None",
")",
"==",
"'auto'",
":",
"type",
"=",
"kwargs",
".",
"get",
"(",
"'suite_type'",
",",
"None",
")",
"return",
"[",
"cls",
".",
"from_directory",
"(",
"''",
",",
"type",
",",
"*",
"*",
"kwargs",
")",
"]",
"# Create nothing.",
"return",
"[",
"]"
] | Generates one or more VSGSuite instances from command line arguments.
:param kwargs: List of additional keyworded arguments to be passed into the VSGSuite defined in the :meth:`~VSGSuite.make_parser` method. | [
"Generates",
"one",
"or",
"more",
"VSGSuite",
"instances",
"from",
"command",
"line",
"arguments",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L137-L154 | train |
dbarsam/python-vsgen | vsgen/suite.py | VSGSuite.write | def write(self, parallel=True):
"""
Writes the configuration to disk.
"""
# Write the Solution files
solutions = sorted(self._solutions, key=lambda x: x.Name)
with VSGWriteCommand('Writing VSG Solution', solutions, parallel) as command:
command.execute()
# Write the Projects files
projects = set(sorted((p for s in solutions for p in s.Projects), key=lambda x: x.Name))
with VSGWriteCommand('Writing VSG Projects', projects, parallel) as command:
command.execute()
# Register the registerables
registerables = set(sorted((p for s in solutions for p in s.Projects), key=lambda x: x.Name))
with VSGRegisterCommand('Registering Project Registerables', registerables) as command:
command.execute() | python | def write(self, parallel=True):
"""
Writes the configuration to disk.
"""
# Write the Solution files
solutions = sorted(self._solutions, key=lambda x: x.Name)
with VSGWriteCommand('Writing VSG Solution', solutions, parallel) as command:
command.execute()
# Write the Projects files
projects = set(sorted((p for s in solutions for p in s.Projects), key=lambda x: x.Name))
with VSGWriteCommand('Writing VSG Projects', projects, parallel) as command:
command.execute()
# Register the registerables
registerables = set(sorted((p for s in solutions for p in s.Projects), key=lambda x: x.Name))
with VSGRegisterCommand('Registering Project Registerables', registerables) as command:
command.execute() | [
"def",
"write",
"(",
"self",
",",
"parallel",
"=",
"True",
")",
":",
"# Write the Solution files",
"solutions",
"=",
"sorted",
"(",
"self",
".",
"_solutions",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"Name",
")",
"with",
"VSGWriteCommand",
"(",
"'Writing VSG Solution'",
",",
"solutions",
",",
"parallel",
")",
"as",
"command",
":",
"command",
".",
"execute",
"(",
")",
"# Write the Projects files",
"projects",
"=",
"set",
"(",
"sorted",
"(",
"(",
"p",
"for",
"s",
"in",
"solutions",
"for",
"p",
"in",
"s",
".",
"Projects",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"Name",
")",
")",
"with",
"VSGWriteCommand",
"(",
"'Writing VSG Projects'",
",",
"projects",
",",
"parallel",
")",
"as",
"command",
":",
"command",
".",
"execute",
"(",
")",
"# Register the registerables",
"registerables",
"=",
"set",
"(",
"sorted",
"(",
"(",
"p",
"for",
"s",
"in",
"solutions",
"for",
"p",
"in",
"s",
".",
"Projects",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"Name",
")",
")",
"with",
"VSGRegisterCommand",
"(",
"'Registering Project Registerables'",
",",
"registerables",
")",
"as",
"command",
":",
"command",
".",
"execute",
"(",
")"
] | Writes the configuration to disk. | [
"Writes",
"the",
"configuration",
"to",
"disk",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/suite.py#L176-L193 | train |
Phyks/libbmc | libbmc/citations/bbl.py | bibitem_as_plaintext | def bibitem_as_plaintext(bibitem):
"""
Return a plaintext representation of a bibitem from the ``.bbl`` file.
.. note::
This plaintext representation can be super ugly, contain URLs and so \
on.
.. note::
You need to have ``delatex`` installed system-wide, or to build it in \
this repo, according to the ``README.md`` before using this \
function.
:param bibitem: The text content of the bibitem.
:returns: A cleaned plaintext citation from the bibitem.
"""
try:
output = subprocess.check_output(["delatex",
"-s"],
input=bibitem.encode("utf-8"))
except FileNotFoundError:
script_dir = os.path.dirname(os.path.abspath(__file__))
output = subprocess.check_output(["%s/../external/opendetex/delatex" %
(script_dir,),
"-s"],
input=bibitem.encode("utf-8"))
output = output.decode("utf-8")
output = tools.clean_whitespaces(output)
return output | python | def bibitem_as_plaintext(bibitem):
"""
Return a plaintext representation of a bibitem from the ``.bbl`` file.
.. note::
This plaintext representation can be super ugly, contain URLs and so \
on.
.. note::
You need to have ``delatex`` installed system-wide, or to build it in \
this repo, according to the ``README.md`` before using this \
function.
:param bibitem: The text content of the bibitem.
:returns: A cleaned plaintext citation from the bibitem.
"""
try:
output = subprocess.check_output(["delatex",
"-s"],
input=bibitem.encode("utf-8"))
except FileNotFoundError:
script_dir = os.path.dirname(os.path.abspath(__file__))
output = subprocess.check_output(["%s/../external/opendetex/delatex" %
(script_dir,),
"-s"],
input=bibitem.encode("utf-8"))
output = output.decode("utf-8")
output = tools.clean_whitespaces(output)
return output | [
"def",
"bibitem_as_plaintext",
"(",
"bibitem",
")",
":",
"try",
":",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"delatex\"",
",",
"\"-s\"",
"]",
",",
"input",
"=",
"bibitem",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"except",
"FileNotFoundError",
":",
"script_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"\"%s/../external/opendetex/delatex\"",
"%",
"(",
"script_dir",
",",
")",
",",
"\"-s\"",
"]",
",",
"input",
"=",
"bibitem",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"output",
"=",
"output",
".",
"decode",
"(",
"\"utf-8\"",
")",
"output",
"=",
"tools",
".",
"clean_whitespaces",
"(",
"output",
")",
"return",
"output"
] | Return a plaintext representation of a bibitem from the ``.bbl`` file.
.. note::
This plaintext representation can be super ugly, contain URLs and so \
on.
.. note::
You need to have ``delatex`` installed system-wide, or to build it in \
this repo, according to the ``README.md`` before using this \
function.
:param bibitem: The text content of the bibitem.
:returns: A cleaned plaintext citation from the bibitem. | [
"Return",
"a",
"plaintext",
"representation",
"of",
"a",
"bibitem",
"from",
"the",
".",
"bbl",
"file",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/citations/bbl.py#L19-L49 | train |
jenisys/parse_type | parse_type/cardinality_field.py | CardinalityField.split_type | def split_type(cls, type_name):
"""Split type of a type name with CardinalityField suffix into its parts.
:param type_name: Type name (as string).
:return: Tuple (type_basename, cardinality)
"""
if cls.matches_type(type_name):
basename = type_name[:-1]
cardinality = cls.from_char_map[type_name[-1]]
else:
# -- ASSUME: Cardinality.one
cardinality = Cardinality.one
basename = type_name
return (basename, cardinality) | python | def split_type(cls, type_name):
"""Split type of a type name with CardinalityField suffix into its parts.
:param type_name: Type name (as string).
:return: Tuple (type_basename, cardinality)
"""
if cls.matches_type(type_name):
basename = type_name[:-1]
cardinality = cls.from_char_map[type_name[-1]]
else:
# -- ASSUME: Cardinality.one
cardinality = Cardinality.one
basename = type_name
return (basename, cardinality) | [
"def",
"split_type",
"(",
"cls",
",",
"type_name",
")",
":",
"if",
"cls",
".",
"matches_type",
"(",
"type_name",
")",
":",
"basename",
"=",
"type_name",
"[",
":",
"-",
"1",
"]",
"cardinality",
"=",
"cls",
".",
"from_char_map",
"[",
"type_name",
"[",
"-",
"1",
"]",
"]",
"else",
":",
"# -- ASSUME: Cardinality.one",
"cardinality",
"=",
"Cardinality",
".",
"one",
"basename",
"=",
"type_name",
"return",
"(",
"basename",
",",
"cardinality",
")"
] | Split type of a type name with CardinalityField suffix into its parts.
:param type_name: Type name (as string).
:return: Tuple (type_basename, cardinality) | [
"Split",
"type",
"of",
"a",
"type",
"name",
"with",
"CardinalityField",
"suffix",
"into",
"its",
"parts",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality_field.py#L48-L61 | train |
jenisys/parse_type | parse_type/cardinality_field.py | CardinalityField.make_type | def make_type(cls, basename, cardinality):
"""Build new type name according to CardinalityField naming scheme.
:param basename: Type basename of primary type (as string).
:param cardinality: Cardinality of the new type (as Cardinality item).
:return: Type name with CardinalityField suffix (if needed)
"""
if cardinality is Cardinality.one:
# -- POSTCONDITION: assert not cls.make_type(type_name)
return basename
# -- NORMAL CASE: type with CardinalityField suffix.
type_name = "%s%s" % (basename, cls.to_char_map[cardinality])
# -- POSTCONDITION: assert cls.make_type(type_name)
return type_name | python | def make_type(cls, basename, cardinality):
"""Build new type name according to CardinalityField naming scheme.
:param basename: Type basename of primary type (as string).
:param cardinality: Cardinality of the new type (as Cardinality item).
:return: Type name with CardinalityField suffix (if needed)
"""
if cardinality is Cardinality.one:
# -- POSTCONDITION: assert not cls.make_type(type_name)
return basename
# -- NORMAL CASE: type with CardinalityField suffix.
type_name = "%s%s" % (basename, cls.to_char_map[cardinality])
# -- POSTCONDITION: assert cls.make_type(type_name)
return type_name | [
"def",
"make_type",
"(",
"cls",
",",
"basename",
",",
"cardinality",
")",
":",
"if",
"cardinality",
"is",
"Cardinality",
".",
"one",
":",
"# -- POSTCONDITION: assert not cls.make_type(type_name)",
"return",
"basename",
"# -- NORMAL CASE: type with CardinalityField suffix.",
"type_name",
"=",
"\"%s%s\"",
"%",
"(",
"basename",
",",
"cls",
".",
"to_char_map",
"[",
"cardinality",
"]",
")",
"# -- POSTCONDITION: assert cls.make_type(type_name)",
"return",
"type_name"
] | Build new type name according to CardinalityField naming scheme.
:param basename: Type basename of primary type (as string).
:param cardinality: Cardinality of the new type (as Cardinality item).
:return: Type name with CardinalityField suffix (if needed) | [
"Build",
"new",
"type",
"name",
"according",
"to",
"CardinalityField",
"naming",
"scheme",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality_field.py#L64-L77 | train |
jenisys/parse_type | parse_type/cardinality_field.py | CardinalityFieldTypeBuilder.create_missing_type_variants | def create_missing_type_variants(cls, type_names, type_dict):
"""
Create missing type variants for types with a cardinality field.
:param type_names: List of type names with cardinality field suffix.
:param type_dict: Type dictionary with named type converters.
:return: Type dictionary with missing type converter variants.
"""
missing_type_names = [ name for name in type_names
if name not in type_dict ]
return cls.create_type_variants(missing_type_names, type_dict) | python | def create_missing_type_variants(cls, type_names, type_dict):
"""
Create missing type variants for types with a cardinality field.
:param type_names: List of type names with cardinality field suffix.
:param type_dict: Type dictionary with named type converters.
:return: Type dictionary with missing type converter variants.
"""
missing_type_names = [ name for name in type_names
if name not in type_dict ]
return cls.create_type_variants(missing_type_names, type_dict) | [
"def",
"create_missing_type_variants",
"(",
"cls",
",",
"type_names",
",",
"type_dict",
")",
":",
"missing_type_names",
"=",
"[",
"name",
"for",
"name",
"in",
"type_names",
"if",
"name",
"not",
"in",
"type_dict",
"]",
"return",
"cls",
".",
"create_type_variants",
"(",
"missing_type_names",
",",
"type_dict",
")"
] | Create missing type variants for types with a cardinality field.
:param type_names: List of type names with cardinality field suffix.
:param type_dict: Type dictionary with named type converters.
:return: Type dictionary with missing type converter variants. | [
"Create",
"missing",
"type",
"variants",
"for",
"types",
"with",
"a",
"cardinality",
"field",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/parse_type/cardinality_field.py#L162-L172 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_store.py | MemoryOpsStore.put_ops | def put_ops(self, key, time, ops):
''' Put an ops only if not already there, otherwise it's a no op.
'''
if self._store.get(key) is None:
self._store[key] = ops | python | def put_ops(self, key, time, ops):
''' Put an ops only if not already there, otherwise it's a no op.
'''
if self._store.get(key) is None:
self._store[key] = ops | [
"def",
"put_ops",
"(",
"self",
",",
"key",
",",
"time",
",",
"ops",
")",
":",
"if",
"self",
".",
"_store",
".",
"get",
"(",
"key",
")",
"is",
"None",
":",
"self",
".",
"_store",
"[",
"key",
"]",
"=",
"ops"
] | Put an ops only if not already there, otherwise it's a no op. | [
"Put",
"an",
"ops",
"only",
"if",
"not",
"already",
"there",
"otherwise",
"it",
"s",
"a",
"no",
"op",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_store.py#L13-L17 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_store.py | MemoryOpsStore.get_ops | def get_ops(self, key):
''' Returns ops from the key if found otherwise raises a KeyError.
'''
ops = self._store.get(key)
if ops is None:
raise KeyError(
'cannot get operations for {}'.format(key))
return ops | python | def get_ops(self, key):
''' Returns ops from the key if found otherwise raises a KeyError.
'''
ops = self._store.get(key)
if ops is None:
raise KeyError(
'cannot get operations for {}'.format(key))
return ops | [
"def",
"get_ops",
"(",
"self",
",",
"key",
")",
":",
"ops",
"=",
"self",
".",
"_store",
".",
"get",
"(",
"key",
")",
"if",
"ops",
"is",
"None",
":",
"raise",
"KeyError",
"(",
"'cannot get operations for {}'",
".",
"format",
"(",
"key",
")",
")",
"return",
"ops"
] | Returns ops from the key if found otherwise raises a KeyError. | [
"Returns",
"ops",
"from",
"the",
"key",
"if",
"found",
"otherwise",
"raises",
"a",
"KeyError",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_store.py#L19-L26 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | _parse_local_location | def _parse_local_location(loc):
'''Parse a local caveat location as generated by LocalThirdPartyCaveat.
This is of the form:
local <version> <pubkey>
where <version> is the bakery version of the client that we're
adding the local caveat for.
It returns None if the location does not represent a local
caveat location.
@return a ThirdPartyInfo.
'''
if not (loc.startswith('local ')):
return None
v = VERSION_1
fields = loc.split()
fields = fields[1:] # Skip 'local'
if len(fields) == 2:
try:
v = int(fields[0])
except ValueError:
return None
fields = fields[1:]
if len(fields) == 1:
key = PublicKey.deserialize(fields[0])
return ThirdPartyInfo(public_key=key, version=v)
return None | python | def _parse_local_location(loc):
'''Parse a local caveat location as generated by LocalThirdPartyCaveat.
This is of the form:
local <version> <pubkey>
where <version> is the bakery version of the client that we're
adding the local caveat for.
It returns None if the location does not represent a local
caveat location.
@return a ThirdPartyInfo.
'''
if not (loc.startswith('local ')):
return None
v = VERSION_1
fields = loc.split()
fields = fields[1:] # Skip 'local'
if len(fields) == 2:
try:
v = int(fields[0])
except ValueError:
return None
fields = fields[1:]
if len(fields) == 1:
key = PublicKey.deserialize(fields[0])
return ThirdPartyInfo(public_key=key, version=v)
return None | [
"def",
"_parse_local_location",
"(",
"loc",
")",
":",
"if",
"not",
"(",
"loc",
".",
"startswith",
"(",
"'local '",
")",
")",
":",
"return",
"None",
"v",
"=",
"VERSION_1",
"fields",
"=",
"loc",
".",
"split",
"(",
")",
"fields",
"=",
"fields",
"[",
"1",
":",
"]",
"# Skip 'local'",
"if",
"len",
"(",
"fields",
")",
"==",
"2",
":",
"try",
":",
"v",
"=",
"int",
"(",
"fields",
"[",
"0",
"]",
")",
"except",
"ValueError",
":",
"return",
"None",
"fields",
"=",
"fields",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"fields",
")",
"==",
"1",
":",
"key",
"=",
"PublicKey",
".",
"deserialize",
"(",
"fields",
"[",
"0",
"]",
")",
"return",
"ThirdPartyInfo",
"(",
"public_key",
"=",
"key",
",",
"version",
"=",
"v",
")",
"return",
"None"
] | Parse a local caveat location as generated by LocalThirdPartyCaveat.
This is of the form:
local <version> <pubkey>
where <version> is the bakery version of the client that we're
adding the local caveat for.
It returns None if the location does not represent a local
caveat location.
@return a ThirdPartyInfo. | [
"Parse",
"a",
"local",
"caveat",
"location",
"as",
"generated",
"by",
"LocalThirdPartyCaveat",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L372-L400 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | Macaroon.add_caveat | def add_caveat(self, cav, key=None, loc=None):
'''Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a client self-discharge caveat using
the public key base64-encoded in the rest of the location. In this
case, the Condition field must be empty. The resulting third-party
caveat will encode the condition "true" encrypted with that public
key.
@param cav the checkers.Caveat to be added.
@param key the public key to encrypt third party caveat.
@param loc locator to find information on third parties when adding
third party caveats. It is expected to have a third_party_info method
that will be called with a location string and should return a
ThirdPartyInfo instance holding the requested information.
'''
if cav.location is None:
self._macaroon.add_first_party_caveat(
self.namespace.resolve_caveat(cav).condition)
return
if key is None:
raise ValueError(
'no private key to encrypt third party caveat')
local_info = _parse_local_location(cav.location)
if local_info is not None:
info = local_info
if cav.condition is not '':
raise ValueError(
'cannot specify caveat condition in '
'local third-party caveat')
cav = checkers.Caveat(location='local', condition='true')
else:
if loc is None:
raise ValueError(
'no locator when adding third party caveat')
info = loc.third_party_info(cav.location)
root_key = os.urandom(24)
# Use the least supported version to encode the caveat.
if self._version < info.version:
info = ThirdPartyInfo(
version=self._version,
public_key=info.public_key,
)
caveat_info = encode_caveat(
cav.condition, root_key, info, key, self._namespace)
if info.version < VERSION_3:
# We're encoding for an earlier client or third party which does
# not understand bundled caveat info, so use the encoded
# caveat information as the caveat id.
id = caveat_info
else:
id = self._new_caveat_id(self._caveat_id_prefix)
self._caveat_data[id] = caveat_info
self._macaroon.add_third_party_caveat(cav.location, root_key, id) | python | def add_caveat(self, cav, key=None, loc=None):
'''Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a client self-discharge caveat using
the public key base64-encoded in the rest of the location. In this
case, the Condition field must be empty. The resulting third-party
caveat will encode the condition "true" encrypted with that public
key.
@param cav the checkers.Caveat to be added.
@param key the public key to encrypt third party caveat.
@param loc locator to find information on third parties when adding
third party caveats. It is expected to have a third_party_info method
that will be called with a location string and should return a
ThirdPartyInfo instance holding the requested information.
'''
if cav.location is None:
self._macaroon.add_first_party_caveat(
self.namespace.resolve_caveat(cav).condition)
return
if key is None:
raise ValueError(
'no private key to encrypt third party caveat')
local_info = _parse_local_location(cav.location)
if local_info is not None:
info = local_info
if cav.condition is not '':
raise ValueError(
'cannot specify caveat condition in '
'local third-party caveat')
cav = checkers.Caveat(location='local', condition='true')
else:
if loc is None:
raise ValueError(
'no locator when adding third party caveat')
info = loc.third_party_info(cav.location)
root_key = os.urandom(24)
# Use the least supported version to encode the caveat.
if self._version < info.version:
info = ThirdPartyInfo(
version=self._version,
public_key=info.public_key,
)
caveat_info = encode_caveat(
cav.condition, root_key, info, key, self._namespace)
if info.version < VERSION_3:
# We're encoding for an earlier client or third party which does
# not understand bundled caveat info, so use the encoded
# caveat information as the caveat id.
id = caveat_info
else:
id = self._new_caveat_id(self._caveat_id_prefix)
self._caveat_data[id] = caveat_info
self._macaroon.add_third_party_caveat(cav.location, root_key, id) | [
"def",
"add_caveat",
"(",
"self",
",",
"cav",
",",
"key",
"=",
"None",
",",
"loc",
"=",
"None",
")",
":",
"if",
"cav",
".",
"location",
"is",
"None",
":",
"self",
".",
"_macaroon",
".",
"add_first_party_caveat",
"(",
"self",
".",
"namespace",
".",
"resolve_caveat",
"(",
"cav",
")",
".",
"condition",
")",
"return",
"if",
"key",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'no private key to encrypt third party caveat'",
")",
"local_info",
"=",
"_parse_local_location",
"(",
"cav",
".",
"location",
")",
"if",
"local_info",
"is",
"not",
"None",
":",
"info",
"=",
"local_info",
"if",
"cav",
".",
"condition",
"is",
"not",
"''",
":",
"raise",
"ValueError",
"(",
"'cannot specify caveat condition in '",
"'local third-party caveat'",
")",
"cav",
"=",
"checkers",
".",
"Caveat",
"(",
"location",
"=",
"'local'",
",",
"condition",
"=",
"'true'",
")",
"else",
":",
"if",
"loc",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'no locator when adding third party caveat'",
")",
"info",
"=",
"loc",
".",
"third_party_info",
"(",
"cav",
".",
"location",
")",
"root_key",
"=",
"os",
".",
"urandom",
"(",
"24",
")",
"# Use the least supported version to encode the caveat.",
"if",
"self",
".",
"_version",
"<",
"info",
".",
"version",
":",
"info",
"=",
"ThirdPartyInfo",
"(",
"version",
"=",
"self",
".",
"_version",
",",
"public_key",
"=",
"info",
".",
"public_key",
",",
")",
"caveat_info",
"=",
"encode_caveat",
"(",
"cav",
".",
"condition",
",",
"root_key",
",",
"info",
",",
"key",
",",
"self",
".",
"_namespace",
")",
"if",
"info",
".",
"version",
"<",
"VERSION_3",
":",
"# We're encoding for an earlier client or third party which does",
"# not understand bundled caveat info, so use the encoded",
"# caveat information as the caveat id.",
"id",
"=",
"caveat_info",
"else",
":",
"id",
"=",
"self",
".",
"_new_caveat_id",
"(",
"self",
".",
"_caveat_id_prefix",
")",
"self",
".",
"_caveat_data",
"[",
"id",
"]",
"=",
"caveat_info",
"self",
".",
"_macaroon",
".",
"add_third_party_caveat",
"(",
"cav",
".",
"location",
",",
"root_key",
",",
"id",
")"
] | Add a caveat to the macaroon.
It encrypts it using the given key pair
and by looking up the location using the given locator.
As a special case, if the caveat's Location field has the prefix
"local " the caveat is added as a client self-discharge caveat using
the public key base64-encoded in the rest of the location. In this
case, the Condition field must be empty. The resulting third-party
caveat will encode the condition "true" encrypted with that public
key.
@param cav the checkers.Caveat to be added.
@param key the public key to encrypt third party caveat.
@param loc locator to find information on third parties when adding
third party caveats. It is expected to have a third_party_info method
that will be called with a location string and should return a
ThirdPartyInfo instance holding the requested information. | [
"Add",
"a",
"caveat",
"to",
"the",
"macaroon",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L90-L150 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | Macaroon.add_caveats | def add_caveats(self, cavs, key, loc):
'''Add an array of caveats to the macaroon.
This method does not mutate the current object.
@param cavs arrary of caveats.
@param key the PublicKey to encrypt third party caveat.
@param loc locator to find the location object that has a method
third_party_info.
'''
if cavs is None:
return
for cav in cavs:
self.add_caveat(cav, key, loc) | python | def add_caveats(self, cavs, key, loc):
'''Add an array of caveats to the macaroon.
This method does not mutate the current object.
@param cavs arrary of caveats.
@param key the PublicKey to encrypt third party caveat.
@param loc locator to find the location object that has a method
third_party_info.
'''
if cavs is None:
return
for cav in cavs:
self.add_caveat(cav, key, loc) | [
"def",
"add_caveats",
"(",
"self",
",",
"cavs",
",",
"key",
",",
"loc",
")",
":",
"if",
"cavs",
"is",
"None",
":",
"return",
"for",
"cav",
"in",
"cavs",
":",
"self",
".",
"add_caveat",
"(",
"cav",
",",
"key",
",",
"loc",
")"
] | Add an array of caveats to the macaroon.
This method does not mutate the current object.
@param cavs arrary of caveats.
@param key the PublicKey to encrypt third party caveat.
@param loc locator to find the location object that has a method
third_party_info. | [
"Add",
"an",
"array",
"of",
"caveats",
"to",
"the",
"macaroon",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L152-L164 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | Macaroon.to_dict | def to_dict(self):
'''Return a dict representation of the macaroon data in JSON format.
@return a dict
'''
if self.version < VERSION_3:
if len(self._caveat_data) > 0:
raise ValueError('cannot serialize pre-version3 macaroon with '
'external caveat data')
return json.loads(self._macaroon.serialize(
json_serializer.JsonSerializer()))
serialized = {
'm': json.loads(self._macaroon.serialize(
json_serializer.JsonSerializer())),
'v': self._version,
}
if self._namespace is not None:
serialized['ns'] = self._namespace.serialize_text().decode('utf-8')
caveat_data = {}
for id in self._caveat_data:
key = base64.b64encode(id).decode('utf-8')
value = base64.b64encode(self._caveat_data[id]).decode('utf-8')
caveat_data[key] = value
if len(caveat_data) > 0:
serialized['cdata'] = caveat_data
return serialized | python | def to_dict(self):
'''Return a dict representation of the macaroon data in JSON format.
@return a dict
'''
if self.version < VERSION_3:
if len(self._caveat_data) > 0:
raise ValueError('cannot serialize pre-version3 macaroon with '
'external caveat data')
return json.loads(self._macaroon.serialize(
json_serializer.JsonSerializer()))
serialized = {
'm': json.loads(self._macaroon.serialize(
json_serializer.JsonSerializer())),
'v': self._version,
}
if self._namespace is not None:
serialized['ns'] = self._namespace.serialize_text().decode('utf-8')
caveat_data = {}
for id in self._caveat_data:
key = base64.b64encode(id).decode('utf-8')
value = base64.b64encode(self._caveat_data[id]).decode('utf-8')
caveat_data[key] = value
if len(caveat_data) > 0:
serialized['cdata'] = caveat_data
return serialized | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"version",
"<",
"VERSION_3",
":",
"if",
"len",
"(",
"self",
".",
"_caveat_data",
")",
">",
"0",
":",
"raise",
"ValueError",
"(",
"'cannot serialize pre-version3 macaroon with '",
"'external caveat data'",
")",
"return",
"json",
".",
"loads",
"(",
"self",
".",
"_macaroon",
".",
"serialize",
"(",
"json_serializer",
".",
"JsonSerializer",
"(",
")",
")",
")",
"serialized",
"=",
"{",
"'m'",
":",
"json",
".",
"loads",
"(",
"self",
".",
"_macaroon",
".",
"serialize",
"(",
"json_serializer",
".",
"JsonSerializer",
"(",
")",
")",
")",
",",
"'v'",
":",
"self",
".",
"_version",
",",
"}",
"if",
"self",
".",
"_namespace",
"is",
"not",
"None",
":",
"serialized",
"[",
"'ns'",
"]",
"=",
"self",
".",
"_namespace",
".",
"serialize_text",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"caveat_data",
"=",
"{",
"}",
"for",
"id",
"in",
"self",
".",
"_caveat_data",
":",
"key",
"=",
"base64",
".",
"b64encode",
"(",
"id",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"value",
"=",
"base64",
".",
"b64encode",
"(",
"self",
".",
"_caveat_data",
"[",
"id",
"]",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"caveat_data",
"[",
"key",
"]",
"=",
"value",
"if",
"len",
"(",
"caveat_data",
")",
">",
"0",
":",
"serialized",
"[",
"'cdata'",
"]",
"=",
"caveat_data",
"return",
"serialized"
] | Return a dict representation of the macaroon data in JSON format.
@return a dict | [
"Return",
"a",
"dict",
"representation",
"of",
"the",
"macaroon",
"data",
"in",
"JSON",
"format",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L172-L196 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | Macaroon.from_dict | def from_dict(cls, json_dict):
'''Return a macaroon obtained from the given dictionary as
deserialized from JSON.
@param json_dict The deserialized JSON object.
'''
json_macaroon = json_dict.get('m')
if json_macaroon is None:
# Try the v1 format if we don't have a macaroon field.
m = pymacaroons.Macaroon.deserialize(
json.dumps(json_dict), json_serializer.JsonSerializer())
macaroon = Macaroon(root_key=None, id=None,
namespace=legacy_namespace(),
version=_bakery_version(m.version))
macaroon._macaroon = m
return macaroon
version = json_dict.get('v', None)
if version is None:
raise ValueError('no version specified')
if (version < VERSION_3 or
version > LATEST_VERSION):
raise ValueError('unknown bakery version {}'.format(version))
m = pymacaroons.Macaroon.deserialize(json.dumps(json_macaroon),
json_serializer.JsonSerializer())
if m.version != macaroon_version(version):
raise ValueError(
'underlying macaroon has inconsistent version; '
'got {} want {}'.format(m.version, macaroon_version(version)))
namespace = checkers.deserialize_namespace(json_dict.get('ns'))
cdata = json_dict.get('cdata', {})
caveat_data = {}
for id64 in cdata:
id = b64decode(id64)
data = b64decode(cdata[id64])
caveat_data[id] = data
macaroon = Macaroon(root_key=None, id=None,
namespace=namespace,
version=version)
macaroon._caveat_data = caveat_data
macaroon._macaroon = m
return macaroon | python | def from_dict(cls, json_dict):
'''Return a macaroon obtained from the given dictionary as
deserialized from JSON.
@param json_dict The deserialized JSON object.
'''
json_macaroon = json_dict.get('m')
if json_macaroon is None:
# Try the v1 format if we don't have a macaroon field.
m = pymacaroons.Macaroon.deserialize(
json.dumps(json_dict), json_serializer.JsonSerializer())
macaroon = Macaroon(root_key=None, id=None,
namespace=legacy_namespace(),
version=_bakery_version(m.version))
macaroon._macaroon = m
return macaroon
version = json_dict.get('v', None)
if version is None:
raise ValueError('no version specified')
if (version < VERSION_3 or
version > LATEST_VERSION):
raise ValueError('unknown bakery version {}'.format(version))
m = pymacaroons.Macaroon.deserialize(json.dumps(json_macaroon),
json_serializer.JsonSerializer())
if m.version != macaroon_version(version):
raise ValueError(
'underlying macaroon has inconsistent version; '
'got {} want {}'.format(m.version, macaroon_version(version)))
namespace = checkers.deserialize_namespace(json_dict.get('ns'))
cdata = json_dict.get('cdata', {})
caveat_data = {}
for id64 in cdata:
id = b64decode(id64)
data = b64decode(cdata[id64])
caveat_data[id] = data
macaroon = Macaroon(root_key=None, id=None,
namespace=namespace,
version=version)
macaroon._caveat_data = caveat_data
macaroon._macaroon = m
return macaroon | [
"def",
"from_dict",
"(",
"cls",
",",
"json_dict",
")",
":",
"json_macaroon",
"=",
"json_dict",
".",
"get",
"(",
"'m'",
")",
"if",
"json_macaroon",
"is",
"None",
":",
"# Try the v1 format if we don't have a macaroon field.",
"m",
"=",
"pymacaroons",
".",
"Macaroon",
".",
"deserialize",
"(",
"json",
".",
"dumps",
"(",
"json_dict",
")",
",",
"json_serializer",
".",
"JsonSerializer",
"(",
")",
")",
"macaroon",
"=",
"Macaroon",
"(",
"root_key",
"=",
"None",
",",
"id",
"=",
"None",
",",
"namespace",
"=",
"legacy_namespace",
"(",
")",
",",
"version",
"=",
"_bakery_version",
"(",
"m",
".",
"version",
")",
")",
"macaroon",
".",
"_macaroon",
"=",
"m",
"return",
"macaroon",
"version",
"=",
"json_dict",
".",
"get",
"(",
"'v'",
",",
"None",
")",
"if",
"version",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'no version specified'",
")",
"if",
"(",
"version",
"<",
"VERSION_3",
"or",
"version",
">",
"LATEST_VERSION",
")",
":",
"raise",
"ValueError",
"(",
"'unknown bakery version {}'",
".",
"format",
"(",
"version",
")",
")",
"m",
"=",
"pymacaroons",
".",
"Macaroon",
".",
"deserialize",
"(",
"json",
".",
"dumps",
"(",
"json_macaroon",
")",
",",
"json_serializer",
".",
"JsonSerializer",
"(",
")",
")",
"if",
"m",
".",
"version",
"!=",
"macaroon_version",
"(",
"version",
")",
":",
"raise",
"ValueError",
"(",
"'underlying macaroon has inconsistent version; '",
"'got {} want {}'",
".",
"format",
"(",
"m",
".",
"version",
",",
"macaroon_version",
"(",
"version",
")",
")",
")",
"namespace",
"=",
"checkers",
".",
"deserialize_namespace",
"(",
"json_dict",
".",
"get",
"(",
"'ns'",
")",
")",
"cdata",
"=",
"json_dict",
".",
"get",
"(",
"'cdata'",
",",
"{",
"}",
")",
"caveat_data",
"=",
"{",
"}",
"for",
"id64",
"in",
"cdata",
":",
"id",
"=",
"b64decode",
"(",
"id64",
")",
"data",
"=",
"b64decode",
"(",
"cdata",
"[",
"id64",
"]",
")",
"caveat_data",
"[",
"id",
"]",
"=",
"data",
"macaroon",
"=",
"Macaroon",
"(",
"root_key",
"=",
"None",
",",
"id",
"=",
"None",
",",
"namespace",
"=",
"namespace",
",",
"version",
"=",
"version",
")",
"macaroon",
".",
"_caveat_data",
"=",
"caveat_data",
"macaroon",
".",
"_macaroon",
"=",
"m",
"return",
"macaroon"
] | Return a macaroon obtained from the given dictionary as
deserialized from JSON.
@param json_dict The deserialized JSON object. | [
"Return",
"a",
"macaroon",
"obtained",
"from",
"the",
"given",
"dictionary",
"as",
"deserialized",
"from",
"JSON",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L199-L239 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | Macaroon.deserialize_json | def deserialize_json(cls, serialized_json):
'''Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon}
'''
serialized = json.loads(serialized_json)
return Macaroon.from_dict(serialized) | python | def deserialize_json(cls, serialized_json):
'''Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon}
'''
serialized = json.loads(serialized_json)
return Macaroon.from_dict(serialized) | [
"def",
"deserialize_json",
"(",
"cls",
",",
"serialized_json",
")",
":",
"serialized",
"=",
"json",
".",
"loads",
"(",
"serialized_json",
")",
"return",
"Macaroon",
".",
"from_dict",
"(",
"serialized",
")"
] | Return a macaroon deserialized from a string
@param serialized_json The string to decode {str}
@return {Macaroon} | [
"Return",
"a",
"macaroon",
"deserialized",
"from",
"a",
"string"
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L242-L248 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/bakery/_macaroon.py | Macaroon._new_caveat_id | def _new_caveat_id(self, base):
'''Return a third party caveat id
This does not duplicate any third party caveat ids already inside
macaroon. If base is non-empty, it is used as the id prefix.
@param base bytes
@return bytes
'''
id = bytearray()
if len(base) > 0:
id.extend(base)
else:
# Add a version byte to the caveat id. Technically
# this is unnecessary as the caveat-decoding logic
# that looks at versions should never see this id,
# but if the caveat payload isn't provided with the
# payload, having this version gives a strong indication
# that the payload has been omitted so we can produce
# a better error for the user.
id.append(VERSION_3)
# Iterate through integers looking for one that isn't already used,
# starting from n so that if everyone is using this same algorithm,
# we'll only perform one iteration.
i = len(self._caveat_data)
caveats = self._macaroon.caveats
while True:
# We append a varint to the end of the id and assume that
# any client that's created the id that we're using as a base
# is using similar conventions - in the worst case they might
# end up with a duplicate third party caveat id and thus create
# a macaroon that cannot be discharged.
temp = id[:]
encode_uvarint(i, temp)
found = False
for cav in caveats:
if (cav.verification_key_id is not None
and cav.caveat_id == temp):
found = True
break
if not found:
return bytes(temp)
i += 1 | python | def _new_caveat_id(self, base):
'''Return a third party caveat id
This does not duplicate any third party caveat ids already inside
macaroon. If base is non-empty, it is used as the id prefix.
@param base bytes
@return bytes
'''
id = bytearray()
if len(base) > 0:
id.extend(base)
else:
# Add a version byte to the caveat id. Technically
# this is unnecessary as the caveat-decoding logic
# that looks at versions should never see this id,
# but if the caveat payload isn't provided with the
# payload, having this version gives a strong indication
# that the payload has been omitted so we can produce
# a better error for the user.
id.append(VERSION_3)
# Iterate through integers looking for one that isn't already used,
# starting from n so that if everyone is using this same algorithm,
# we'll only perform one iteration.
i = len(self._caveat_data)
caveats = self._macaroon.caveats
while True:
# We append a varint to the end of the id and assume that
# any client that's created the id that we're using as a base
# is using similar conventions - in the worst case they might
# end up with a duplicate third party caveat id and thus create
# a macaroon that cannot be discharged.
temp = id[:]
encode_uvarint(i, temp)
found = False
for cav in caveats:
if (cav.verification_key_id is not None
and cav.caveat_id == temp):
found = True
break
if not found:
return bytes(temp)
i += 1 | [
"def",
"_new_caveat_id",
"(",
"self",
",",
"base",
")",
":",
"id",
"=",
"bytearray",
"(",
")",
"if",
"len",
"(",
"base",
")",
">",
"0",
":",
"id",
".",
"extend",
"(",
"base",
")",
"else",
":",
"# Add a version byte to the caveat id. Technically",
"# this is unnecessary as the caveat-decoding logic",
"# that looks at versions should never see this id,",
"# but if the caveat payload isn't provided with the",
"# payload, having this version gives a strong indication",
"# that the payload has been omitted so we can produce",
"# a better error for the user.",
"id",
".",
"append",
"(",
"VERSION_3",
")",
"# Iterate through integers looking for one that isn't already used,",
"# starting from n so that if everyone is using this same algorithm,",
"# we'll only perform one iteration.",
"i",
"=",
"len",
"(",
"self",
".",
"_caveat_data",
")",
"caveats",
"=",
"self",
".",
"_macaroon",
".",
"caveats",
"while",
"True",
":",
"# We append a varint to the end of the id and assume that",
"# any client that's created the id that we're using as a base",
"# is using similar conventions - in the worst case they might",
"# end up with a duplicate third party caveat id and thus create",
"# a macaroon that cannot be discharged.",
"temp",
"=",
"id",
"[",
":",
"]",
"encode_uvarint",
"(",
"i",
",",
"temp",
")",
"found",
"=",
"False",
"for",
"cav",
"in",
"caveats",
":",
"if",
"(",
"cav",
".",
"verification_key_id",
"is",
"not",
"None",
"and",
"cav",
".",
"caveat_id",
"==",
"temp",
")",
":",
"found",
"=",
"True",
"break",
"if",
"not",
"found",
":",
"return",
"bytes",
"(",
"temp",
")",
"i",
"+=",
"1"
] | Return a third party caveat id
This does not duplicate any third party caveat ids already inside
macaroon. If base is non-empty, it is used as the id prefix.
@param base bytes
@return bytes | [
"Return",
"a",
"third",
"party",
"caveat",
"id"
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/bakery/_macaroon.py#L250-L293 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_client.py | extract_macaroons | def extract_macaroons(headers_or_request):
''' Returns an array of any macaroons found in the given slice of cookies.
If the argument implements a get_header method, that will be used
instead of the get method to retrieve headers.
@param headers_or_request: dict of headers or a
urllib.request.Request-like object.
@return: A list of list of mpy macaroons
'''
def get_header(key, default=None):
try:
return headers_or_request.get_header(key, default)
except AttributeError:
return headers_or_request.get(key, default)
mss = []
def add_macaroon(data):
try:
data = utils.b64decode(data)
data_as_objs = json.loads(data.decode('utf-8'))
except ValueError:
return
ms = [utils.macaroon_from_dict(x) for x in data_as_objs]
mss.append(ms)
cookie_header = get_header('Cookie')
if cookie_header is not None:
cs = SimpleCookie()
# The cookie might be a unicode object, so convert it
# to ASCII. This may cause an exception under Python 2.
# TODO is that a problem?
cs.load(str(cookie_header))
for c in cs:
if c.startswith('macaroon-'):
add_macaroon(cs[c].value)
# Python doesn't make it easy to have multiple values for a
# key, so split the header instead, which is necessary
# for HTTP1.1 compatibility anyway (see RFC 7230, section 3.2.2)
macaroon_header = get_header('Macaroons')
if macaroon_header is not None:
for h in macaroon_header.split(','):
add_macaroon(h)
return mss | python | def extract_macaroons(headers_or_request):
''' Returns an array of any macaroons found in the given slice of cookies.
If the argument implements a get_header method, that will be used
instead of the get method to retrieve headers.
@param headers_or_request: dict of headers or a
urllib.request.Request-like object.
@return: A list of list of mpy macaroons
'''
def get_header(key, default=None):
try:
return headers_or_request.get_header(key, default)
except AttributeError:
return headers_or_request.get(key, default)
mss = []
def add_macaroon(data):
try:
data = utils.b64decode(data)
data_as_objs = json.loads(data.decode('utf-8'))
except ValueError:
return
ms = [utils.macaroon_from_dict(x) for x in data_as_objs]
mss.append(ms)
cookie_header = get_header('Cookie')
if cookie_header is not None:
cs = SimpleCookie()
# The cookie might be a unicode object, so convert it
# to ASCII. This may cause an exception under Python 2.
# TODO is that a problem?
cs.load(str(cookie_header))
for c in cs:
if c.startswith('macaroon-'):
add_macaroon(cs[c].value)
# Python doesn't make it easy to have multiple values for a
# key, so split the header instead, which is necessary
# for HTTP1.1 compatibility anyway (see RFC 7230, section 3.2.2)
macaroon_header = get_header('Macaroons')
if macaroon_header is not None:
for h in macaroon_header.split(','):
add_macaroon(h)
return mss | [
"def",
"extract_macaroons",
"(",
"headers_or_request",
")",
":",
"def",
"get_header",
"(",
"key",
",",
"default",
"=",
"None",
")",
":",
"try",
":",
"return",
"headers_or_request",
".",
"get_header",
"(",
"key",
",",
"default",
")",
"except",
"AttributeError",
":",
"return",
"headers_or_request",
".",
"get",
"(",
"key",
",",
"default",
")",
"mss",
"=",
"[",
"]",
"def",
"add_macaroon",
"(",
"data",
")",
":",
"try",
":",
"data",
"=",
"utils",
".",
"b64decode",
"(",
"data",
")",
"data_as_objs",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"except",
"ValueError",
":",
"return",
"ms",
"=",
"[",
"utils",
".",
"macaroon_from_dict",
"(",
"x",
")",
"for",
"x",
"in",
"data_as_objs",
"]",
"mss",
".",
"append",
"(",
"ms",
")",
"cookie_header",
"=",
"get_header",
"(",
"'Cookie'",
")",
"if",
"cookie_header",
"is",
"not",
"None",
":",
"cs",
"=",
"SimpleCookie",
"(",
")",
"# The cookie might be a unicode object, so convert it",
"# to ASCII. This may cause an exception under Python 2.",
"# TODO is that a problem?",
"cs",
".",
"load",
"(",
"str",
"(",
"cookie_header",
")",
")",
"for",
"c",
"in",
"cs",
":",
"if",
"c",
".",
"startswith",
"(",
"'macaroon-'",
")",
":",
"add_macaroon",
"(",
"cs",
"[",
"c",
"]",
".",
"value",
")",
"# Python doesn't make it easy to have multiple values for a",
"# key, so split the header instead, which is necessary",
"# for HTTP1.1 compatibility anyway (see RFC 7230, section 3.2.2)",
"macaroon_header",
"=",
"get_header",
"(",
"'Macaroons'",
")",
"if",
"macaroon_header",
"is",
"not",
"None",
":",
"for",
"h",
"in",
"macaroon_header",
".",
"split",
"(",
"','",
")",
":",
"add_macaroon",
"(",
"h",
")",
"return",
"mss"
] | Returns an array of any macaroons found in the given slice of cookies.
If the argument implements a get_header method, that will be used
instead of the get method to retrieve headers.
@param headers_or_request: dict of headers or a
urllib.request.Request-like object.
@return: A list of list of mpy macaroons | [
"Returns",
"an",
"array",
"of",
"any",
"macaroons",
"found",
"in",
"the",
"given",
"slice",
"of",
"cookies",
".",
"If",
"the",
"argument",
"implements",
"a",
"get_header",
"method",
"that",
"will",
"be",
"used",
"instead",
"of",
"the",
"get",
"method",
"to",
"retrieve",
"headers",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L302-L344 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_client.py | _wait_for_macaroon | def _wait_for_macaroon(wait_url):
''' Returns a macaroon from a legacy wait endpoint.
'''
headers = {
BAKERY_PROTOCOL_HEADER: str(bakery.LATEST_VERSION)
}
resp = requests.get(url=wait_url, headers=headers)
if resp.status_code != 200:
raise InteractionError('cannot get {}'.format(wait_url))
return bakery.Macaroon.from_dict(resp.json().get('Macaroon')) | python | def _wait_for_macaroon(wait_url):
''' Returns a macaroon from a legacy wait endpoint.
'''
headers = {
BAKERY_PROTOCOL_HEADER: str(bakery.LATEST_VERSION)
}
resp = requests.get(url=wait_url, headers=headers)
if resp.status_code != 200:
raise InteractionError('cannot get {}'.format(wait_url))
return bakery.Macaroon.from_dict(resp.json().get('Macaroon')) | [
"def",
"_wait_for_macaroon",
"(",
"wait_url",
")",
":",
"headers",
"=",
"{",
"BAKERY_PROTOCOL_HEADER",
":",
"str",
"(",
"bakery",
".",
"LATEST_VERSION",
")",
"}",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
"=",
"wait_url",
",",
"headers",
"=",
"headers",
")",
"if",
"resp",
".",
"status_code",
"!=",
"200",
":",
"raise",
"InteractionError",
"(",
"'cannot get {}'",
".",
"format",
"(",
"wait_url",
")",
")",
"return",
"bakery",
".",
"Macaroon",
".",
"from_dict",
"(",
"resp",
".",
"json",
"(",
")",
".",
"get",
"(",
"'Macaroon'",
")",
")"
] | Returns a macaroon from a legacy wait endpoint. | [
"Returns",
"a",
"macaroon",
"from",
"a",
"legacy",
"wait",
"endpoint",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L361-L371 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_client.py | Client.handle_error | def handle_error(self, error, url):
'''Try to resolve the given error, which should be a response
to the given URL, by discharging any macaroon contained in
it. That is, if error.code is ERR_DISCHARGE_REQUIRED
then it will try to discharge err.info.macaroon. If the discharge
succeeds, the discharged macaroon will be saved to the client's cookie
jar, otherwise an exception will be raised.
'''
if error.info is None or error.info.macaroon is None:
raise BakeryException('unable to read info in discharge error '
'response')
discharges = bakery.discharge_all(
error.info.macaroon,
self.acquire_discharge,
self.key,
)
macaroons = '[' + ','.join(map(utils.macaroon_to_json_string,
discharges)) + ']'
all_macaroons = base64.urlsafe_b64encode(utils.to_bytes(macaroons))
full_path = urljoin(url, error.info.macaroon_path)
if error.info.cookie_name_suffix is not None:
name = 'macaroon-' + error.info.cookie_name_suffix
else:
name = 'macaroon-auth'
expires = checkers.macaroons_expiry_time(checkers.Namespace(), discharges)
self.cookies.set_cookie(utils.cookie(
name=name,
value=all_macaroons.decode('ascii'),
url=full_path,
expires=expires,
)) | python | def handle_error(self, error, url):
'''Try to resolve the given error, which should be a response
to the given URL, by discharging any macaroon contained in
it. That is, if error.code is ERR_DISCHARGE_REQUIRED
then it will try to discharge err.info.macaroon. If the discharge
succeeds, the discharged macaroon will be saved to the client's cookie
jar, otherwise an exception will be raised.
'''
if error.info is None or error.info.macaroon is None:
raise BakeryException('unable to read info in discharge error '
'response')
discharges = bakery.discharge_all(
error.info.macaroon,
self.acquire_discharge,
self.key,
)
macaroons = '[' + ','.join(map(utils.macaroon_to_json_string,
discharges)) + ']'
all_macaroons = base64.urlsafe_b64encode(utils.to_bytes(macaroons))
full_path = urljoin(url, error.info.macaroon_path)
if error.info.cookie_name_suffix is not None:
name = 'macaroon-' + error.info.cookie_name_suffix
else:
name = 'macaroon-auth'
expires = checkers.macaroons_expiry_time(checkers.Namespace(), discharges)
self.cookies.set_cookie(utils.cookie(
name=name,
value=all_macaroons.decode('ascii'),
url=full_path,
expires=expires,
)) | [
"def",
"handle_error",
"(",
"self",
",",
"error",
",",
"url",
")",
":",
"if",
"error",
".",
"info",
"is",
"None",
"or",
"error",
".",
"info",
".",
"macaroon",
"is",
"None",
":",
"raise",
"BakeryException",
"(",
"'unable to read info in discharge error '",
"'response'",
")",
"discharges",
"=",
"bakery",
".",
"discharge_all",
"(",
"error",
".",
"info",
".",
"macaroon",
",",
"self",
".",
"acquire_discharge",
",",
"self",
".",
"key",
",",
")",
"macaroons",
"=",
"'['",
"+",
"','",
".",
"join",
"(",
"map",
"(",
"utils",
".",
"macaroon_to_json_string",
",",
"discharges",
")",
")",
"+",
"']'",
"all_macaroons",
"=",
"base64",
".",
"urlsafe_b64encode",
"(",
"utils",
".",
"to_bytes",
"(",
"macaroons",
")",
")",
"full_path",
"=",
"urljoin",
"(",
"url",
",",
"error",
".",
"info",
".",
"macaroon_path",
")",
"if",
"error",
".",
"info",
".",
"cookie_name_suffix",
"is",
"not",
"None",
":",
"name",
"=",
"'macaroon-'",
"+",
"error",
".",
"info",
".",
"cookie_name_suffix",
"else",
":",
"name",
"=",
"'macaroon-auth'",
"expires",
"=",
"checkers",
".",
"macaroons_expiry_time",
"(",
"checkers",
".",
"Namespace",
"(",
")",
",",
"discharges",
")",
"self",
".",
"cookies",
".",
"set_cookie",
"(",
"utils",
".",
"cookie",
"(",
"name",
"=",
"name",
",",
"value",
"=",
"all_macaroons",
".",
"decode",
"(",
"'ascii'",
")",
",",
"url",
"=",
"full_path",
",",
"expires",
"=",
"expires",
",",
")",
")"
] | Try to resolve the given error, which should be a response
to the given URL, by discharging any macaroon contained in
it. That is, if error.code is ERR_DISCHARGE_REQUIRED
then it will try to discharge err.info.macaroon. If the discharge
succeeds, the discharged macaroon will be saved to the client's cookie
jar, otherwise an exception will be raised. | [
"Try",
"to",
"resolve",
"the",
"given",
"error",
"which",
"should",
"be",
"a",
"response",
"to",
"the",
"given",
"URL",
"by",
"discharging",
"any",
"macaroon",
"contained",
"in",
"it",
".",
"That",
"is",
"if",
"error",
".",
"code",
"is",
"ERR_DISCHARGE_REQUIRED",
"then",
"it",
"will",
"try",
"to",
"discharge",
"err",
".",
"info",
".",
"macaroon",
".",
"If",
"the",
"discharge",
"succeeds",
"the",
"discharged",
"macaroon",
"will",
"be",
"saved",
"to",
"the",
"client",
"s",
"cookie",
"jar",
"otherwise",
"an",
"exception",
"will",
"be",
"raised",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L89-L121 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_client.py | Client.acquire_discharge | def acquire_discharge(self, cav, payload):
''' Request a discharge macaroon from the caveat location
as an HTTP URL.
@param cav Third party {pymacaroons.Caveat} to be discharged.
@param payload External caveat data {bytes}.
@return The acquired macaroon {macaroonbakery.Macaroon}
'''
resp = self._acquire_discharge_with_token(cav, payload, None)
# TODO Fabrice what is the other http response possible ??
if resp.status_code == 200:
return bakery.Macaroon.from_dict(resp.json().get('Macaroon'))
cause = Error.from_dict(resp.json())
if cause.code != ERR_INTERACTION_REQUIRED:
raise DischargeError(cause.message)
if cause.info is None:
raise DischargeError(
'interaction-required response with no info: {}'.format(
resp.json())
)
loc = cav.location
if not loc.endswith('/'):
loc = loc + '/'
token, m = self._interact(loc, cause, payload)
if m is not None:
# We've acquired the macaroon directly via legacy interaction.
return m
# Try to acquire the discharge again, but this time with
# the token acquired by the interaction method.
resp = self._acquire_discharge_with_token(cav, payload, token)
if resp.status_code == 200:
return bakery.Macaroon.from_dict(resp.json().get('Macaroon'))
else:
raise DischargeError(
'discharge failed with code {}'.format(resp.status_code)) | python | def acquire_discharge(self, cav, payload):
''' Request a discharge macaroon from the caveat location
as an HTTP URL.
@param cav Third party {pymacaroons.Caveat} to be discharged.
@param payload External caveat data {bytes}.
@return The acquired macaroon {macaroonbakery.Macaroon}
'''
resp = self._acquire_discharge_with_token(cav, payload, None)
# TODO Fabrice what is the other http response possible ??
if resp.status_code == 200:
return bakery.Macaroon.from_dict(resp.json().get('Macaroon'))
cause = Error.from_dict(resp.json())
if cause.code != ERR_INTERACTION_REQUIRED:
raise DischargeError(cause.message)
if cause.info is None:
raise DischargeError(
'interaction-required response with no info: {}'.format(
resp.json())
)
loc = cav.location
if not loc.endswith('/'):
loc = loc + '/'
token, m = self._interact(loc, cause, payload)
if m is not None:
# We've acquired the macaroon directly via legacy interaction.
return m
# Try to acquire the discharge again, but this time with
# the token acquired by the interaction method.
resp = self._acquire_discharge_with_token(cav, payload, token)
if resp.status_code == 200:
return bakery.Macaroon.from_dict(resp.json().get('Macaroon'))
else:
raise DischargeError(
'discharge failed with code {}'.format(resp.status_code)) | [
"def",
"acquire_discharge",
"(",
"self",
",",
"cav",
",",
"payload",
")",
":",
"resp",
"=",
"self",
".",
"_acquire_discharge_with_token",
"(",
"cav",
",",
"payload",
",",
"None",
")",
"# TODO Fabrice what is the other http response possible ??",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"return",
"bakery",
".",
"Macaroon",
".",
"from_dict",
"(",
"resp",
".",
"json",
"(",
")",
".",
"get",
"(",
"'Macaroon'",
")",
")",
"cause",
"=",
"Error",
".",
"from_dict",
"(",
"resp",
".",
"json",
"(",
")",
")",
"if",
"cause",
".",
"code",
"!=",
"ERR_INTERACTION_REQUIRED",
":",
"raise",
"DischargeError",
"(",
"cause",
".",
"message",
")",
"if",
"cause",
".",
"info",
"is",
"None",
":",
"raise",
"DischargeError",
"(",
"'interaction-required response with no info: {}'",
".",
"format",
"(",
"resp",
".",
"json",
"(",
")",
")",
")",
"loc",
"=",
"cav",
".",
"location",
"if",
"not",
"loc",
".",
"endswith",
"(",
"'/'",
")",
":",
"loc",
"=",
"loc",
"+",
"'/'",
"token",
",",
"m",
"=",
"self",
".",
"_interact",
"(",
"loc",
",",
"cause",
",",
"payload",
")",
"if",
"m",
"is",
"not",
"None",
":",
"# We've acquired the macaroon directly via legacy interaction.",
"return",
"m",
"# Try to acquire the discharge again, but this time with",
"# the token acquired by the interaction method.",
"resp",
"=",
"self",
".",
"_acquire_discharge_with_token",
"(",
"cav",
",",
"payload",
",",
"token",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"return",
"bakery",
".",
"Macaroon",
".",
"from_dict",
"(",
"resp",
".",
"json",
"(",
")",
".",
"get",
"(",
"'Macaroon'",
")",
")",
"else",
":",
"raise",
"DischargeError",
"(",
"'discharge failed with code {}'",
".",
"format",
"(",
"resp",
".",
"status_code",
")",
")"
] | Request a discharge macaroon from the caveat location
as an HTTP URL.
@param cav Third party {pymacaroons.Caveat} to be discharged.
@param payload External caveat data {bytes}.
@return The acquired macaroon {macaroonbakery.Macaroon} | [
"Request",
"a",
"discharge",
"macaroon",
"from",
"the",
"caveat",
"location",
"as",
"an",
"HTTP",
"URL",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L123-L156 | train |
go-macaroon-bakery/py-macaroon-bakery | macaroonbakery/httpbakery/_client.py | Client._interact | def _interact(self, location, error_info, payload):
'''Gathers a macaroon by directing the user to interact with a
web page. The error_info argument holds the interaction-required
error response.
@return DischargeToken, bakery.Macaroon
'''
if (self._interaction_methods is None or
len(self._interaction_methods) == 0):
raise InteractionError('interaction required but not possible')
# TODO(rogpeppe) make the robust against a wider range of error info.
if error_info.info.interaction_methods is None and \
error_info.info.visit_url is not None:
# It's an old-style error; deal with it differently.
return None, self._legacy_interact(location, error_info)
for interactor in self._interaction_methods:
found = error_info.info.interaction_methods.get(interactor.kind())
if found is None:
continue
try:
token = interactor.interact(self, location, error_info)
except InteractionMethodNotFound:
continue
if token is None:
raise InteractionError('interaction method returned an empty '
'token')
return token, None
raise InteractionError('no supported interaction method') | python | def _interact(self, location, error_info, payload):
'''Gathers a macaroon by directing the user to interact with a
web page. The error_info argument holds the interaction-required
error response.
@return DischargeToken, bakery.Macaroon
'''
if (self._interaction_methods is None or
len(self._interaction_methods) == 0):
raise InteractionError('interaction required but not possible')
# TODO(rogpeppe) make the robust against a wider range of error info.
if error_info.info.interaction_methods is None and \
error_info.info.visit_url is not None:
# It's an old-style error; deal with it differently.
return None, self._legacy_interact(location, error_info)
for interactor in self._interaction_methods:
found = error_info.info.interaction_methods.get(interactor.kind())
if found is None:
continue
try:
token = interactor.interact(self, location, error_info)
except InteractionMethodNotFound:
continue
if token is None:
raise InteractionError('interaction method returned an empty '
'token')
return token, None
raise InteractionError('no supported interaction method') | [
"def",
"_interact",
"(",
"self",
",",
"location",
",",
"error_info",
",",
"payload",
")",
":",
"if",
"(",
"self",
".",
"_interaction_methods",
"is",
"None",
"or",
"len",
"(",
"self",
".",
"_interaction_methods",
")",
"==",
"0",
")",
":",
"raise",
"InteractionError",
"(",
"'interaction required but not possible'",
")",
"# TODO(rogpeppe) make the robust against a wider range of error info.",
"if",
"error_info",
".",
"info",
".",
"interaction_methods",
"is",
"None",
"and",
"error_info",
".",
"info",
".",
"visit_url",
"is",
"not",
"None",
":",
"# It's an old-style error; deal with it differently.",
"return",
"None",
",",
"self",
".",
"_legacy_interact",
"(",
"location",
",",
"error_info",
")",
"for",
"interactor",
"in",
"self",
".",
"_interaction_methods",
":",
"found",
"=",
"error_info",
".",
"info",
".",
"interaction_methods",
".",
"get",
"(",
"interactor",
".",
"kind",
"(",
")",
")",
"if",
"found",
"is",
"None",
":",
"continue",
"try",
":",
"token",
"=",
"interactor",
".",
"interact",
"(",
"self",
",",
"location",
",",
"error_info",
")",
"except",
"InteractionMethodNotFound",
":",
"continue",
"if",
"token",
"is",
"None",
":",
"raise",
"InteractionError",
"(",
"'interaction method returned an empty '",
"'token'",
")",
"return",
"token",
",",
"None",
"raise",
"InteractionError",
"(",
"'no supported interaction method'",
")"
] | Gathers a macaroon by directing the user to interact with a
web page. The error_info argument holds the interaction-required
error response.
@return DischargeToken, bakery.Macaroon | [
"Gathers",
"a",
"macaroon",
"by",
"directing",
"the",
"user",
"to",
"interact",
"with",
"a",
"web",
"page",
".",
"The",
"error_info",
"argument",
"holds",
"the",
"interaction",
"-",
"required",
"error",
"response",
"."
] | 63ce1ef1dabe816eb8aaec48fbb46761c34ddf77 | https://github.com/go-macaroon-bakery/py-macaroon-bakery/blob/63ce1ef1dabe816eb8aaec48fbb46761c34ddf77/macaroonbakery/httpbakery/_client.py#L173-L200 | train |
Phyks/libbmc | libbmc/bibtex.py | dict2bibtex | def dict2bibtex(data):
"""
Convert a single BibTeX entry dict to a BibTeX string.
:param data: A dict representing BibTeX entry, as the ones from \
``bibtexparser.BibDatabase.entries`` output.
:return: A formatted BibTeX string.
"""
bibtex = '@' + data['ENTRYTYPE'] + '{' + data['ID'] + ",\n"
for field in [i for i in sorted(data) if i not in ['ENTRYTYPE', 'ID']]:
bibtex += "\t" + field + "={" + data[field] + "},\n"
bibtex += "}\n\n"
return bibtex | python | def dict2bibtex(data):
"""
Convert a single BibTeX entry dict to a BibTeX string.
:param data: A dict representing BibTeX entry, as the ones from \
``bibtexparser.BibDatabase.entries`` output.
:return: A formatted BibTeX string.
"""
bibtex = '@' + data['ENTRYTYPE'] + '{' + data['ID'] + ",\n"
for field in [i for i in sorted(data) if i not in ['ENTRYTYPE', 'ID']]:
bibtex += "\t" + field + "={" + data[field] + "},\n"
bibtex += "}\n\n"
return bibtex | [
"def",
"dict2bibtex",
"(",
"data",
")",
":",
"bibtex",
"=",
"'@'",
"+",
"data",
"[",
"'ENTRYTYPE'",
"]",
"+",
"'{'",
"+",
"data",
"[",
"'ID'",
"]",
"+",
"\",\\n\"",
"for",
"field",
"in",
"[",
"i",
"for",
"i",
"in",
"sorted",
"(",
"data",
")",
"if",
"i",
"not",
"in",
"[",
"'ENTRYTYPE'",
",",
"'ID'",
"]",
"]",
":",
"bibtex",
"+=",
"\"\\t\"",
"+",
"field",
"+",
"\"={\"",
"+",
"data",
"[",
"field",
"]",
"+",
"\"},\\n\"",
"bibtex",
"+=",
"\"}\\n\\n\"",
"return",
"bibtex"
] | Convert a single BibTeX entry dict to a BibTeX string.
:param data: A dict representing BibTeX entry, as the ones from \
``bibtexparser.BibDatabase.entries`` output.
:return: A formatted BibTeX string. | [
"Convert",
"a",
"single",
"BibTeX",
"entry",
"dict",
"to",
"a",
"BibTeX",
"string",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L17-L30 | train |
Phyks/libbmc | libbmc/bibtex.py | write | def write(filename, data):
"""
Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object.
"""
with open(filename, 'w') as fh:
fh.write(bibdatabase2bibtex(data)) | python | def write(filename, data):
"""
Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object.
"""
with open(filename, 'w') as fh:
fh.write(bibdatabase2bibtex(data)) | [
"def",
"write",
"(",
"filename",
",",
"data",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'w'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"bibdatabase2bibtex",
"(",
"data",
")",
")"
] | Create a new BibTeX file.
:param filename: The name of the BibTeX file to write.
:param data: A ``bibtexparser.BibDatabase`` object. | [
"Create",
"a",
"new",
"BibTeX",
"file",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L43-L51 | train |
Phyks/libbmc | libbmc/bibtex.py | edit | def edit(filename, identifier, data):
"""
Update an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to update, in the BibTeX file.
:param data: A dict associating fields and updated values. Fields present \
in the BibTeX file but not in this dict will be kept as is.
"""
# Get current bibtex
with open(filename, 'r') as fh:
bibtex = bibtexparser.load(fh)
# Update it
# TODO: Not working
bibtex.entries_dict[identifier] = data.entries[0]
# Write the resulting BibTeX
write(filename, bibtex) | python | def edit(filename, identifier, data):
"""
Update an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to update, in the BibTeX file.
:param data: A dict associating fields and updated values. Fields present \
in the BibTeX file but not in this dict will be kept as is.
"""
# Get current bibtex
with open(filename, 'r') as fh:
bibtex = bibtexparser.load(fh)
# Update it
# TODO: Not working
bibtex.entries_dict[identifier] = data.entries[0]
# Write the resulting BibTeX
write(filename, bibtex) | [
"def",
"edit",
"(",
"filename",
",",
"identifier",
",",
"data",
")",
":",
"# Get current bibtex",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fh",
":",
"bibtex",
"=",
"bibtexparser",
".",
"load",
"(",
"fh",
")",
"# Update it",
"# TODO: Not working",
"bibtex",
".",
"entries_dict",
"[",
"identifier",
"]",
"=",
"data",
".",
"entries",
"[",
"0",
"]",
"# Write the resulting BibTeX",
"write",
"(",
"filename",
",",
"bibtex",
")"
] | Update an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to update, in the BibTeX file.
:param data: A dict associating fields and updated values. Fields present \
in the BibTeX file but not in this dict will be kept as is. | [
"Update",
"an",
"entry",
"in",
"a",
"BibTeX",
"file",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L65-L83 | train |
Phyks/libbmc | libbmc/bibtex.py | delete | def delete(filename, identifier):
"""
Delete an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to delete, in the BibTeX file.
"""
# Get current bibtex
with open(filename, 'r') as fh:
bibtex = bibtexparser.load(fh)
# Delete the bibtex entry
# TODO: Not working
try:
del bibtex.entries_dict[identifier]
except KeyError:
pass
# Write the resulting BibTeX
write(filename, bibtex) | python | def delete(filename, identifier):
"""
Delete an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to delete, in the BibTeX file.
"""
# Get current bibtex
with open(filename, 'r') as fh:
bibtex = bibtexparser.load(fh)
# Delete the bibtex entry
# TODO: Not working
try:
del bibtex.entries_dict[identifier]
except KeyError:
pass
# Write the resulting BibTeX
write(filename, bibtex) | [
"def",
"delete",
"(",
"filename",
",",
"identifier",
")",
":",
"# Get current bibtex",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fh",
":",
"bibtex",
"=",
"bibtexparser",
".",
"load",
"(",
"fh",
")",
"# Delete the bibtex entry",
"# TODO: Not working",
"try",
":",
"del",
"bibtex",
".",
"entries_dict",
"[",
"identifier",
"]",
"except",
"KeyError",
":",
"pass",
"# Write the resulting BibTeX",
"write",
"(",
"filename",
",",
"bibtex",
")"
] | Delete an entry in a BibTeX file.
:param filename: The name of the BibTeX file to edit.
:param identifier: The id of the entry to delete, in the BibTeX file. | [
"Delete",
"an",
"entry",
"in",
"a",
"BibTeX",
"file",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L107-L126 | train |
Phyks/libbmc | libbmc/bibtex.py | get | def get(filename, ignore_fields=None):
"""
Get all entries from a BibTeX file.
:param filename: The name of the BibTeX file.
:param ignore_fields: An optional list of fields to strip from the BibTeX \
file.
:returns: A ``bibtexparser.BibDatabase`` object representing the fetched \
entries.
"""
# Handle default argument
if ignore_fields is None:
ignore_fields = []
# Open bibtex file
with open(filename, 'r') as fh:
bibtex = bibtexparser.load(fh)
# Clean the entries if necessary
bibtex.entries = [{k: entry[k]
for k in entry if k not in ignore_fields}
for entry in bibtex.entries]
return bibtex | python | def get(filename, ignore_fields=None):
"""
Get all entries from a BibTeX file.
:param filename: The name of the BibTeX file.
:param ignore_fields: An optional list of fields to strip from the BibTeX \
file.
:returns: A ``bibtexparser.BibDatabase`` object representing the fetched \
entries.
"""
# Handle default argument
if ignore_fields is None:
ignore_fields = []
# Open bibtex file
with open(filename, 'r') as fh:
bibtex = bibtexparser.load(fh)
# Clean the entries if necessary
bibtex.entries = [{k: entry[k]
for k in entry if k not in ignore_fields}
for entry in bibtex.entries]
return bibtex | [
"def",
"get",
"(",
"filename",
",",
"ignore_fields",
"=",
"None",
")",
":",
"# Handle default argument",
"if",
"ignore_fields",
"is",
"None",
":",
"ignore_fields",
"=",
"[",
"]",
"# Open bibtex file",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"fh",
":",
"bibtex",
"=",
"bibtexparser",
".",
"load",
"(",
"fh",
")",
"# Clean the entries if necessary",
"bibtex",
".",
"entries",
"=",
"[",
"{",
"k",
":",
"entry",
"[",
"k",
"]",
"for",
"k",
"in",
"entry",
"if",
"k",
"not",
"in",
"ignore_fields",
"}",
"for",
"entry",
"in",
"bibtex",
".",
"entries",
"]",
"return",
"bibtex"
] | Get all entries from a BibTeX file.
:param filename: The name of the BibTeX file.
:param ignore_fields: An optional list of fields to strip from the BibTeX \
file.
:returns: A ``bibtexparser.BibDatabase`` object representing the fetched \
entries. | [
"Get",
"all",
"entries",
"from",
"a",
"BibTeX",
"file",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L129-L153 | train |
Phyks/libbmc | libbmc/bibtex.py | to_filename | def to_filename(data,
mask=DEFAULT_PAPERS_FILENAME_MASK,
extra_formatters=None):
"""
Convert a bibtex entry to a formatted filename according to a given mask.
.. note ::
Available formatters out of the box are:
- ``journal``
- ``title``
- ``year``
- ``first`` for the first author
- ``last`` for the last author
- ``authors`` for the list of authors
- ``arxiv_version`` (discarded if no arXiv version in the BibTeX)
Filename is slugified after applying the masks.
:param data: A ``bibtexparser.BibDatabase`` object representing a \
BibTeX entry, as the one from ``bibtexparser`` output.
:param mask: A Python format string.
:param extra_formatters: A dict of format string (in the mask) and \
associated lambdas to perform the formatting.
:returns: A formatted filename.
"""
# Handle default argument
if extra_formatters is None:
extra_formatters = {}
entry = data.entries[0]
authors = re.split(' and ', entry['author'])
formatters = {
"journal": "",
"title": "",
"year": "",
"first": "",
"last": "",
"authors": "",
"arxiv_version": ""
}
formatters["journal"] = entry.get("journal", "")
formatters["title"] = entry.get("title", "")
formatters["year"] = entry.get("year", "")
formatters["first"] = authors[0].split(',')[0].strip()
formatters["last"] = authors[-1].split(',')[0].strip()
formatters["authors"] = ", ".join([i.split(',')[0].strip()
for i in authors])
for extra_formatter in extra_formatters:
formatters[extra_formatter] = extra_formatters[extra_formatter](entry)
arxiv_version = ""
if "eprint" in entry:
arxiv_version = '-' + entry['eprint'][entry['eprint'].rfind('v'):]
formatters["arxiv_version"] = arxiv_version
return tools.slugify(mask.format(**formatters)) | python | def to_filename(data,
mask=DEFAULT_PAPERS_FILENAME_MASK,
extra_formatters=None):
"""
Convert a bibtex entry to a formatted filename according to a given mask.
.. note ::
Available formatters out of the box are:
- ``journal``
- ``title``
- ``year``
- ``first`` for the first author
- ``last`` for the last author
- ``authors`` for the list of authors
- ``arxiv_version`` (discarded if no arXiv version in the BibTeX)
Filename is slugified after applying the masks.
:param data: A ``bibtexparser.BibDatabase`` object representing a \
BibTeX entry, as the one from ``bibtexparser`` output.
:param mask: A Python format string.
:param extra_formatters: A dict of format string (in the mask) and \
associated lambdas to perform the formatting.
:returns: A formatted filename.
"""
# Handle default argument
if extra_formatters is None:
extra_formatters = {}
entry = data.entries[0]
authors = re.split(' and ', entry['author'])
formatters = {
"journal": "",
"title": "",
"year": "",
"first": "",
"last": "",
"authors": "",
"arxiv_version": ""
}
formatters["journal"] = entry.get("journal", "")
formatters["title"] = entry.get("title", "")
formatters["year"] = entry.get("year", "")
formatters["first"] = authors[0].split(',')[0].strip()
formatters["last"] = authors[-1].split(',')[0].strip()
formatters["authors"] = ", ".join([i.split(',')[0].strip()
for i in authors])
for extra_formatter in extra_formatters:
formatters[extra_formatter] = extra_formatters[extra_formatter](entry)
arxiv_version = ""
if "eprint" in entry:
arxiv_version = '-' + entry['eprint'][entry['eprint'].rfind('v'):]
formatters["arxiv_version"] = arxiv_version
return tools.slugify(mask.format(**formatters)) | [
"def",
"to_filename",
"(",
"data",
",",
"mask",
"=",
"DEFAULT_PAPERS_FILENAME_MASK",
",",
"extra_formatters",
"=",
"None",
")",
":",
"# Handle default argument",
"if",
"extra_formatters",
"is",
"None",
":",
"extra_formatters",
"=",
"{",
"}",
"entry",
"=",
"data",
".",
"entries",
"[",
"0",
"]",
"authors",
"=",
"re",
".",
"split",
"(",
"' and '",
",",
"entry",
"[",
"'author'",
"]",
")",
"formatters",
"=",
"{",
"\"journal\"",
":",
"\"\"",
",",
"\"title\"",
":",
"\"\"",
",",
"\"year\"",
":",
"\"\"",
",",
"\"first\"",
":",
"\"\"",
",",
"\"last\"",
":",
"\"\"",
",",
"\"authors\"",
":",
"\"\"",
",",
"\"arxiv_version\"",
":",
"\"\"",
"}",
"formatters",
"[",
"\"journal\"",
"]",
"=",
"entry",
".",
"get",
"(",
"\"journal\"",
",",
"\"\"",
")",
"formatters",
"[",
"\"title\"",
"]",
"=",
"entry",
".",
"get",
"(",
"\"title\"",
",",
"\"\"",
")",
"formatters",
"[",
"\"year\"",
"]",
"=",
"entry",
".",
"get",
"(",
"\"year\"",
",",
"\"\"",
")",
"formatters",
"[",
"\"first\"",
"]",
"=",
"authors",
"[",
"0",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"formatters",
"[",
"\"last\"",
"]",
"=",
"authors",
"[",
"-",
"1",
"]",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"formatters",
"[",
"\"authors\"",
"]",
"=",
"\", \"",
".",
"join",
"(",
"[",
"i",
".",
"split",
"(",
"','",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"for",
"i",
"in",
"authors",
"]",
")",
"for",
"extra_formatter",
"in",
"extra_formatters",
":",
"formatters",
"[",
"extra_formatter",
"]",
"=",
"extra_formatters",
"[",
"extra_formatter",
"]",
"(",
"entry",
")",
"arxiv_version",
"=",
"\"\"",
"if",
"\"eprint\"",
"in",
"entry",
":",
"arxiv_version",
"=",
"'-'",
"+",
"entry",
"[",
"'eprint'",
"]",
"[",
"entry",
"[",
"'eprint'",
"]",
".",
"rfind",
"(",
"'v'",
")",
":",
"]",
"formatters",
"[",
"\"arxiv_version\"",
"]",
"=",
"arxiv_version",
"return",
"tools",
".",
"slugify",
"(",
"mask",
".",
"format",
"(",
"*",
"*",
"formatters",
")",
")"
] | Convert a bibtex entry to a formatted filename according to a given mask.
.. note ::
Available formatters out of the box are:
- ``journal``
- ``title``
- ``year``
- ``first`` for the first author
- ``last`` for the last author
- ``authors`` for the list of authors
- ``arxiv_version`` (discarded if no arXiv version in the BibTeX)
Filename is slugified after applying the masks.
:param data: A ``bibtexparser.BibDatabase`` object representing a \
BibTeX entry, as the one from ``bibtexparser`` output.
:param mask: A Python format string.
:param extra_formatters: A dict of format string (in the mask) and \
associated lambdas to perform the formatting.
:returns: A formatted filename. | [
"Convert",
"a",
"bibtex",
"entry",
"to",
"a",
"formatted",
"filename",
"according",
"to",
"a",
"given",
"mask",
"."
] | 9ef1a29d2514157d1edd6c13ecbd61b07ae9315e | https://github.com/Phyks/libbmc/blob/9ef1a29d2514157d1edd6c13ecbd61b07ae9315e/libbmc/bibtex.py#L224-L285 | train |
ets-labs/python-domain-models | domain_models/fields.py | Field.bind_name | def bind_name(self, name):
"""Bind field to its name in model class."""
if self.name:
raise errors.Error('Already bound "{0}" with name "{1}" could not '
'be rebound'.format(self, self.name))
self.name = name
self.storage_name = ''.join(('_', self.name))
return self | python | def bind_name(self, name):
"""Bind field to its name in model class."""
if self.name:
raise errors.Error('Already bound "{0}" with name "{1}" could not '
'be rebound'.format(self, self.name))
self.name = name
self.storage_name = ''.join(('_', self.name))
return self | [
"def",
"bind_name",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"name",
":",
"raise",
"errors",
".",
"Error",
"(",
"'Already bound \"{0}\" with name \"{1}\" could not '",
"'be rebound'",
".",
"format",
"(",
"self",
",",
"self",
".",
"name",
")",
")",
"self",
".",
"name",
"=",
"name",
"self",
".",
"storage_name",
"=",
"''",
".",
"join",
"(",
"(",
"'_'",
",",
"self",
".",
"name",
")",
")",
"return",
"self"
] | Bind field to its name in model class. | [
"Bind",
"field",
"to",
"its",
"name",
"in",
"model",
"class",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L24-L31 | train |
ets-labs/python-domain-models | domain_models/fields.py | Field.bind_model_cls | def bind_model_cls(self, model_cls):
"""Bind field to model class."""
if self.model_cls:
raise errors.Error('"{0}" has been already bound to "{1}" and '
'could not be rebound to "{2}"'.format(
self, self.model_cls, model_cls))
self.model_cls = model_cls
return self | python | def bind_model_cls(self, model_cls):
"""Bind field to model class."""
if self.model_cls:
raise errors.Error('"{0}" has been already bound to "{1}" and '
'could not be rebound to "{2}"'.format(
self, self.model_cls, model_cls))
self.model_cls = model_cls
return self | [
"def",
"bind_model_cls",
"(",
"self",
",",
"model_cls",
")",
":",
"if",
"self",
".",
"model_cls",
":",
"raise",
"errors",
".",
"Error",
"(",
"'\"{0}\" has been already bound to \"{1}\" and '",
"'could not be rebound to \"{2}\"'",
".",
"format",
"(",
"self",
",",
"self",
".",
"model_cls",
",",
"model_cls",
")",
")",
"self",
".",
"model_cls",
"=",
"model_cls",
"return",
"self"
] | Bind field to model class. | [
"Bind",
"field",
"to",
"model",
"class",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L33-L40 | train |
ets-labs/python-domain-models | domain_models/fields.py | Field.init_model | def init_model(self, model, value):
"""Init model with field.
:param DomainModel model:
:param object value:
"""
if value is None and self.default is not None:
value = self.default() if callable(self.default) else self.default
self.set_value(model, value) | python | def init_model(self, model, value):
"""Init model with field.
:param DomainModel model:
:param object value:
"""
if value is None and self.default is not None:
value = self.default() if callable(self.default) else self.default
self.set_value(model, value) | [
"def",
"init_model",
"(",
"self",
",",
"model",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"self",
".",
"default",
"is",
"not",
"None",
":",
"value",
"=",
"self",
".",
"default",
"(",
")",
"if",
"callable",
"(",
"self",
".",
"default",
")",
"else",
"self",
".",
"default",
"self",
".",
"set_value",
"(",
"model",
",",
"value",
")"
] | Init model with field.
:param DomainModel model:
:param object value: | [
"Init",
"model",
"with",
"field",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L42-L51 | train |
ets-labs/python-domain-models | domain_models/fields.py | Field.get_value | def get_value(self, model, default=None):
"""Return field's value.
:param DomainModel model:
:param object default:
:rtype object:
"""
if default is not None:
default = self._converter(default)
value = getattr(model, self.storage_name)
return value if value is not None else default | python | def get_value(self, model, default=None):
"""Return field's value.
:param DomainModel model:
:param object default:
:rtype object:
"""
if default is not None:
default = self._converter(default)
value = getattr(model, self.storage_name)
return value if value is not None else default | [
"def",
"get_value",
"(",
"self",
",",
"model",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"not",
"None",
":",
"default",
"=",
"self",
".",
"_converter",
"(",
"default",
")",
"value",
"=",
"getattr",
"(",
"model",
",",
"self",
".",
"storage_name",
")",
"return",
"value",
"if",
"value",
"is",
"not",
"None",
"else",
"default"
] | Return field's value.
:param DomainModel model:
:param object default:
:rtype object: | [
"Return",
"field",
"s",
"value",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L53-L64 | train |
ets-labs/python-domain-models | domain_models/fields.py | Field.set_value | def set_value(self, model, value):
"""Set field's value.
:param DomainModel model:
:param object value:
"""
if value is None and self.required:
raise AttributeError("This field is required.")
if value is not None:
value = self._converter(value)
setattr(model, self.storage_name, value) | python | def set_value(self, model, value):
"""Set field's value.
:param DomainModel model:
:param object value:
"""
if value is None and self.required:
raise AttributeError("This field is required.")
if value is not None:
value = self._converter(value)
setattr(model, self.storage_name, value) | [
"def",
"set_value",
"(",
"self",
",",
"model",
",",
"value",
")",
":",
"if",
"value",
"is",
"None",
"and",
"self",
".",
"required",
":",
"raise",
"AttributeError",
"(",
"\"This field is required.\"",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"self",
".",
"_converter",
"(",
"value",
")",
"setattr",
"(",
"model",
",",
"self",
".",
"storage_name",
",",
"value",
")"
] | Set field's value.
:param DomainModel model:
:param object value: | [
"Set",
"field",
"s",
"value",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L66-L78 | train |
ets-labs/python-domain-models | domain_models/fields.py | Field._get_model_instance | def _get_model_instance(model_cls, data):
"""Convert dict into object of class of passed model.
:param class model_cls:
:param object data:
:rtype DomainModel:
"""
if not isinstance(data, (model_cls, dict)):
raise TypeError('{0} is not valid type, instance of '
'{1} or dict required'.format(data, model_cls))
return model_cls(**data) if isinstance(data, dict) else data | python | def _get_model_instance(model_cls, data):
"""Convert dict into object of class of passed model.
:param class model_cls:
:param object data:
:rtype DomainModel:
"""
if not isinstance(data, (model_cls, dict)):
raise TypeError('{0} is not valid type, instance of '
'{1} or dict required'.format(data, model_cls))
return model_cls(**data) if isinstance(data, dict) else data | [
"def",
"_get_model_instance",
"(",
"model_cls",
",",
"data",
")",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"(",
"model_cls",
",",
"dict",
")",
")",
":",
"raise",
"TypeError",
"(",
"'{0} is not valid type, instance of '",
"'{1} or dict required'",
".",
"format",
"(",
"data",
",",
"model_cls",
")",
")",
"return",
"model_cls",
"(",
"*",
"*",
"data",
")",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
"else",
"data"
] | Convert dict into object of class of passed model.
:param class model_cls:
:param object data:
:rtype DomainModel: | [
"Convert",
"dict",
"into",
"object",
"of",
"class",
"of",
"passed",
"model",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L97-L107 | train |
ets-labs/python-domain-models | domain_models/fields.py | Collection.get_builtin_type | def get_builtin_type(self, model):
"""Return built-in type representation of Collection.
:param DomainModel model:
:rtype list:
"""
return [item.get_data() if isinstance(item, self.related_model_cls)
else item for item in self.get_value(model)] | python | def get_builtin_type(self, model):
"""Return built-in type representation of Collection.
:param DomainModel model:
:rtype list:
"""
return [item.get_data() if isinstance(item, self.related_model_cls)
else item for item in self.get_value(model)] | [
"def",
"get_builtin_type",
"(",
"self",
",",
"model",
")",
":",
"return",
"[",
"item",
".",
"get_data",
"(",
")",
"if",
"isinstance",
"(",
"item",
",",
"self",
".",
"related_model_cls",
")",
"else",
"item",
"for",
"item",
"in",
"self",
".",
"get_value",
"(",
"model",
")",
"]"
] | Return built-in type representation of Collection.
:param DomainModel model:
:rtype list: | [
"Return",
"built",
"-",
"in",
"type",
"representation",
"of",
"Collection",
"."
] | 7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9 | https://github.com/ets-labs/python-domain-models/blob/7de1816ba0338f20fdb3e0f57fad0ffd5bea13f9/domain_models/fields.py#L215-L222 | train |
useblocks/groundwork | groundwork/util.py | gw_get | def gw_get(object_dict, name=None, plugin=None):
"""
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name of the object
:type name: str
:param plugin: plugin name, which registers the object
:return: None, single object or dict of objects
"""
if plugin is not None:
if name is None:
object_list = {}
for key in object_dict.keys():
if object_dict[key].plugin == plugin:
object_list[key] = object_dict[key]
return object_list
else:
if name in object_dict.keys():
if object_dict[name].plugin == plugin:
return object_dict[name]
else:
return None
else:
return None
else:
if name is None:
return object_dict
else:
if name in object_dict.keys():
return object_dict[name]
else:
return None | python | def gw_get(object_dict, name=None, plugin=None):
"""
Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name of the object
:type name: str
:param plugin: plugin name, which registers the object
:return: None, single object or dict of objects
"""
if plugin is not None:
if name is None:
object_list = {}
for key in object_dict.keys():
if object_dict[key].plugin == plugin:
object_list[key] = object_dict[key]
return object_list
else:
if name in object_dict.keys():
if object_dict[name].plugin == plugin:
return object_dict[name]
else:
return None
else:
return None
else:
if name is None:
return object_dict
else:
if name in object_dict.keys():
return object_dict[name]
else:
return None | [
"def",
"gw_get",
"(",
"object_dict",
",",
"name",
"=",
"None",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"plugin",
"is",
"not",
"None",
":",
"if",
"name",
"is",
"None",
":",
"object_list",
"=",
"{",
"}",
"for",
"key",
"in",
"object_dict",
".",
"keys",
"(",
")",
":",
"if",
"object_dict",
"[",
"key",
"]",
".",
"plugin",
"==",
"plugin",
":",
"object_list",
"[",
"key",
"]",
"=",
"object_dict",
"[",
"key",
"]",
"return",
"object_list",
"else",
":",
"if",
"name",
"in",
"object_dict",
".",
"keys",
"(",
")",
":",
"if",
"object_dict",
"[",
"name",
"]",
".",
"plugin",
"==",
"plugin",
":",
"return",
"object_dict",
"[",
"name",
"]",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"else",
":",
"if",
"name",
"is",
"None",
":",
"return",
"object_dict",
"else",
":",
"if",
"name",
"in",
"object_dict",
".",
"keys",
"(",
")",
":",
"return",
"object_dict",
"[",
"name",
"]",
"else",
":",
"return",
"None"
] | Getter function to retrieve objects from a given object dictionary.
Used mainly to provide get() inside patterns.
:param object_dict: objects, which must have 'name' and 'plugin' as attribute
:type object_dict: dictionary
:param name: name of the object
:type name: str
:param plugin: plugin name, which registers the object
:return: None, single object or dict of objects | [
"Getter",
"function",
"to",
"retrieve",
"objects",
"from",
"a",
"given",
"object",
"dictionary",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/util.py#L1-L36 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | http_error_handler | def http_error_handler(f):
"""Handle 404 errors returned by the API server
"""
def hrefs_to_resources(hrefs):
for href in hrefs.replace(',', '').split():
type, uuid = href.split('/')[-2:]
yield Resource(type, uuid=uuid)
def hrefs_list_to_resources(hrefs_list):
for href in eval(hrefs_list):
type, uuid = href.split('/')[-2:]
yield Resource(type, uuid=uuid)
@wraps(f)
def wrapper(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except HttpError as e:
if e.http_status == 404:
# remove previously created resource
# from the cache
self.emit('deleted', self)
if isinstance(self, Resource):
raise ResourceNotFound(resource=self)
elif isinstance(self, Collection):
raise CollectionNotFound(collection=self)
elif e.http_status == 409:
# contrail 3.2
matches = re.match(r'^Delete when children still present: (\[[^]]*\])', e.message)
if matches:
raise ChildrenExists(
resources=list(hrefs_list_to_resources(matches.group(1))))
matches = re.match(r'^Delete when resource still referred: (\[[^]]*\])', e.message)
if matches:
raise BackRefsExists(
resources=list(hrefs_list_to_resources(matches.group(1))))
# contrail 2.21
matches = re.match(r'^Children (.*) still exist$', e.message)
if matches:
raise ChildrenExists(
resources=list(hrefs_to_resources(matches.group(1))))
matches = re.match(r'^Back-References from (.*) still exist$', e.message)
if matches:
raise BackRefsExists(
resources=list(hrefs_to_resources(matches.group(1))))
raise
return wrapper | python | def http_error_handler(f):
"""Handle 404 errors returned by the API server
"""
def hrefs_to_resources(hrefs):
for href in hrefs.replace(',', '').split():
type, uuid = href.split('/')[-2:]
yield Resource(type, uuid=uuid)
def hrefs_list_to_resources(hrefs_list):
for href in eval(hrefs_list):
type, uuid = href.split('/')[-2:]
yield Resource(type, uuid=uuid)
@wraps(f)
def wrapper(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except HttpError as e:
if e.http_status == 404:
# remove previously created resource
# from the cache
self.emit('deleted', self)
if isinstance(self, Resource):
raise ResourceNotFound(resource=self)
elif isinstance(self, Collection):
raise CollectionNotFound(collection=self)
elif e.http_status == 409:
# contrail 3.2
matches = re.match(r'^Delete when children still present: (\[[^]]*\])', e.message)
if matches:
raise ChildrenExists(
resources=list(hrefs_list_to_resources(matches.group(1))))
matches = re.match(r'^Delete when resource still referred: (\[[^]]*\])', e.message)
if matches:
raise BackRefsExists(
resources=list(hrefs_list_to_resources(matches.group(1))))
# contrail 2.21
matches = re.match(r'^Children (.*) still exist$', e.message)
if matches:
raise ChildrenExists(
resources=list(hrefs_to_resources(matches.group(1))))
matches = re.match(r'^Back-References from (.*) still exist$', e.message)
if matches:
raise BackRefsExists(
resources=list(hrefs_to_resources(matches.group(1))))
raise
return wrapper | [
"def",
"http_error_handler",
"(",
"f",
")",
":",
"def",
"hrefs_to_resources",
"(",
"hrefs",
")",
":",
"for",
"href",
"in",
"hrefs",
".",
"replace",
"(",
"','",
",",
"''",
")",
".",
"split",
"(",
")",
":",
"type",
",",
"uuid",
"=",
"href",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"2",
":",
"]",
"yield",
"Resource",
"(",
"type",
",",
"uuid",
"=",
"uuid",
")",
"def",
"hrefs_list_to_resources",
"(",
"hrefs_list",
")",
":",
"for",
"href",
"in",
"eval",
"(",
"hrefs_list",
")",
":",
"type",
",",
"uuid",
"=",
"href",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"2",
":",
"]",
"yield",
"Resource",
"(",
"type",
",",
"uuid",
"=",
"uuid",
")",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"HttpError",
"as",
"e",
":",
"if",
"e",
".",
"http_status",
"==",
"404",
":",
"# remove previously created resource",
"# from the cache",
"self",
".",
"emit",
"(",
"'deleted'",
",",
"self",
")",
"if",
"isinstance",
"(",
"self",
",",
"Resource",
")",
":",
"raise",
"ResourceNotFound",
"(",
"resource",
"=",
"self",
")",
"elif",
"isinstance",
"(",
"self",
",",
"Collection",
")",
":",
"raise",
"CollectionNotFound",
"(",
"collection",
"=",
"self",
")",
"elif",
"e",
".",
"http_status",
"==",
"409",
":",
"# contrail 3.2",
"matches",
"=",
"re",
".",
"match",
"(",
"r'^Delete when children still present: (\\[[^]]*\\])'",
",",
"e",
".",
"message",
")",
"if",
"matches",
":",
"raise",
"ChildrenExists",
"(",
"resources",
"=",
"list",
"(",
"hrefs_list_to_resources",
"(",
"matches",
".",
"group",
"(",
"1",
")",
")",
")",
")",
"matches",
"=",
"re",
".",
"match",
"(",
"r'^Delete when resource still referred: (\\[[^]]*\\])'",
",",
"e",
".",
"message",
")",
"if",
"matches",
":",
"raise",
"BackRefsExists",
"(",
"resources",
"=",
"list",
"(",
"hrefs_list_to_resources",
"(",
"matches",
".",
"group",
"(",
"1",
")",
")",
")",
")",
"# contrail 2.21",
"matches",
"=",
"re",
".",
"match",
"(",
"r'^Children (.*) still exist$'",
",",
"e",
".",
"message",
")",
"if",
"matches",
":",
"raise",
"ChildrenExists",
"(",
"resources",
"=",
"list",
"(",
"hrefs_to_resources",
"(",
"matches",
".",
"group",
"(",
"1",
")",
")",
")",
")",
"matches",
"=",
"re",
".",
"match",
"(",
"r'^Back-References from (.*) still exist$'",
",",
"e",
".",
"message",
")",
"if",
"matches",
":",
"raise",
"BackRefsExists",
"(",
"resources",
"=",
"list",
"(",
"hrefs_to_resources",
"(",
"matches",
".",
"group",
"(",
"1",
")",
")",
")",
")",
"raise",
"return",
"wrapper"
] | Handle 404 errors returned by the API server | [
"Handle",
"404",
"errors",
"returned",
"by",
"the",
"API",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L30-L77 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | ResourceBase.href | def href(self):
"""Return URL of the resource
:rtype: str
"""
url = self.session.base_url + str(self.path)
if self.path.is_collection and not self.path.is_root:
return url + 's'
return url | python | def href(self):
"""Return URL of the resource
:rtype: str
"""
url = self.session.base_url + str(self.path)
if self.path.is_collection and not self.path.is_root:
return url + 's'
return url | [
"def",
"href",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"session",
".",
"base_url",
"+",
"str",
"(",
"self",
".",
"path",
")",
"if",
"self",
".",
"path",
".",
"is_collection",
"and",
"not",
"self",
".",
"path",
".",
"is_root",
":",
"return",
"url",
"+",
"'s'",
"return",
"url"
] | Return URL of the resource
:rtype: str | [
"Return",
"URL",
"of",
"the",
"resource"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L205-L213 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Collection.filter | def filter(self, field_name, field_value):
"""Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection
"""
self.filters.append((field_name, field_value))
return self | python | def filter(self, field_name, field_value):
"""Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection
"""
self.filters.append((field_name, field_value))
return self | [
"def",
"filter",
"(",
"self",
",",
"field_name",
",",
"field_value",
")",
":",
"self",
".",
"filters",
".",
"append",
"(",
"(",
"field_name",
",",
"field_value",
")",
")",
"return",
"self"
] | Add permanent filter on the collection
:param field_name: name of the field to filter on
:type field_name: str
:param field_value: value to filter on
:rtype: Collection | [
"Add",
"permanent",
"filter",
"on",
"the",
"collection"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L299-L309 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Collection.fetch | def fetch(self, recursive=1, fields=None, detail=None,
filters=None, parent_uuid=None, back_refs_uuid=None):
"""
Fetch collection from API server
:param recursive: level of recursion
:type recursive: int
:param fields: fetch only listed fields.
contrail 3.0 required
:type fields: [str]
:param detail: fetch all fields
:type detail: bool
:param filters: list of filters
:type filters: [(name, value), ...]
:param parent_uuid: filter by parent_uuid
:type parent_uuid: v4UUID str or list of v4UUID str
:param back_refs_uuid: filter by back_refs_uuid
:type back_refs_uuid: v4UUID str or list of v4UUID str
:rtype: Collection
"""
params = self._format_fetch_params(fields=fields, detail=detail, filters=filters,
parent_uuid=parent_uuid, back_refs_uuid=back_refs_uuid)
data = self.session.get_json(self.href, **params)
if not self.type:
self.data = [Collection(col["link"]["name"],
fetch=recursive - 1 > 0,
recursive=recursive - 1,
fields=self._fetch_fields(fields),
detail=detail or self.detail,
filters=self._fetch_filters(filters),
parent_uuid=self._fetch_parent_uuid(parent_uuid),
back_refs_uuid=self._fetch_back_refs_uuid(back_refs_uuid))
for col in data['links']
if col["link"]["rel"] == "collection"]
else:
# when detail=False, res == {resource_attrs}
# when detail=True, res == {'type': {resource_attrs}}
self.data = [Resource(self.type,
fetch=recursive - 1 > 0,
recursive=recursive - 1,
**res.get(self.type, res))
for res_type, res_list in data.items()
for res in res_list]
return self | python | def fetch(self, recursive=1, fields=None, detail=None,
filters=None, parent_uuid=None, back_refs_uuid=None):
"""
Fetch collection from API server
:param recursive: level of recursion
:type recursive: int
:param fields: fetch only listed fields.
contrail 3.0 required
:type fields: [str]
:param detail: fetch all fields
:type detail: bool
:param filters: list of filters
:type filters: [(name, value), ...]
:param parent_uuid: filter by parent_uuid
:type parent_uuid: v4UUID str or list of v4UUID str
:param back_refs_uuid: filter by back_refs_uuid
:type back_refs_uuid: v4UUID str or list of v4UUID str
:rtype: Collection
"""
params = self._format_fetch_params(fields=fields, detail=detail, filters=filters,
parent_uuid=parent_uuid, back_refs_uuid=back_refs_uuid)
data = self.session.get_json(self.href, **params)
if not self.type:
self.data = [Collection(col["link"]["name"],
fetch=recursive - 1 > 0,
recursive=recursive - 1,
fields=self._fetch_fields(fields),
detail=detail or self.detail,
filters=self._fetch_filters(filters),
parent_uuid=self._fetch_parent_uuid(parent_uuid),
back_refs_uuid=self._fetch_back_refs_uuid(back_refs_uuid))
for col in data['links']
if col["link"]["rel"] == "collection"]
else:
# when detail=False, res == {resource_attrs}
# when detail=True, res == {'type': {resource_attrs}}
self.data = [Resource(self.type,
fetch=recursive - 1 > 0,
recursive=recursive - 1,
**res.get(self.type, res))
for res_type, res_list in data.items()
for res in res_list]
return self | [
"def",
"fetch",
"(",
"self",
",",
"recursive",
"=",
"1",
",",
"fields",
"=",
"None",
",",
"detail",
"=",
"None",
",",
"filters",
"=",
"None",
",",
"parent_uuid",
"=",
"None",
",",
"back_refs_uuid",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_format_fetch_params",
"(",
"fields",
"=",
"fields",
",",
"detail",
"=",
"detail",
",",
"filters",
"=",
"filters",
",",
"parent_uuid",
"=",
"parent_uuid",
",",
"back_refs_uuid",
"=",
"back_refs_uuid",
")",
"data",
"=",
"self",
".",
"session",
".",
"get_json",
"(",
"self",
".",
"href",
",",
"*",
"*",
"params",
")",
"if",
"not",
"self",
".",
"type",
":",
"self",
".",
"data",
"=",
"[",
"Collection",
"(",
"col",
"[",
"\"link\"",
"]",
"[",
"\"name\"",
"]",
",",
"fetch",
"=",
"recursive",
"-",
"1",
">",
"0",
",",
"recursive",
"=",
"recursive",
"-",
"1",
",",
"fields",
"=",
"self",
".",
"_fetch_fields",
"(",
"fields",
")",
",",
"detail",
"=",
"detail",
"or",
"self",
".",
"detail",
",",
"filters",
"=",
"self",
".",
"_fetch_filters",
"(",
"filters",
")",
",",
"parent_uuid",
"=",
"self",
".",
"_fetch_parent_uuid",
"(",
"parent_uuid",
")",
",",
"back_refs_uuid",
"=",
"self",
".",
"_fetch_back_refs_uuid",
"(",
"back_refs_uuid",
")",
")",
"for",
"col",
"in",
"data",
"[",
"'links'",
"]",
"if",
"col",
"[",
"\"link\"",
"]",
"[",
"\"rel\"",
"]",
"==",
"\"collection\"",
"]",
"else",
":",
"# when detail=False, res == {resource_attrs}",
"# when detail=True, res == {'type': {resource_attrs}}",
"self",
".",
"data",
"=",
"[",
"Resource",
"(",
"self",
".",
"type",
",",
"fetch",
"=",
"recursive",
"-",
"1",
">",
"0",
",",
"recursive",
"=",
"recursive",
"-",
"1",
",",
"*",
"*",
"res",
".",
"get",
"(",
"self",
".",
"type",
",",
"res",
")",
")",
"for",
"res_type",
",",
"res_list",
"in",
"data",
".",
"items",
"(",
")",
"for",
"res",
"in",
"res_list",
"]",
"return",
"self"
] | Fetch collection from API server
:param recursive: level of recursion
:type recursive: int
:param fields: fetch only listed fields.
contrail 3.0 required
:type fields: [str]
:param detail: fetch all fields
:type detail: bool
:param filters: list of filters
:type filters: [(name, value), ...]
:param parent_uuid: filter by parent_uuid
:type parent_uuid: v4UUID str or list of v4UUID str
:param back_refs_uuid: filter by back_refs_uuid
:type back_refs_uuid: v4UUID str or list of v4UUID str
:rtype: Collection | [
"Fetch",
"collection",
"from",
"API",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L346-L393 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.check | def check(self):
"""Check that the resource exists.
:raises ResourceNotFound: if the resource doesn't exists
"""
if self.fq_name:
self['uuid'] = self._check_fq_name(self.fq_name)
elif self.uuid:
self['fq_name'] = self._check_uuid(self.uuid)
return True | python | def check(self):
"""Check that the resource exists.
:raises ResourceNotFound: if the resource doesn't exists
"""
if self.fq_name:
self['uuid'] = self._check_fq_name(self.fq_name)
elif self.uuid:
self['fq_name'] = self._check_uuid(self.uuid)
return True | [
"def",
"check",
"(",
"self",
")",
":",
"if",
"self",
".",
"fq_name",
":",
"self",
"[",
"'uuid'",
"]",
"=",
"self",
".",
"_check_fq_name",
"(",
"self",
".",
"fq_name",
")",
"elif",
"self",
".",
"uuid",
":",
"self",
"[",
"'fq_name'",
"]",
"=",
"self",
".",
"_check_uuid",
"(",
"self",
".",
"uuid",
")",
"return",
"True"
] | Check that the resource exists.
:raises ResourceNotFound: if the resource doesn't exists | [
"Check",
"that",
"the",
"resource",
"exists",
"."
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L488-L497 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.fq_name | def fq_name(self):
"""Return FQDN of the resource
:rtype: FQName
"""
return self.get('fq_name', self.get('to', super(Resource, self).fq_name)) | python | def fq_name(self):
"""Return FQDN of the resource
:rtype: FQName
"""
return self.get('fq_name', self.get('to', super(Resource, self).fq_name)) | [
"def",
"fq_name",
"(",
"self",
")",
":",
"return",
"self",
".",
"get",
"(",
"'fq_name'",
",",
"self",
".",
"get",
"(",
"'to'",
",",
"super",
"(",
"Resource",
",",
"self",
")",
".",
"fq_name",
")",
")"
] | Return FQDN of the resource
:rtype: FQName | [
"Return",
"FQDN",
"of",
"the",
"resource"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L529-L534 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.parent | def parent(self):
"""Return parent resource
:rtype: Resource
:raises ResourceNotFound: parent resource doesn't exists
:raises ResourceMissing: parent resource is not defined
"""
try:
return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True)
except KeyError:
raise ResourceMissing('%s has no parent resource' % self) | python | def parent(self):
"""Return parent resource
:rtype: Resource
:raises ResourceNotFound: parent resource doesn't exists
:raises ResourceMissing: parent resource is not defined
"""
try:
return Resource(self['parent_type'], uuid=self['parent_uuid'], check=True)
except KeyError:
raise ResourceMissing('%s has no parent resource' % self) | [
"def",
"parent",
"(",
"self",
")",
":",
"try",
":",
"return",
"Resource",
"(",
"self",
"[",
"'parent_type'",
"]",
",",
"uuid",
"=",
"self",
"[",
"'parent_uuid'",
"]",
",",
"check",
"=",
"True",
")",
"except",
"KeyError",
":",
"raise",
"ResourceMissing",
"(",
"'%s has no parent resource'",
"%",
"self",
")"
] | Return parent resource
:rtype: Resource
:raises ResourceNotFound: parent resource doesn't exists
:raises ResourceMissing: parent resource is not defined | [
"Return",
"parent",
"resource"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L537-L547 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.parent | def parent(self, resource):
"""Set parent resource
:param resource: parent resource
:type resource: Resource
:raises ResourceNotFound: resource not found on the API
"""
resource.check()
self['parent_type'] = resource.type
self['parent_uuid'] = resource.uuid | python | def parent(self, resource):
"""Set parent resource
:param resource: parent resource
:type resource: Resource
:raises ResourceNotFound: resource not found on the API
"""
resource.check()
self['parent_type'] = resource.type
self['parent_uuid'] = resource.uuid | [
"def",
"parent",
"(",
"self",
",",
"resource",
")",
":",
"resource",
".",
"check",
"(",
")",
"self",
"[",
"'parent_type'",
"]",
"=",
"resource",
".",
"type",
"self",
"[",
"'parent_uuid'",
"]",
"=",
"resource",
".",
"uuid"
] | Set parent resource
:param resource: parent resource
:type resource: Resource
:raises ResourceNotFound: resource not found on the API | [
"Set",
"parent",
"resource"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L550-L560 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.created | def created(self):
"""Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API
"""
if 'id_perms' not in self:
self.fetch()
created = self['id_perms']['created']
return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.%f') | python | def created(self):
"""Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API
"""
if 'id_perms' not in self:
self.fetch()
created = self['id_perms']['created']
return datetime.strptime(created, '%Y-%m-%dT%H:%M:%S.%f') | [
"def",
"created",
"(",
"self",
")",
":",
"if",
"'id_perms'",
"not",
"in",
"self",
":",
"self",
".",
"fetch",
"(",
")",
"created",
"=",
"self",
"[",
"'id_perms'",
"]",
"[",
"'created'",
"]",
"return",
"datetime",
".",
"strptime",
"(",
"created",
",",
"'%Y-%m-%dT%H:%M:%S.%f'",
")"
] | Return creation date
:rtype: datetime
:raises ResourceNotFound: resource not found on the API | [
"Return",
"creation",
"date"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L563-L572 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.save | def save(self):
"""Save the resource to the API server
If the resource doesn't have a uuid the resource will be created.
If uuid is present the resource is updated.
:rtype: Resource
"""
if self.path.is_collection:
self.session.post_json(self.href,
{self.type: dict(self.data)},
cls=ResourceEncoder)
else:
self.session.put_json(self.href,
{self.type: dict(self.data)},
cls=ResourceEncoder)
return self.fetch(exclude_children=True, exclude_back_refs=True) | python | def save(self):
"""Save the resource to the API server
If the resource doesn't have a uuid the resource will be created.
If uuid is present the resource is updated.
:rtype: Resource
"""
if self.path.is_collection:
self.session.post_json(self.href,
{self.type: dict(self.data)},
cls=ResourceEncoder)
else:
self.session.put_json(self.href,
{self.type: dict(self.data)},
cls=ResourceEncoder)
return self.fetch(exclude_children=True, exclude_back_refs=True) | [
"def",
"save",
"(",
"self",
")",
":",
"if",
"self",
".",
"path",
".",
"is_collection",
":",
"self",
".",
"session",
".",
"post_json",
"(",
"self",
".",
"href",
",",
"{",
"self",
".",
"type",
":",
"dict",
"(",
"self",
".",
"data",
")",
"}",
",",
"cls",
"=",
"ResourceEncoder",
")",
"else",
":",
"self",
".",
"session",
".",
"put_json",
"(",
"self",
".",
"href",
",",
"{",
"self",
".",
"type",
":",
"dict",
"(",
"self",
".",
"data",
")",
"}",
",",
"cls",
"=",
"ResourceEncoder",
")",
"return",
"self",
".",
"fetch",
"(",
"exclude_children",
"=",
"True",
",",
"exclude_back_refs",
"=",
"True",
")"
] | Save the resource to the API server
If the resource doesn't have a uuid the resource will be created.
If uuid is present the resource is updated.
:rtype: Resource | [
"Save",
"the",
"resource",
"to",
"the",
"API",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L575-L591 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.delete | def delete(self):
"""Delete resource from the API server
"""
res = self.session.delete(self.href)
self.emit('deleted', self)
return res | python | def delete(self):
"""Delete resource from the API server
"""
res = self.session.delete(self.href)
self.emit('deleted', self)
return res | [
"def",
"delete",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"session",
".",
"delete",
"(",
"self",
".",
"href",
")",
"self",
".",
"emit",
"(",
"'deleted'",
",",
"self",
")",
"return",
"res"
] | Delete resource from the API server | [
"Delete",
"resource",
"from",
"the",
"API",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L594-L599 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.fetch | def fetch(self, recursive=1, exclude_children=False, exclude_back_refs=False):
"""Fetch resource from the API server
:param recursive: level of recursion for fetching resources
:type recursive: int
:param exclude_children: don't get children references
:type exclude_children: bool
:param exclude_back_refs: don't get back_refs references
:type exclude_back_refs: bool
:rtype: Resource
"""
if not self.path.is_resource and not self.path.is_uuid:
self.check()
params = {}
# even if the param is False the API will exclude resources
if exclude_children:
params['exclude_children'] = True
if exclude_back_refs:
params['exclude_back_refs'] = True
data = self.session.get_json(self.href, **params)[self.type]
self.from_dict(data)
return self | python | def fetch(self, recursive=1, exclude_children=False, exclude_back_refs=False):
"""Fetch resource from the API server
:param recursive: level of recursion for fetching resources
:type recursive: int
:param exclude_children: don't get children references
:type exclude_children: bool
:param exclude_back_refs: don't get back_refs references
:type exclude_back_refs: bool
:rtype: Resource
"""
if not self.path.is_resource and not self.path.is_uuid:
self.check()
params = {}
# even if the param is False the API will exclude resources
if exclude_children:
params['exclude_children'] = True
if exclude_back_refs:
params['exclude_back_refs'] = True
data = self.session.get_json(self.href, **params)[self.type]
self.from_dict(data)
return self | [
"def",
"fetch",
"(",
"self",
",",
"recursive",
"=",
"1",
",",
"exclude_children",
"=",
"False",
",",
"exclude_back_refs",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"path",
".",
"is_resource",
"and",
"not",
"self",
".",
"path",
".",
"is_uuid",
":",
"self",
".",
"check",
"(",
")",
"params",
"=",
"{",
"}",
"# even if the param is False the API will exclude resources",
"if",
"exclude_children",
":",
"params",
"[",
"'exclude_children'",
"]",
"=",
"True",
"if",
"exclude_back_refs",
":",
"params",
"[",
"'exclude_back_refs'",
"]",
"=",
"True",
"data",
"=",
"self",
".",
"session",
".",
"get_json",
"(",
"self",
".",
"href",
",",
"*",
"*",
"params",
")",
"[",
"self",
".",
"type",
"]",
"self",
".",
"from_dict",
"(",
"data",
")",
"return",
"self"
] | Fetch resource from the API server
:param recursive: level of recursion for fetching resources
:type recursive: int
:param exclude_children: don't get children references
:type exclude_children: bool
:param exclude_back_refs: don't get back_refs references
:type exclude_back_refs: bool
:rtype: Resource | [
"Fetch",
"resource",
"from",
"the",
"API",
"server"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L602-L624 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.from_dict | def from_dict(self, data, recursive=1):
"""Populate the resource from a python dict
:param recursive: level of recursion for fetching resources
:type recursive: int
"""
# Find other linked resources
data = self._encode_resource(data, recursive=recursive)
self.data = data | python | def from_dict(self, data, recursive=1):
"""Populate the resource from a python dict
:param recursive: level of recursion for fetching resources
:type recursive: int
"""
# Find other linked resources
data = self._encode_resource(data, recursive=recursive)
self.data = data | [
"def",
"from_dict",
"(",
"self",
",",
"data",
",",
"recursive",
"=",
"1",
")",
":",
"# Find other linked resources",
"data",
"=",
"self",
".",
"_encode_resource",
"(",
"data",
",",
"recursive",
"=",
"recursive",
")",
"self",
".",
"data",
"=",
"data"
] | Populate the resource from a python dict
:param recursive: level of recursion for fetching resources
:type recursive: int | [
"Populate",
"the",
"resource",
"from",
"a",
"python",
"dict"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L626-L634 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.remove_ref | def remove_ref(self, ref):
"""Remove reference from self to ref
>>> iip = Resource('instance-ip',
uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',
fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:
iip.remove_ref(vmi)
>>> iip['virtual_machine_interface_refs']
KeyError: u'virtual_machine_interface_refs'
:param ref: reference to remove
:type ref: Resource
:rtype: Resource
"""
self.session.remove_ref(self, ref)
return self.fetch() | python | def remove_ref(self, ref):
"""Remove reference from self to ref
>>> iip = Resource('instance-ip',
uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',
fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:
iip.remove_ref(vmi)
>>> iip['virtual_machine_interface_refs']
KeyError: u'virtual_machine_interface_refs'
:param ref: reference to remove
:type ref: Resource
:rtype: Resource
"""
self.session.remove_ref(self, ref)
return self.fetch() | [
"def",
"remove_ref",
"(",
"self",
",",
"ref",
")",
":",
"self",
".",
"session",
".",
"remove_ref",
"(",
"self",
",",
"ref",
")",
"return",
"self",
".",
"fetch",
"(",
")"
] | Remove reference from self to ref
>>> iip = Resource('instance-ip',
uuid='30213cf9-4b03-4afc-b8f9-c9971a216978',
fetch=True)
>>> for vmi in iip['virtual_machine_interface_refs']:
iip.remove_ref(vmi)
>>> iip['virtual_machine_interface_refs']
KeyError: u'virtual_machine_interface_refs'
:param ref: reference to remove
:type ref: Resource
:rtype: Resource | [
"Remove",
"reference",
"from",
"self",
"to",
"ref"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L669-L686 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.set_ref | def set_ref(self, ref, attr=None):
"""Set reference to resource
Can be used to set references on a resource
that is not already created.
:param ref: reference to add
:type ref: Resource
:rtype: Resource
"""
ref_attr = '%s_refs' % ref.type.replace('-', '_')
ref = {
'to': ref.fq_name,
'uuid': ref.uuid,
}
if ref_attr in self:
self[ref_attr].append(ref)
else:
self[ref_attr] = [ref]
return self | python | def set_ref(self, ref, attr=None):
"""Set reference to resource
Can be used to set references on a resource
that is not already created.
:param ref: reference to add
:type ref: Resource
:rtype: Resource
"""
ref_attr = '%s_refs' % ref.type.replace('-', '_')
ref = {
'to': ref.fq_name,
'uuid': ref.uuid,
}
if ref_attr in self:
self[ref_attr].append(ref)
else:
self[ref_attr] = [ref]
return self | [
"def",
"set_ref",
"(",
"self",
",",
"ref",
",",
"attr",
"=",
"None",
")",
":",
"ref_attr",
"=",
"'%s_refs'",
"%",
"ref",
".",
"type",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"ref",
"=",
"{",
"'to'",
":",
"ref",
".",
"fq_name",
",",
"'uuid'",
":",
"ref",
".",
"uuid",
",",
"}",
"if",
"ref_attr",
"in",
"self",
":",
"self",
"[",
"ref_attr",
"]",
".",
"append",
"(",
"ref",
")",
"else",
":",
"self",
"[",
"ref_attr",
"]",
"=",
"[",
"ref",
"]",
"return",
"self"
] | Set reference to resource
Can be used to set references on a resource
that is not already created.
:param ref: reference to add
:type ref: Resource
:rtype: Resource | [
"Set",
"reference",
"to",
"resource"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L699-L719 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.add_ref | def add_ref(self, ref, attr=None):
"""Add reference to resource
:param ref: reference to add
:type ref: Resource
:rtype: Resource
"""
self.session.add_ref(self, ref, attr)
return self.fetch() | python | def add_ref(self, ref, attr=None):
"""Add reference to resource
:param ref: reference to add
:type ref: Resource
:rtype: Resource
"""
self.session.add_ref(self, ref, attr)
return self.fetch() | [
"def",
"add_ref",
"(",
"self",
",",
"ref",
",",
"attr",
"=",
"None",
")",
":",
"self",
".",
"session",
".",
"add_ref",
"(",
"self",
",",
"ref",
",",
"attr",
")",
"return",
"self",
".",
"fetch",
"(",
")"
] | Add reference to resource
:param ref: reference to add
:type ref: Resource
:rtype: Resource | [
"Add",
"reference",
"to",
"resource"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L721-L730 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | Resource.add_back_ref | def add_back_ref(self, back_ref, attr=None):
"""Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource
"""
back_ref.add_ref(self, attr)
return self.fetch() | python | def add_back_ref(self, back_ref, attr=None):
"""Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource
"""
back_ref.add_ref(self, attr)
return self.fetch() | [
"def",
"add_back_ref",
"(",
"self",
",",
"back_ref",
",",
"attr",
"=",
"None",
")",
":",
"back_ref",
".",
"add_ref",
"(",
"self",
",",
"attr",
")",
"return",
"self",
".",
"fetch",
"(",
")"
] | Add reference from back_ref to self
:param back_ref: back_ref to add
:type back_ref: Resource
:rtype: Resource | [
"Add",
"reference",
"from",
"back_ref",
"to",
"self"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L732-L741 | train |
eonpatapon/contrail-api-cli | contrail_api_cli/resource.py | ResourceCache._search | def _search(self, trie, strings, limit=None):
"""Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection]
"""
results = [trie.has_keys_with_prefix(s) for s in strings]
if not any(results):
return []
for result, s in zip(results, strings):
if result is True:
return trie.values(s)[:limit] | python | def _search(self, trie, strings, limit=None):
"""Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection]
"""
results = [trie.has_keys_with_prefix(s) for s in strings]
if not any(results):
return []
for result, s in zip(results, strings):
if result is True:
return trie.values(s)[:limit] | [
"def",
"_search",
"(",
"self",
",",
"trie",
",",
"strings",
",",
"limit",
"=",
"None",
")",
":",
"results",
"=",
"[",
"trie",
".",
"has_keys_with_prefix",
"(",
"s",
")",
"for",
"s",
"in",
"strings",
"]",
"if",
"not",
"any",
"(",
"results",
")",
":",
"return",
"[",
"]",
"for",
"result",
",",
"s",
"in",
"zip",
"(",
"results",
",",
"strings",
")",
":",
"if",
"result",
"is",
"True",
":",
"return",
"trie",
".",
"values",
"(",
"s",
")",
"[",
":",
"limit",
"]"
] | Search in cache
:param strings: list of strings to get from the cache
:type strings: str list
:param limit: limit search results
:type limit: int
:rtype: [Resource | Collection] | [
"Search",
"in",
"cache"
] | 1571bf523fa054f3d6bf83dba43a224fea173a73 | https://github.com/eonpatapon/contrail-api-cli/blob/1571bf523fa054f3d6bf83dba43a224fea173a73/contrail_api_cli/resource.py#L777-L792 | train |
useblocks/groundwork | groundwork/signals.py | SignalsApplication.register | def register(self, signal, plugin, description=""):
"""
Registers a new signal.
:param signal: Unique name of the signal
:param plugin: Plugin, which registers the new signal
:param description: Description of the reason or use case, why this signal is needed.
Used for documentation.
"""
if signal in self.signals.keys():
raise Exception("Signal %s was already registered by %s" % (signal, self.signals[signal].plugin.name))
self.signals[signal] = Signal(signal, plugin, self._namespace, description)
self.__log.debug("Signal %s registered by %s" % (signal, plugin.name))
return self.signals[signal] | python | def register(self, signal, plugin, description=""):
"""
Registers a new signal.
:param signal: Unique name of the signal
:param plugin: Plugin, which registers the new signal
:param description: Description of the reason or use case, why this signal is needed.
Used for documentation.
"""
if signal in self.signals.keys():
raise Exception("Signal %s was already registered by %s" % (signal, self.signals[signal].plugin.name))
self.signals[signal] = Signal(signal, plugin, self._namespace, description)
self.__log.debug("Signal %s registered by %s" % (signal, plugin.name))
return self.signals[signal] | [
"def",
"register",
"(",
"self",
",",
"signal",
",",
"plugin",
",",
"description",
"=",
"\"\"",
")",
":",
"if",
"signal",
"in",
"self",
".",
"signals",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"Signal %s was already registered by %s\"",
"%",
"(",
"signal",
",",
"self",
".",
"signals",
"[",
"signal",
"]",
".",
"plugin",
".",
"name",
")",
")",
"self",
".",
"signals",
"[",
"signal",
"]",
"=",
"Signal",
"(",
"signal",
",",
"plugin",
",",
"self",
".",
"_namespace",
",",
"description",
")",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Signal %s registered by %s\"",
"%",
"(",
"signal",
",",
"plugin",
".",
"name",
")",
")",
"return",
"self",
".",
"signals",
"[",
"signal",
"]"
] | Registers a new signal.
:param signal: Unique name of the signal
:param plugin: Plugin, which registers the new signal
:param description: Description of the reason or use case, why this signal is needed.
Used for documentation. | [
"Registers",
"a",
"new",
"signal",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L48-L62 | train |
useblocks/groundwork | groundwork/signals.py | SignalsApplication.unregister | def unregister(self, signal):
"""
Unregisters an existing signal
:param signal: Name of the signal
"""
if signal in self.signals.keys():
del(self.signals[signal])
self.__log.debug("Signal %s unregisterd" % signal)
else:
self.__log.debug("Signal %s does not exist and could not be unregistered.") | python | def unregister(self, signal):
"""
Unregisters an existing signal
:param signal: Name of the signal
"""
if signal in self.signals.keys():
del(self.signals[signal])
self.__log.debug("Signal %s unregisterd" % signal)
else:
self.__log.debug("Signal %s does not exist and could not be unregistered.") | [
"def",
"unregister",
"(",
"self",
",",
"signal",
")",
":",
"if",
"signal",
"in",
"self",
".",
"signals",
".",
"keys",
"(",
")",
":",
"del",
"(",
"self",
".",
"signals",
"[",
"signal",
"]",
")",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Signal %s unregisterd\"",
"%",
"signal",
")",
"else",
":",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Signal %s does not exist and could not be unregistered.\"",
")"
] | Unregisters an existing signal
:param signal: Name of the signal | [
"Unregisters",
"an",
"existing",
"signal"
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L64-L74 | train |
useblocks/groundwork | groundwork/signals.py | SignalsApplication.disconnect | def disconnect(self, receiver):
"""
Disconnect a receiver from a signal.
Signal and receiver must exist, otherwise an exception is thrown.
:param receiver: Name of the receiver
"""
if receiver not in self.receivers.keys():
raise Exception("No receiver %s was registered" % receiver)
self.receivers[receiver].disconnect()
del(self.receivers[receiver])
self.__log.debug("Receiver %s disconnected" % receiver) | python | def disconnect(self, receiver):
"""
Disconnect a receiver from a signal.
Signal and receiver must exist, otherwise an exception is thrown.
:param receiver: Name of the receiver
"""
if receiver not in self.receivers.keys():
raise Exception("No receiver %s was registered" % receiver)
self.receivers[receiver].disconnect()
del(self.receivers[receiver])
self.__log.debug("Receiver %s disconnected" % receiver) | [
"def",
"disconnect",
"(",
"self",
",",
"receiver",
")",
":",
"if",
"receiver",
"not",
"in",
"self",
".",
"receivers",
".",
"keys",
"(",
")",
":",
"raise",
"Exception",
"(",
"\"No receiver %s was registered\"",
"%",
"receiver",
")",
"self",
".",
"receivers",
"[",
"receiver",
"]",
".",
"disconnect",
"(",
")",
"del",
"(",
"self",
".",
"receivers",
"[",
"receiver",
"]",
")",
"self",
".",
"__log",
".",
"debug",
"(",
"\"Receiver %s disconnected\"",
"%",
"receiver",
")"
] | Disconnect a receiver from a signal.
Signal and receiver must exist, otherwise an exception is thrown.
:param receiver: Name of the receiver | [
"Disconnect",
"a",
"receiver",
"from",
"a",
"signal",
".",
"Signal",
"and",
"receiver",
"must",
"exist",
"otherwise",
"an",
"exception",
"is",
"thrown",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L98-L109 | train |
useblocks/groundwork | groundwork/signals.py | SignalsApplication.get | def get(self, signal=None, plugin=None):
"""
Get one or more signals.
:param signal: Name of the signal
:type signal: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if signal is None:
signals_list = {}
for key in self.signals.keys():
if self.signals[key].plugin == plugin:
signals_list[key] = self.signals[key]
return signals_list
else:
if signal in self.signals.keys():
if self.signals[signal].plugin == plugin:
return self.signals[signal]
else:
return None
else:
return None
else:
if signal is None:
return self.signals
else:
if signal in self.signals.keys():
return self.signals[signal]
else:
return None | python | def get(self, signal=None, plugin=None):
"""
Get one or more signals.
:param signal: Name of the signal
:type signal: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if signal is None:
signals_list = {}
for key in self.signals.keys():
if self.signals[key].plugin == plugin:
signals_list[key] = self.signals[key]
return signals_list
else:
if signal in self.signals.keys():
if self.signals[signal].plugin == plugin:
return self.signals[signal]
else:
return None
else:
return None
else:
if signal is None:
return self.signals
else:
if signal in self.signals.keys():
return self.signals[signal]
else:
return None | [
"def",
"get",
"(",
"self",
",",
"signal",
"=",
"None",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"plugin",
"is",
"not",
"None",
":",
"if",
"signal",
"is",
"None",
":",
"signals_list",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"signals",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"signals",
"[",
"key",
"]",
".",
"plugin",
"==",
"plugin",
":",
"signals_list",
"[",
"key",
"]",
"=",
"self",
".",
"signals",
"[",
"key",
"]",
"return",
"signals_list",
"else",
":",
"if",
"signal",
"in",
"self",
".",
"signals",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"signals",
"[",
"signal",
"]",
".",
"plugin",
"==",
"plugin",
":",
"return",
"self",
".",
"signals",
"[",
"signal",
"]",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"else",
":",
"if",
"signal",
"is",
"None",
":",
"return",
"self",
".",
"signals",
"else",
":",
"if",
"signal",
"in",
"self",
".",
"signals",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"signals",
"[",
"signal",
"]",
"else",
":",
"return",
"None"
] | Get one or more signals.
:param signal: Name of the signal
:type signal: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern | [
"Get",
"one",
"or",
"more",
"signals",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L126-L157 | train |
useblocks/groundwork | groundwork/signals.py | SignalsApplication.get_receiver | def get_receiver(self, receiver=None, plugin=None):
"""
Get one or more receivers.
:param receiver: Name of the signal
:type receiver: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if receiver is None:
receiver_list = {}
for key in self.receivers.keys():
if self.receivers[key].plugin == plugin:
receiver_list[key] = self.receivers[key]
return receiver_list
else:
if receiver in self.receivers.keys():
if self.receivers[receiver].plugin == plugin:
return self.receivers[receiver]
else:
return None
else:
return None
else:
if receiver is None:
return self.receivers
else:
if receiver in self.receivers.keys():
return self.receivers[receiver]
else:
return None | python | def get_receiver(self, receiver=None, plugin=None):
"""
Get one or more receivers.
:param receiver: Name of the signal
:type receiver: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern
"""
if plugin is not None:
if receiver is None:
receiver_list = {}
for key in self.receivers.keys():
if self.receivers[key].plugin == plugin:
receiver_list[key] = self.receivers[key]
return receiver_list
else:
if receiver in self.receivers.keys():
if self.receivers[receiver].plugin == plugin:
return self.receivers[receiver]
else:
return None
else:
return None
else:
if receiver is None:
return self.receivers
else:
if receiver in self.receivers.keys():
return self.receivers[receiver]
else:
return None | [
"def",
"get_receiver",
"(",
"self",
",",
"receiver",
"=",
"None",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"plugin",
"is",
"not",
"None",
":",
"if",
"receiver",
"is",
"None",
":",
"receiver_list",
"=",
"{",
"}",
"for",
"key",
"in",
"self",
".",
"receivers",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"receivers",
"[",
"key",
"]",
".",
"plugin",
"==",
"plugin",
":",
"receiver_list",
"[",
"key",
"]",
"=",
"self",
".",
"receivers",
"[",
"key",
"]",
"return",
"receiver_list",
"else",
":",
"if",
"receiver",
"in",
"self",
".",
"receivers",
".",
"keys",
"(",
")",
":",
"if",
"self",
".",
"receivers",
"[",
"receiver",
"]",
".",
"plugin",
"==",
"plugin",
":",
"return",
"self",
".",
"receivers",
"[",
"receiver",
"]",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"else",
":",
"if",
"receiver",
"is",
"None",
":",
"return",
"self",
".",
"receivers",
"else",
":",
"if",
"receiver",
"in",
"self",
".",
"receivers",
".",
"keys",
"(",
")",
":",
"return",
"self",
".",
"receivers",
"[",
"receiver",
"]",
"else",
":",
"return",
"None"
] | Get one or more receivers.
:param receiver: Name of the signal
:type receiver: str
:param plugin: Plugin object, under which the signals where registered
:type plugin: GwBasePattern | [
"Get",
"one",
"or",
"more",
"receivers",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/signals.py#L159-L190 | train |
suurjaak/InputScope | inputscope/listener.py | start | def start(inqueue, outqueue=None):
"""Starts the listener with incoming and outgoing queues."""
conf.init(), db.init(conf.DbPath)
Listener(inqueue, outqueue).run() | python | def start(inqueue, outqueue=None):
"""Starts the listener with incoming and outgoing queues."""
conf.init(), db.init(conf.DbPath)
Listener(inqueue, outqueue).run() | [
"def",
"start",
"(",
"inqueue",
",",
"outqueue",
"=",
"None",
")",
":",
"conf",
".",
"init",
"(",
")",
",",
"db",
".",
"init",
"(",
"conf",
".",
"DbPath",
")",
"Listener",
"(",
"inqueue",
",",
"outqueue",
")",
".",
"run",
"(",
")"
] | Starts the listener with incoming and outgoing queues. | [
"Starts",
"the",
"listener",
"with",
"incoming",
"and",
"outgoing",
"queues",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L263-L266 | train |
suurjaak/InputScope | inputscope/listener.py | main | def main():
"""Entry point for stand-alone execution."""
conf.init(), db.init(conf.DbPath)
inqueue = LineQueue(sys.stdin).queue
outqueue = type("", (), {"put": lambda self, x: print("\r%s" % x, end=" ")})()
if "--quiet" in sys.argv: outqueue = None
if conf.MouseEnabled: inqueue.put("mouse_start")
if conf.KeyboardEnabled: inqueue.put("keyboard_start")
start(inqueue, outqueue) | python | def main():
"""Entry point for stand-alone execution."""
conf.init(), db.init(conf.DbPath)
inqueue = LineQueue(sys.stdin).queue
outqueue = type("", (), {"put": lambda self, x: print("\r%s" % x, end=" ")})()
if "--quiet" in sys.argv: outqueue = None
if conf.MouseEnabled: inqueue.put("mouse_start")
if conf.KeyboardEnabled: inqueue.put("keyboard_start")
start(inqueue, outqueue) | [
"def",
"main",
"(",
")",
":",
"conf",
".",
"init",
"(",
")",
",",
"db",
".",
"init",
"(",
"conf",
".",
"DbPath",
")",
"inqueue",
"=",
"LineQueue",
"(",
"sys",
".",
"stdin",
")",
".",
"queue",
"outqueue",
"=",
"type",
"(",
"\"\"",
",",
"(",
")",
",",
"{",
"\"put\"",
":",
"lambda",
"self",
",",
"x",
":",
"print",
"(",
"\"\\r%s\"",
"%",
"x",
",",
"end",
"=",
"\" \"",
")",
"}",
")",
"(",
")",
"if",
"\"--quiet\"",
"in",
"sys",
".",
"argv",
":",
"outqueue",
"=",
"None",
"if",
"conf",
".",
"MouseEnabled",
":",
"inqueue",
".",
"put",
"(",
"\"mouse_start\"",
")",
"if",
"conf",
".",
"KeyboardEnabled",
":",
"inqueue",
".",
"put",
"(",
"\"keyboard_start\"",
")",
"start",
"(",
"inqueue",
",",
"outqueue",
")"
] | Entry point for stand-alone execution. | [
"Entry",
"point",
"for",
"stand",
"-",
"alone",
"execution",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L269-L277 | train |
suurjaak/InputScope | inputscope/listener.py | KeyHandler._handle_windows | def _handle_windows(self, event):
"""Windows key event handler."""
vkey = self._keyname(event.GetKey())
if event.Message in self.KEYS_UP + self.KEYS_DOWN:
if vkey in self.MODIFIERNAMES:
self._realmodifiers[vkey] = event.Message in self.KEYS_DOWN
self._modifiers[self.MODIFIERNAMES[vkey]] = self._realmodifiers[vkey]
if event.Message not in self.KEYS_DOWN:
return True
is_altgr = False
if (vkey, event.IsExtended()) in self.NUMPAD_SPECIALS:
key = vkey = "Numpad-" + vkey
elif not event.Ascii or vkey.startswith("Numpad"):
key = vkey
else:
is_altgr = event.Ascii in self.ALT_GRS
key = self._keyname(unichr(event.Ascii))
if DEBUG: print("Adding key %s (real %s)" % (key.encode("utf-8"), vkey.encode("utf-8")))
self._output(type="keys", key=key, realkey=vkey)
if vkey not in self.MODIFIERNAMES and not is_altgr:
modifier = "-".join(k for k in ["Ctrl", "Alt", "Shift", "Win"]
if self._modifiers[k])
if modifier and modifier != "Shift": # Shift-X is not a combo
if self._modifiers["Ctrl"] and event.Ascii:
key = self._keyname(unichr(event.KeyID))
realmodifier = "-".join(k for k, v in self._realmodifiers.items() if v)
realkey = "%s-%s" % (realmodifier, key)
key = "%s-%s" % (modifier, key)
if DEBUG: print("Adding combo %s (real %s)" % (key.encode("utf-8"), realkey.encode("utf-8")))
self._output(type="combos", key=key, realkey=realkey)
if DEBUG:
print("CHARACTER: %r" % key)
print('GetKey: {0}'.format(event.GetKey())) # Name of the virtual keycode, str
print('IsAlt: {0}'.format(event.IsAlt())) # Was the alt key depressed?, bool
print('IsExtended: {0}'.format(event.IsExtended())) # Is this an extended key?, bool
print('IsInjected: {0}'.format(event.IsInjected())) # Was this event generated programmatically?, bool
print('IsTransition: {0}'.format(event.IsTransition())) #Is this a transition from up to down or vice versa?, bool
print('ASCII: {0}'.format(event.Ascii)) # ASCII value, if one exists, str
print('KeyID: {0}'.format(event.KeyID)) # Virtual key code, int
print('ScanCode: {0}'.format(event.ScanCode)) # Scan code, int
print('Message: {0}'.format(event.Message)) # Name of the virtual keycode, str
print()
return True | python | def _handle_windows(self, event):
"""Windows key event handler."""
vkey = self._keyname(event.GetKey())
if event.Message in self.KEYS_UP + self.KEYS_DOWN:
if vkey in self.MODIFIERNAMES:
self._realmodifiers[vkey] = event.Message in self.KEYS_DOWN
self._modifiers[self.MODIFIERNAMES[vkey]] = self._realmodifiers[vkey]
if event.Message not in self.KEYS_DOWN:
return True
is_altgr = False
if (vkey, event.IsExtended()) in self.NUMPAD_SPECIALS:
key = vkey = "Numpad-" + vkey
elif not event.Ascii or vkey.startswith("Numpad"):
key = vkey
else:
is_altgr = event.Ascii in self.ALT_GRS
key = self._keyname(unichr(event.Ascii))
if DEBUG: print("Adding key %s (real %s)" % (key.encode("utf-8"), vkey.encode("utf-8")))
self._output(type="keys", key=key, realkey=vkey)
if vkey not in self.MODIFIERNAMES and not is_altgr:
modifier = "-".join(k for k in ["Ctrl", "Alt", "Shift", "Win"]
if self._modifiers[k])
if modifier and modifier != "Shift": # Shift-X is not a combo
if self._modifiers["Ctrl"] and event.Ascii:
key = self._keyname(unichr(event.KeyID))
realmodifier = "-".join(k for k, v in self._realmodifiers.items() if v)
realkey = "%s-%s" % (realmodifier, key)
key = "%s-%s" % (modifier, key)
if DEBUG: print("Adding combo %s (real %s)" % (key.encode("utf-8"), realkey.encode("utf-8")))
self._output(type="combos", key=key, realkey=realkey)
if DEBUG:
print("CHARACTER: %r" % key)
print('GetKey: {0}'.format(event.GetKey())) # Name of the virtual keycode, str
print('IsAlt: {0}'.format(event.IsAlt())) # Was the alt key depressed?, bool
print('IsExtended: {0}'.format(event.IsExtended())) # Is this an extended key?, bool
print('IsInjected: {0}'.format(event.IsInjected())) # Was this event generated programmatically?, bool
print('IsTransition: {0}'.format(event.IsTransition())) #Is this a transition from up to down or vice versa?, bool
print('ASCII: {0}'.format(event.Ascii)) # ASCII value, if one exists, str
print('KeyID: {0}'.format(event.KeyID)) # Virtual key code, int
print('ScanCode: {0}'.format(event.ScanCode)) # Scan code, int
print('Message: {0}'.format(event.Message)) # Name of the virtual keycode, str
print()
return True | [
"def",
"_handle_windows",
"(",
"self",
",",
"event",
")",
":",
"vkey",
"=",
"self",
".",
"_keyname",
"(",
"event",
".",
"GetKey",
"(",
")",
")",
"if",
"event",
".",
"Message",
"in",
"self",
".",
"KEYS_UP",
"+",
"self",
".",
"KEYS_DOWN",
":",
"if",
"vkey",
"in",
"self",
".",
"MODIFIERNAMES",
":",
"self",
".",
"_realmodifiers",
"[",
"vkey",
"]",
"=",
"event",
".",
"Message",
"in",
"self",
".",
"KEYS_DOWN",
"self",
".",
"_modifiers",
"[",
"self",
".",
"MODIFIERNAMES",
"[",
"vkey",
"]",
"]",
"=",
"self",
".",
"_realmodifiers",
"[",
"vkey",
"]",
"if",
"event",
".",
"Message",
"not",
"in",
"self",
".",
"KEYS_DOWN",
":",
"return",
"True",
"is_altgr",
"=",
"False",
"if",
"(",
"vkey",
",",
"event",
".",
"IsExtended",
"(",
")",
")",
"in",
"self",
".",
"NUMPAD_SPECIALS",
":",
"key",
"=",
"vkey",
"=",
"\"Numpad-\"",
"+",
"vkey",
"elif",
"not",
"event",
".",
"Ascii",
"or",
"vkey",
".",
"startswith",
"(",
"\"Numpad\"",
")",
":",
"key",
"=",
"vkey",
"else",
":",
"is_altgr",
"=",
"event",
".",
"Ascii",
"in",
"self",
".",
"ALT_GRS",
"key",
"=",
"self",
".",
"_keyname",
"(",
"unichr",
"(",
"event",
".",
"Ascii",
")",
")",
"if",
"DEBUG",
":",
"print",
"(",
"\"Adding key %s (real %s)\"",
"%",
"(",
"key",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"vkey",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
")",
"self",
".",
"_output",
"(",
"type",
"=",
"\"keys\"",
",",
"key",
"=",
"key",
",",
"realkey",
"=",
"vkey",
")",
"if",
"vkey",
"not",
"in",
"self",
".",
"MODIFIERNAMES",
"and",
"not",
"is_altgr",
":",
"modifier",
"=",
"\"-\"",
".",
"join",
"(",
"k",
"for",
"k",
"in",
"[",
"\"Ctrl\"",
",",
"\"Alt\"",
",",
"\"Shift\"",
",",
"\"Win\"",
"]",
"if",
"self",
".",
"_modifiers",
"[",
"k",
"]",
")",
"if",
"modifier",
"and",
"modifier",
"!=",
"\"Shift\"",
":",
"# Shift-X is not a combo\r",
"if",
"self",
".",
"_modifiers",
"[",
"\"Ctrl\"",
"]",
"and",
"event",
".",
"Ascii",
":",
"key",
"=",
"self",
".",
"_keyname",
"(",
"unichr",
"(",
"event",
".",
"KeyID",
")",
")",
"realmodifier",
"=",
"\"-\"",
".",
"join",
"(",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_realmodifiers",
".",
"items",
"(",
")",
"if",
"v",
")",
"realkey",
"=",
"\"%s-%s\"",
"%",
"(",
"realmodifier",
",",
"key",
")",
"key",
"=",
"\"%s-%s\"",
"%",
"(",
"modifier",
",",
"key",
")",
"if",
"DEBUG",
":",
"print",
"(",
"\"Adding combo %s (real %s)\"",
"%",
"(",
"key",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"realkey",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
")",
"self",
".",
"_output",
"(",
"type",
"=",
"\"combos\"",
",",
"key",
"=",
"key",
",",
"realkey",
"=",
"realkey",
")",
"if",
"DEBUG",
":",
"print",
"(",
"\"CHARACTER: %r\"",
"%",
"key",
")",
"print",
"(",
"'GetKey: {0}'",
".",
"format",
"(",
"event",
".",
"GetKey",
"(",
")",
")",
")",
"# Name of the virtual keycode, str\r",
"print",
"(",
"'IsAlt: {0}'",
".",
"format",
"(",
"event",
".",
"IsAlt",
"(",
")",
")",
")",
"# Was the alt key depressed?, bool\r",
"print",
"(",
"'IsExtended: {0}'",
".",
"format",
"(",
"event",
".",
"IsExtended",
"(",
")",
")",
")",
"# Is this an extended key?, bool\r",
"print",
"(",
"'IsInjected: {0}'",
".",
"format",
"(",
"event",
".",
"IsInjected",
"(",
")",
")",
")",
"# Was this event generated programmatically?, bool\r",
"print",
"(",
"'IsTransition: {0}'",
".",
"format",
"(",
"event",
".",
"IsTransition",
"(",
")",
")",
")",
"#Is this a transition from up to down or vice versa?, bool\r",
"print",
"(",
"'ASCII: {0}'",
".",
"format",
"(",
"event",
".",
"Ascii",
")",
")",
"# ASCII value, if one exists, str\r",
"print",
"(",
"'KeyID: {0}'",
".",
"format",
"(",
"event",
".",
"KeyID",
")",
")",
"# Virtual key code, int\r",
"print",
"(",
"'ScanCode: {0}'",
".",
"format",
"(",
"event",
".",
"ScanCode",
")",
")",
"# Scan code, int\r",
"print",
"(",
"'Message: {0}'",
".",
"format",
"(",
"event",
".",
"Message",
")",
")",
"# Name of the virtual keycode, str\r",
"print",
"(",
")",
"return",
"True"
] | Windows key event handler. | [
"Windows",
"key",
"event",
"handler",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L170-L216 | train |
suurjaak/InputScope | inputscope/listener.py | KeyHandler._handle_mac | def _handle_mac(self, keycode):
"""Mac key event handler"""
key = self._keyname(unichr(keycode))
self._output(type="keys", key=key, realkey=key) | python | def _handle_mac(self, keycode):
"""Mac key event handler"""
key = self._keyname(unichr(keycode))
self._output(type="keys", key=key, realkey=key) | [
"def",
"_handle_mac",
"(",
"self",
",",
"keycode",
")",
":",
"key",
"=",
"self",
".",
"_keyname",
"(",
"unichr",
"(",
"keycode",
")",
")",
"self",
".",
"_output",
"(",
"type",
"=",
"\"keys\"",
",",
"key",
"=",
"key",
",",
"realkey",
"=",
"key",
")"
] | Mac key event handler | [
"Mac",
"key",
"event",
"handler"
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L219-L222 | train |
suurjaak/InputScope | inputscope/listener.py | KeyHandler._handle_linux | def _handle_linux(self, keycode, character, press):
"""Linux key event handler."""
if character is None: return
key = self._keyname(character, keycode)
if key in self.MODIFIERNAMES:
self._modifiers[self.MODIFIERNAMES[key]] = press
self._realmodifiers[key] = press
if press:
self._output(type="keys", key=key, realkey=key)
if press and key not in self.MODIFIERNAMES:
modifier = "-".join(k for k in ["Ctrl", "Alt", "Shift", "Win"]
if self._modifiers[k])
if modifier and modifier != "Shift": # Shift-X is not a combo
realmodifier = "-".join(k for k, v in self._realmodifiers.items() if v)
realkey = "%s-%s" % (realmodifier, key)
key = "%s-%s" % (modifier, key)
if DEBUG: print("Adding combo %s (real %s)" % (key.encode("utf-8"), realkey.encode("utf-8")))
self._output(type="combos", key=key, realkey=realkey) | python | def _handle_linux(self, keycode, character, press):
"""Linux key event handler."""
if character is None: return
key = self._keyname(character, keycode)
if key in self.MODIFIERNAMES:
self._modifiers[self.MODIFIERNAMES[key]] = press
self._realmodifiers[key] = press
if press:
self._output(type="keys", key=key, realkey=key)
if press and key not in self.MODIFIERNAMES:
modifier = "-".join(k for k in ["Ctrl", "Alt", "Shift", "Win"]
if self._modifiers[k])
if modifier and modifier != "Shift": # Shift-X is not a combo
realmodifier = "-".join(k for k, v in self._realmodifiers.items() if v)
realkey = "%s-%s" % (realmodifier, key)
key = "%s-%s" % (modifier, key)
if DEBUG: print("Adding combo %s (real %s)" % (key.encode("utf-8"), realkey.encode("utf-8")))
self._output(type="combos", key=key, realkey=realkey) | [
"def",
"_handle_linux",
"(",
"self",
",",
"keycode",
",",
"character",
",",
"press",
")",
":",
"if",
"character",
"is",
"None",
":",
"return",
"key",
"=",
"self",
".",
"_keyname",
"(",
"character",
",",
"keycode",
")",
"if",
"key",
"in",
"self",
".",
"MODIFIERNAMES",
":",
"self",
".",
"_modifiers",
"[",
"self",
".",
"MODIFIERNAMES",
"[",
"key",
"]",
"]",
"=",
"press",
"self",
".",
"_realmodifiers",
"[",
"key",
"]",
"=",
"press",
"if",
"press",
":",
"self",
".",
"_output",
"(",
"type",
"=",
"\"keys\"",
",",
"key",
"=",
"key",
",",
"realkey",
"=",
"key",
")",
"if",
"press",
"and",
"key",
"not",
"in",
"self",
".",
"MODIFIERNAMES",
":",
"modifier",
"=",
"\"-\"",
".",
"join",
"(",
"k",
"for",
"k",
"in",
"[",
"\"Ctrl\"",
",",
"\"Alt\"",
",",
"\"Shift\"",
",",
"\"Win\"",
"]",
"if",
"self",
".",
"_modifiers",
"[",
"k",
"]",
")",
"if",
"modifier",
"and",
"modifier",
"!=",
"\"Shift\"",
":",
"# Shift-X is not a combo\r",
"realmodifier",
"=",
"\"-\"",
".",
"join",
"(",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_realmodifiers",
".",
"items",
"(",
")",
"if",
"v",
")",
"realkey",
"=",
"\"%s-%s\"",
"%",
"(",
"realmodifier",
",",
"key",
")",
"key",
"=",
"\"%s-%s\"",
"%",
"(",
"modifier",
",",
"key",
")",
"if",
"DEBUG",
":",
"print",
"(",
"\"Adding combo %s (real %s)\"",
"%",
"(",
"key",
".",
"encode",
"(",
"\"utf-8\"",
")",
",",
"realkey",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
")",
"self",
".",
"_output",
"(",
"type",
"=",
"\"combos\"",
",",
"key",
"=",
"key",
",",
"realkey",
"=",
"realkey",
")"
] | Linux key event handler. | [
"Linux",
"key",
"event",
"handler",
"."
] | 245ff045163a1995e8cd5ac558d0a93024eb86eb | https://github.com/suurjaak/InputScope/blob/245ff045163a1995e8cd5ac558d0a93024eb86eb/inputscope/listener.py#L224-L241 | train |
useblocks/groundwork | groundwork/plugins/gw_documents_info.py | GwDocumentsInfo._store_documentation | def _store_documentation(self, path, html, overwrite, quiet):
"""
Stores all documents on the file system.
Target location is **path**. File name is the lowercase name of the document + .rst.
"""
echo("Storing groundwork application documents\n")
echo("Application: %s" % self.app.name)
echo("Number of documents: %s\n" % len(self.app.documents.get()))
if not os.path.isabs(path):
path = os.path.abspath(path)
if not os.path.isdir(path):
echo("Path %s is not a directory!" % path)
sys.exit(1)
if not os.path.exists(path):
echo("Path %s does not exist" % path)
sys.exit(1)
for dirpath, dirnames, files in os.walk(path):
if files:
echo("Path %s is not empty!\n" % path)
if not overwrite:
sys.exit(1)
documents = []
for key, document in self.app.documents.get().items():
file_extension = ".html" if html else ".rst"
# lowers the name, removes all whitespaces and adds the file extension
file_name_parts = key.lower().split()
file_name = "".join(file_name_parts)
file_name += file_extension
documents.append((file_name, document))
echo("Going to write to following files:")
for document in documents:
echo(" %s" % document[0])
echo("\nTarget directory: %s" % path)
answer = None
while answer not in ["N", "Y"] and not quiet:
answer = prompt("Shall we go on? [Y]es, [N]o: ").upper()
if answer == "N":
sys.exit(0)
for document in documents:
try:
with open(os.path.join(path, document[0]), "w") as doc_file:
doc_rendered = Environment().from_string(document[1].content).render(app=self.app,
plugin=document[1].plugin)
if html:
output = publish_parts(doc_rendered, writer_name="html")['whole']
else:
output = doc_rendered
doc_file.write(output)
except Exception as e:
echo("%s error occurred: %s" % (document[0], e))
else:
echo("%s stored." % document[0]) | python | def _store_documentation(self, path, html, overwrite, quiet):
"""
Stores all documents on the file system.
Target location is **path**. File name is the lowercase name of the document + .rst.
"""
echo("Storing groundwork application documents\n")
echo("Application: %s" % self.app.name)
echo("Number of documents: %s\n" % len(self.app.documents.get()))
if not os.path.isabs(path):
path = os.path.abspath(path)
if not os.path.isdir(path):
echo("Path %s is not a directory!" % path)
sys.exit(1)
if not os.path.exists(path):
echo("Path %s does not exist" % path)
sys.exit(1)
for dirpath, dirnames, files in os.walk(path):
if files:
echo("Path %s is not empty!\n" % path)
if not overwrite:
sys.exit(1)
documents = []
for key, document in self.app.documents.get().items():
file_extension = ".html" if html else ".rst"
# lowers the name, removes all whitespaces and adds the file extension
file_name_parts = key.lower().split()
file_name = "".join(file_name_parts)
file_name += file_extension
documents.append((file_name, document))
echo("Going to write to following files:")
for document in documents:
echo(" %s" % document[0])
echo("\nTarget directory: %s" % path)
answer = None
while answer not in ["N", "Y"] and not quiet:
answer = prompt("Shall we go on? [Y]es, [N]o: ").upper()
if answer == "N":
sys.exit(0)
for document in documents:
try:
with open(os.path.join(path, document[0]), "w") as doc_file:
doc_rendered = Environment().from_string(document[1].content).render(app=self.app,
plugin=document[1].plugin)
if html:
output = publish_parts(doc_rendered, writer_name="html")['whole']
else:
output = doc_rendered
doc_file.write(output)
except Exception as e:
echo("%s error occurred: %s" % (document[0], e))
else:
echo("%s stored." % document[0]) | [
"def",
"_store_documentation",
"(",
"self",
",",
"path",
",",
"html",
",",
"overwrite",
",",
"quiet",
")",
":",
"echo",
"(",
"\"Storing groundwork application documents\\n\"",
")",
"echo",
"(",
"\"Application: %s\"",
"%",
"self",
".",
"app",
".",
"name",
")",
"echo",
"(",
"\"Number of documents: %s\\n\"",
"%",
"len",
"(",
"self",
".",
"app",
".",
"documents",
".",
"get",
"(",
")",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"echo",
"(",
"\"Path %s is not a directory!\"",
"%",
"path",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"echo",
"(",
"\"Path %s does not exist\"",
"%",
"path",
")",
"sys",
".",
"exit",
"(",
"1",
")",
"for",
"dirpath",
",",
"dirnames",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
"if",
"files",
":",
"echo",
"(",
"\"Path %s is not empty!\\n\"",
"%",
"path",
")",
"if",
"not",
"overwrite",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"documents",
"=",
"[",
"]",
"for",
"key",
",",
"document",
"in",
"self",
".",
"app",
".",
"documents",
".",
"get",
"(",
")",
".",
"items",
"(",
")",
":",
"file_extension",
"=",
"\".html\"",
"if",
"html",
"else",
"\".rst\"",
"# lowers the name, removes all whitespaces and adds the file extension",
"file_name_parts",
"=",
"key",
".",
"lower",
"(",
")",
".",
"split",
"(",
")",
"file_name",
"=",
"\"\"",
".",
"join",
"(",
"file_name_parts",
")",
"file_name",
"+=",
"file_extension",
"documents",
".",
"append",
"(",
"(",
"file_name",
",",
"document",
")",
")",
"echo",
"(",
"\"Going to write to following files:\"",
")",
"for",
"document",
"in",
"documents",
":",
"echo",
"(",
"\" %s\"",
"%",
"document",
"[",
"0",
"]",
")",
"echo",
"(",
"\"\\nTarget directory: %s\"",
"%",
"path",
")",
"answer",
"=",
"None",
"while",
"answer",
"not",
"in",
"[",
"\"N\"",
",",
"\"Y\"",
"]",
"and",
"not",
"quiet",
":",
"answer",
"=",
"prompt",
"(",
"\"Shall we go on? [Y]es, [N]o: \"",
")",
".",
"upper",
"(",
")",
"if",
"answer",
"==",
"\"N\"",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"for",
"document",
"in",
"documents",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"document",
"[",
"0",
"]",
")",
",",
"\"w\"",
")",
"as",
"doc_file",
":",
"doc_rendered",
"=",
"Environment",
"(",
")",
".",
"from_string",
"(",
"document",
"[",
"1",
"]",
".",
"content",
")",
".",
"render",
"(",
"app",
"=",
"self",
".",
"app",
",",
"plugin",
"=",
"document",
"[",
"1",
"]",
".",
"plugin",
")",
"if",
"html",
":",
"output",
"=",
"publish_parts",
"(",
"doc_rendered",
",",
"writer_name",
"=",
"\"html\"",
")",
"[",
"'whole'",
"]",
"else",
":",
"output",
"=",
"doc_rendered",
"doc_file",
".",
"write",
"(",
"output",
")",
"except",
"Exception",
"as",
"e",
":",
"echo",
"(",
"\"%s error occurred: %s\"",
"%",
"(",
"document",
"[",
"0",
"]",
",",
"e",
")",
")",
"else",
":",
"echo",
"(",
"\"%s stored.\"",
"%",
"document",
"[",
"0",
"]",
")"
] | Stores all documents on the file system.
Target location is **path**. File name is the lowercase name of the document + .rst. | [
"Stores",
"all",
"documents",
"on",
"the",
"file",
"system",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/plugins/gw_documents_info.py#L86-L150 | train |
useblocks/groundwork | groundwork/plugins/gw_documents_info.py | GwDocumentsInfo._show_documentation | def _show_documentation(self):
"""
Shows all documents of the current groundwork app in the console.
Documents are sorted bei its names, except "main", which gets set to the beginning.
"""
documents = []
for key, document in self.app.documents.get().items():
if key != "main":
documents.append((key, document))
documents = sorted(documents, key=lambda x: x[0])
main = self.app.documents.get("main")
if main is not None:
documents.insert(0, (main.name, main))
user_answer = ""
index = 0
while user_answer != "X":
if index < 0:
index = 0
if index > len(documents) - 1:
index = len(documents) - 1
document = documents[index][1]
os.system('cls' if os.name == 'nt' else 'clear')
echo(Environment().from_string(document.content).render(app=self.app, plugin=document.plugin))
source = "This document is registered by '%s' under the name '%s'" % (document.plugin.name, document.name)
echo("-" * len(source))
echo(source)
echo("-" * len(source))
commands = "Actions: "
if index < len(documents) - 1:
commands += "[N]ext, "
if index > 0:
commands += "[P]revious, "
commands += "E[x]it"
echo(commands)
if index < len(documents) - 1:
default = "N"
elif index > 0:
default = "P"
else:
default = "X"
user_answer = prompt("Select your action", default=default).upper()
if user_answer == "N":
index += 1
elif user_answer == "P":
index -= 1 | python | def _show_documentation(self):
"""
Shows all documents of the current groundwork app in the console.
Documents are sorted bei its names, except "main", which gets set to the beginning.
"""
documents = []
for key, document in self.app.documents.get().items():
if key != "main":
documents.append((key, document))
documents = sorted(documents, key=lambda x: x[0])
main = self.app.documents.get("main")
if main is not None:
documents.insert(0, (main.name, main))
user_answer = ""
index = 0
while user_answer != "X":
if index < 0:
index = 0
if index > len(documents) - 1:
index = len(documents) - 1
document = documents[index][1]
os.system('cls' if os.name == 'nt' else 'clear')
echo(Environment().from_string(document.content).render(app=self.app, plugin=document.plugin))
source = "This document is registered by '%s' under the name '%s'" % (document.plugin.name, document.name)
echo("-" * len(source))
echo(source)
echo("-" * len(source))
commands = "Actions: "
if index < len(documents) - 1:
commands += "[N]ext, "
if index > 0:
commands += "[P]revious, "
commands += "E[x]it"
echo(commands)
if index < len(documents) - 1:
default = "N"
elif index > 0:
default = "P"
else:
default = "X"
user_answer = prompt("Select your action", default=default).upper()
if user_answer == "N":
index += 1
elif user_answer == "P":
index -= 1 | [
"def",
"_show_documentation",
"(",
"self",
")",
":",
"documents",
"=",
"[",
"]",
"for",
"key",
",",
"document",
"in",
"self",
".",
"app",
".",
"documents",
".",
"get",
"(",
")",
".",
"items",
"(",
")",
":",
"if",
"key",
"!=",
"\"main\"",
":",
"documents",
".",
"append",
"(",
"(",
"key",
",",
"document",
")",
")",
"documents",
"=",
"sorted",
"(",
"documents",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"main",
"=",
"self",
".",
"app",
".",
"documents",
".",
"get",
"(",
"\"main\"",
")",
"if",
"main",
"is",
"not",
"None",
":",
"documents",
".",
"insert",
"(",
"0",
",",
"(",
"main",
".",
"name",
",",
"main",
")",
")",
"user_answer",
"=",
"\"\"",
"index",
"=",
"0",
"while",
"user_answer",
"!=",
"\"X\"",
":",
"if",
"index",
"<",
"0",
":",
"index",
"=",
"0",
"if",
"index",
">",
"len",
"(",
"documents",
")",
"-",
"1",
":",
"index",
"=",
"len",
"(",
"documents",
")",
"-",
"1",
"document",
"=",
"documents",
"[",
"index",
"]",
"[",
"1",
"]",
"os",
".",
"system",
"(",
"'cls'",
"if",
"os",
".",
"name",
"==",
"'nt'",
"else",
"'clear'",
")",
"echo",
"(",
"Environment",
"(",
")",
".",
"from_string",
"(",
"document",
".",
"content",
")",
".",
"render",
"(",
"app",
"=",
"self",
".",
"app",
",",
"plugin",
"=",
"document",
".",
"plugin",
")",
")",
"source",
"=",
"\"This document is registered by '%s' under the name '%s'\"",
"%",
"(",
"document",
".",
"plugin",
".",
"name",
",",
"document",
".",
"name",
")",
"echo",
"(",
"\"-\"",
"*",
"len",
"(",
"source",
")",
")",
"echo",
"(",
"source",
")",
"echo",
"(",
"\"-\"",
"*",
"len",
"(",
"source",
")",
")",
"commands",
"=",
"\"Actions: \"",
"if",
"index",
"<",
"len",
"(",
"documents",
")",
"-",
"1",
":",
"commands",
"+=",
"\"[N]ext, \"",
"if",
"index",
">",
"0",
":",
"commands",
"+=",
"\"[P]revious, \"",
"commands",
"+=",
"\"E[x]it\"",
"echo",
"(",
"commands",
")",
"if",
"index",
"<",
"len",
"(",
"documents",
")",
"-",
"1",
":",
"default",
"=",
"\"N\"",
"elif",
"index",
">",
"0",
":",
"default",
"=",
"\"P\"",
"else",
":",
"default",
"=",
"\"X\"",
"user_answer",
"=",
"prompt",
"(",
"\"Select your action\"",
",",
"default",
"=",
"default",
")",
".",
"upper",
"(",
")",
"if",
"user_answer",
"==",
"\"N\"",
":",
"index",
"+=",
"1",
"elif",
"user_answer",
"==",
"\"P\"",
":",
"index",
"-=",
"1"
] | Shows all documents of the current groundwork app in the console.
Documents are sorted bei its names, except "main", which gets set to the beginning. | [
"Shows",
"all",
"documents",
"of",
"the",
"current",
"groundwork",
"app",
"in",
"the",
"console",
"."
] | d34fce43f54246ca4db0f7b89e450dcdc847c68c | https://github.com/useblocks/groundwork/blob/d34fce43f54246ca4db0f7b89e450dcdc847c68c/groundwork/plugins/gw_documents_info.py#L152-L202 | train |
jenisys/parse_type | tasks/_tasklet_cleanup.py | execute_cleanup_tasks | def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False):
"""Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Collection).
:param dry_run: Indicates dry-run mode (bool)
"""
# pylint: disable=redefined-outer-name
executor = Executor(cleanup_tasks, ctx.config)
for cleanup_task in cleanup_tasks.tasks:
print("CLEANUP TASK: %s" % cleanup_task)
executor.execute((cleanup_task, dict(dry_run=dry_run))) | python | def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False):
"""Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Collection).
:param dry_run: Indicates dry-run mode (bool)
"""
# pylint: disable=redefined-outer-name
executor = Executor(cleanup_tasks, ctx.config)
for cleanup_task in cleanup_tasks.tasks:
print("CLEANUP TASK: %s" % cleanup_task)
executor.execute((cleanup_task, dict(dry_run=dry_run))) | [
"def",
"execute_cleanup_tasks",
"(",
"ctx",
",",
"cleanup_tasks",
",",
"dry_run",
"=",
"False",
")",
":",
"# pylint: disable=redefined-outer-name",
"executor",
"=",
"Executor",
"(",
"cleanup_tasks",
",",
"ctx",
".",
"config",
")",
"for",
"cleanup_task",
"in",
"cleanup_tasks",
".",
"tasks",
":",
"print",
"(",
"\"CLEANUP TASK: %s\"",
"%",
"cleanup_task",
")",
"executor",
".",
"execute",
"(",
"(",
"cleanup_task",
",",
"dict",
"(",
"dry_run",
"=",
"dry_run",
")",
")",
")"
] | Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Collection).
:param dry_run: Indicates dry-run mode (bool) | [
"Execute",
"several",
"cleanup",
"tasks",
"as",
"part",
"of",
"the",
"cleanup",
"."
] | 7cad3a67a5ca725cb786da31f656fd473084289f | https://github.com/jenisys/parse_type/blob/7cad3a67a5ca725cb786da31f656fd473084289f/tasks/_tasklet_cleanup.py#L70-L83 | train |
dbarsam/python-vsgen | vsgen/util/entrypoints.py | entrypoints | def entrypoints(section):
"""
Returns the Entry Point for a given Entry Point section.
:param str section: The section name in the entry point collection
:returns: A dictionary of (Name, Class) pairs stored in the entry point collection.
"""
return {ep.name: ep.load() for ep in pkg_resources.iter_entry_points(section)} | python | def entrypoints(section):
"""
Returns the Entry Point for a given Entry Point section.
:param str section: The section name in the entry point collection
:returns: A dictionary of (Name, Class) pairs stored in the entry point collection.
"""
return {ep.name: ep.load() for ep in pkg_resources.iter_entry_points(section)} | [
"def",
"entrypoints",
"(",
"section",
")",
":",
"return",
"{",
"ep",
".",
"name",
":",
"ep",
".",
"load",
"(",
")",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"section",
")",
"}"
] | Returns the Entry Point for a given Entry Point section.
:param str section: The section name in the entry point collection
:returns: A dictionary of (Name, Class) pairs stored in the entry point collection. | [
"Returns",
"the",
"Entry",
"Point",
"for",
"a",
"given",
"Entry",
"Point",
"section",
"."
] | 640191bb018a1ff7d7b7a4982e0d3c1a423ba878 | https://github.com/dbarsam/python-vsgen/blob/640191bb018a1ff7d7b7a4982e0d3c1a423ba878/vsgen/util/entrypoints.py#L12-L19 | train |
Subsets and Splits