id
int32
0
252k
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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
15,000
CygnusNetworks/pypureomapi
pypureomapi.py
pack_mac
def pack_mac(macstr): """Converts a mac address given in colon delimited notation to a six byte string in network byte order. >>> pack_mac("30:31:32:33:34:35") == b'012345' True >>> pack_mac("bad") Traceback (most recent call last): ... ValueError: given mac addresses has an invalid number of colons @type macstr: str @rtype: bytes @raises ValueError: for badly formatted mac addresses """ if not isinstance(macstr, basestring): raise ValueError("given mac addresses is not a string") parts = macstr.split(":") if len(parts) != 6: raise ValueError("given mac addresses has an invalid number of colons") parts = [int(part, 16) for part in parts] # raises ValueError return int_seq_to_bytes(parts)
python
def pack_mac(macstr): if not isinstance(macstr, basestring): raise ValueError("given mac addresses is not a string") parts = macstr.split(":") if len(parts) != 6: raise ValueError("given mac addresses has an invalid number of colons") parts = [int(part, 16) for part in parts] # raises ValueError return int_seq_to_bytes(parts)
[ "def", "pack_mac", "(", "macstr", ")", ":", "if", "not", "isinstance", "(", "macstr", ",", "basestring", ")", ":", "raise", "ValueError", "(", "\"given mac addresses is not a string\"", ")", "parts", "=", "macstr", ".", "split", "(", "\":\"", ")", "if", "len...
Converts a mac address given in colon delimited notation to a six byte string in network byte order. >>> pack_mac("30:31:32:33:34:35") == b'012345' True >>> pack_mac("bad") Traceback (most recent call last): ... ValueError: given mac addresses has an invalid number of colons @type macstr: str @rtype: bytes @raises ValueError: for badly formatted mac addresses
[ "Converts", "a", "mac", "address", "given", "in", "colon", "delimited", "notation", "to", "a", "six", "byte", "string", "in", "network", "byte", "order", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L776-L798
15,001
CygnusNetworks/pypureomapi
pypureomapi.py
unpack_mac
def unpack_mac(sixbytes): """Converts a mac address given in a six byte string in network byte order to a string in colon delimited notation. >>> unpack_mac(b"012345") '30:31:32:33:34:35' >>> unpack_mac(b"bad") Traceback (most recent call last): ... ValueError: given buffer is not exactly six bytes long @type sixbytes: bytes @rtype: str @raises ValueError: for bad input """ if not isinstance(sixbytes, bytes): raise ValueError("given buffer is not a string") if len(sixbytes) != 6: raise ValueError("given buffer is not exactly six bytes long") return ":".join(["%2.2x".__mod__(x) for x in bytes_to_int_seq(sixbytes)])
python
def unpack_mac(sixbytes): if not isinstance(sixbytes, bytes): raise ValueError("given buffer is not a string") if len(sixbytes) != 6: raise ValueError("given buffer is not exactly six bytes long") return ":".join(["%2.2x".__mod__(x) for x in bytes_to_int_seq(sixbytes)])
[ "def", "unpack_mac", "(", "sixbytes", ")", ":", "if", "not", "isinstance", "(", "sixbytes", ",", "bytes", ")", ":", "raise", "ValueError", "(", "\"given buffer is not a string\"", ")", "if", "len", "(", "sixbytes", ")", "!=", "6", ":", "raise", "ValueError",...
Converts a mac address given in a six byte string in network byte order to a string in colon delimited notation. >>> unpack_mac(b"012345") '30:31:32:33:34:35' >>> unpack_mac(b"bad") Traceback (most recent call last): ... ValueError: given buffer is not exactly six bytes long @type sixbytes: bytes @rtype: str @raises ValueError: for bad input
[ "Converts", "a", "mac", "address", "given", "in", "a", "six", "byte", "string", "in", "network", "byte", "order", "to", "a", "string", "in", "colon", "delimited", "notation", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L804-L823
15,002
CygnusNetworks/pypureomapi
pypureomapi.py
OmapiStartupMessage.validate
def validate(self): """Checks whether this OmapiStartupMessage matches the implementation. @raises OmapiError: """ if self.implemented_protocol_version != self.protocol_version: raise OmapiError("protocol mismatch") if self.implemented_header_size != self.header_size: raise OmapiError("header size mismatch")
python
def validate(self): if self.implemented_protocol_version != self.protocol_version: raise OmapiError("protocol mismatch") if self.implemented_header_size != self.header_size: raise OmapiError("header size mismatch")
[ "def", "validate", "(", "self", ")", ":", "if", "self", ".", "implemented_protocol_version", "!=", "self", ".", "protocol_version", ":", "raise", "OmapiError", "(", "\"protocol mismatch\"", ")", "if", "self", ".", "implemented_header_size", "!=", "self", ".", "h...
Checks whether this OmapiStartupMessage matches the implementation. @raises OmapiError:
[ "Checks", "whether", "this", "OmapiStartupMessage", "matches", "the", "implementation", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L263-L270
15,003
CygnusNetworks/pypureomapi
pypureomapi.py
OmapiStartupMessage.serialize
def serialize(self, outbuffer): """Serialize this OmapiStartupMessage to the given outbuffer. @type outbuffer: OutBuffer """ outbuffer.add_net32int(self.protocol_version) outbuffer.add_net32int(self.header_size)
python
def serialize(self, outbuffer): outbuffer.add_net32int(self.protocol_version) outbuffer.add_net32int(self.header_size)
[ "def", "serialize", "(", "self", ",", "outbuffer", ")", ":", "outbuffer", ".", "add_net32int", "(", "self", ".", "protocol_version", ")", "outbuffer", ".", "add_net32int", "(", "self", ".", "header_size", ")" ]
Serialize this OmapiStartupMessage to the given outbuffer. @type outbuffer: OutBuffer
[ "Serialize", "this", "OmapiStartupMessage", "to", "the", "given", "outbuffer", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L280-L285
15,004
CygnusNetworks/pypureomapi
pypureomapi.py
OmapiMessage.sign
def sign(self, authenticator): """Sign this OMAPI message. @type authenticator: OmapiAuthenticatorBase """ self.authid = authenticator.authid self.signature = b"\0" * authenticator.authlen # provide authlen self.signature = authenticator.sign(self.as_string(forsigning=True)) assert len(self.signature) == authenticator.authlen
python
def sign(self, authenticator): self.authid = authenticator.authid self.signature = b"\0" * authenticator.authlen # provide authlen self.signature = authenticator.sign(self.as_string(forsigning=True)) assert len(self.signature) == authenticator.authlen
[ "def", "sign", "(", "self", ",", "authenticator", ")", ":", "self", ".", "authid", "=", "authenticator", ".", "authid", "self", ".", "signature", "=", "b\"\\0\"", "*", "authenticator", ".", "authlen", "# provide authlen", "self", ".", "signature", "=", "auth...
Sign this OMAPI message. @type authenticator: OmapiAuthenticatorBase
[ "Sign", "this", "OMAPI", "message", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L462-L469
15,005
CygnusNetworks/pypureomapi
pypureomapi.py
OmapiMessage.verify
def verify(self, authenticators): """Verify this OMAPI message. >>> a1 = OmapiHMACMD5Authenticator(b"egg", b"spam") >>> a2 = OmapiHMACMD5Authenticator(b"egg", b"tomatoes") >>> a1.authid = a2.authid = 5 >>> m = OmapiMessage.open(b"host") >>> m.verify({a1.authid: a1}) False >>> m.sign(a1) >>> m.verify({a1.authid: a1}) True >>> m.sign(a2) >>> m.verify({a1.authid: a1}) False @type authenticators: {int: OmapiAuthenticatorBase} @rtype: bool """ try: return authenticators[self.authid]. sign(self.as_string(forsigning=True)) == self.signature except KeyError: return False
python
def verify(self, authenticators): try: return authenticators[self.authid]. sign(self.as_string(forsigning=True)) == self.signature except KeyError: return False
[ "def", "verify", "(", "self", ",", "authenticators", ")", ":", "try", ":", "return", "authenticators", "[", "self", ".", "authid", "]", ".", "sign", "(", "self", ".", "as_string", "(", "forsigning", "=", "True", ")", ")", "==", "self", ".", "signature"...
Verify this OMAPI message. >>> a1 = OmapiHMACMD5Authenticator(b"egg", b"spam") >>> a2 = OmapiHMACMD5Authenticator(b"egg", b"tomatoes") >>> a1.authid = a2.authid = 5 >>> m = OmapiMessage.open(b"host") >>> m.verify({a1.authid: a1}) False >>> m.sign(a1) >>> m.verify({a1.authid: a1}) True >>> m.sign(a2) >>> m.verify({a1.authid: a1}) False @type authenticators: {int: OmapiAuthenticatorBase} @rtype: bool
[ "Verify", "this", "OMAPI", "message", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L471-L493
15,006
CygnusNetworks/pypureomapi
pypureomapi.py
OmapiMessage.open
def open(cls, typename): """Create an OMAPI open message with given typename. @type typename: bytes @rtype: OmapiMessage """ return cls(opcode=OMAPI_OP_OPEN, message=[(b"type", typename)], tid=-1)
python
def open(cls, typename): return cls(opcode=OMAPI_OP_OPEN, message=[(b"type", typename)], tid=-1)
[ "def", "open", "(", "cls", ",", "typename", ")", ":", "return", "cls", "(", "opcode", "=", "OMAPI_OP_OPEN", ",", "message", "=", "[", "(", "b\"type\"", ",", "typename", ")", "]", ",", "tid", "=", "-", "1", ")" ]
Create an OMAPI open message with given typename. @type typename: bytes @rtype: OmapiMessage
[ "Create", "an", "OMAPI", "open", "message", "with", "given", "typename", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L496-L501
15,007
CygnusNetworks/pypureomapi
pypureomapi.py
InBuffer.parse_startup_message
def parse_startup_message(self): """results in an OmapiStartupMessage >>> d = b"\\0\\0\\0\\x64\\0\\0\\0\\x18" >>> next(InBuffer(d).parse_startup_message()).validate() """ return parse_map(lambda args: OmapiStartupMessage(*args), parse_chain(self.parse_net32int, lambda _: self.parse_net32int()))
python
def parse_startup_message(self): return parse_map(lambda args: OmapiStartupMessage(*args), parse_chain(self.parse_net32int, lambda _: self.parse_net32int()))
[ "def", "parse_startup_message", "(", "self", ")", ":", "return", "parse_map", "(", "lambda", "args", ":", "OmapiStartupMessage", "(", "*", "args", ")", ",", "parse_chain", "(", "self", ".", "parse_net32int", ",", "lambda", "_", ":", "self", ".", "parse_net32...
results in an OmapiStartupMessage >>> d = b"\\0\\0\\0\\x64\\0\\0\\0\\x18" >>> next(InBuffer(d).parse_startup_message()).validate()
[ "results", "in", "an", "OmapiStartupMessage" ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L686-L692
15,008
CygnusNetworks/pypureomapi
pypureomapi.py
InBuffer.parse_message
def parse_message(self): """results in an OmapiMessage""" parser = parse_chain(self.parse_net32int, # authid lambda *_: self.parse_net32int(), # authlen lambda *_: self.parse_net32int(), # opcode lambda *_: self.parse_net32int(), # handle lambda *_: self.parse_net32int(), # tid lambda *_: self.parse_net32int(), # rid lambda *_: self.parse_bindict(), # message lambda *_: self.parse_bindict(), # object lambda *args: self.parse_fixedbuffer(args[1])) # signature return parse_map(lambda args: # skip authlen in args: OmapiMessage(*(args[0:1] + args[2:])), parser)
python
def parse_message(self): parser = parse_chain(self.parse_net32int, # authid lambda *_: self.parse_net32int(), # authlen lambda *_: self.parse_net32int(), # opcode lambda *_: self.parse_net32int(), # handle lambda *_: self.parse_net32int(), # tid lambda *_: self.parse_net32int(), # rid lambda *_: self.parse_bindict(), # message lambda *_: self.parse_bindict(), # object lambda *args: self.parse_fixedbuffer(args[1])) # signature return parse_map(lambda args: # skip authlen in args: OmapiMessage(*(args[0:1] + args[2:])), parser)
[ "def", "parse_message", "(", "self", ")", ":", "parser", "=", "parse_chain", "(", "self", ".", "parse_net32int", ",", "# authid", "lambda", "*", "_", ":", "self", ".", "parse_net32int", "(", ")", ",", "# authlen", "lambda", "*", "_", ":", "self", ".", ...
results in an OmapiMessage
[ "results", "in", "an", "OmapiMessage" ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L694-L706
15,009
CygnusNetworks/pypureomapi
pypureomapi.py
TCPClientTransport.fill_inbuffer
def fill_inbuffer(self): """Read bytes from the connection and hand them to the protocol. @raises OmapiError: @raises socket.error: """ if not self.connection: raise OmapiError("not connected") try: data = self.connection.recv(2048) except socket.error: self.close() raise if not data: self.close() raise OmapiError("connection closed") try: self.protocol.data_received(data) except OmapiSizeLimitError: self.close() raise
python
def fill_inbuffer(self): if not self.connection: raise OmapiError("not connected") try: data = self.connection.recv(2048) except socket.error: self.close() raise if not data: self.close() raise OmapiError("connection closed") try: self.protocol.data_received(data) except OmapiSizeLimitError: self.close() raise
[ "def", "fill_inbuffer", "(", "self", ")", ":", "if", "not", "self", ".", "connection", ":", "raise", "OmapiError", "(", "\"not connected\"", ")", "try", ":", "data", "=", "self", ".", "connection", ".", "recv", "(", "2048", ")", "except", "socket", ".", ...
Read bytes from the connection and hand them to the protocol. @raises OmapiError: @raises socket.error:
[ "Read", "bytes", "from", "the", "connection", "and", "hand", "them", "to", "the", "protocol", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L849-L868
15,010
CygnusNetworks/pypureomapi
pypureomapi.py
TCPClientTransport.write
def write(self, data): """Send all of data to the connection. @type data: bytes @raises socket.error: """ try: self.connection.sendall(data) except socket.error: self.close() raise
python
def write(self, data): try: self.connection.sendall(data) except socket.error: self.close() raise
[ "def", "write", "(", "self", ",", "data", ")", ":", "try", ":", "self", ".", "connection", ".", "sendall", "(", "data", ")", "except", "socket", ".", "error", ":", "self", ".", "close", "(", ")", "raise" ]
Send all of data to the connection. @type data: bytes @raises socket.error:
[ "Send", "all", "of", "data", "to", "the", "connection", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L870-L880
15,011
CygnusNetworks/pypureomapi
pypureomapi.py
OmapiProtocol.send_message
def send_message(self, message, sign=True): """Send the given message to the connection. @type message: OmapiMessage @param sign: whether the message needs to be signed @raises OmapiError: @raises socket.error: """ if sign: message.sign(self.authenticators[self.defauth]) logger.debug("sending %s", LazyStr(message.dump_oneline)) self.transport.write(message.as_string())
python
def send_message(self, message, sign=True): if sign: message.sign(self.authenticators[self.defauth]) logger.debug("sending %s", LazyStr(message.dump_oneline)) self.transport.write(message.as_string())
[ "def", "send_message", "(", "self", ",", "message", ",", "sign", "=", "True", ")", ":", "if", "sign", ":", "message", ".", "sign", "(", "self", ".", "authenticators", "[", "self", ".", "defauth", "]", ")", "logger", ".", "debug", "(", "\"sending %s\"",...
Send the given message to the connection. @type message: OmapiMessage @param sign: whether the message needs to be signed @raises OmapiError: @raises socket.error:
[ "Send", "the", "given", "message", "to", "the", "connection", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L937-L948
15,012
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.receive_message
def receive_message(self): """Read the next message from the connection. @rtype: OmapiMessage @raises OmapiError: @raises socket.error: """ while not self.recv_message_queue: self.transport.fill_inbuffer() message = self.recv_message_queue.pop(0) assert message is not None if not message.verify(self.protocol.authenticators): self.close() raise OmapiError("bad omapi message signature") return message
python
def receive_message(self): while not self.recv_message_queue: self.transport.fill_inbuffer() message = self.recv_message_queue.pop(0) assert message is not None if not message.verify(self.protocol.authenticators): self.close() raise OmapiError("bad omapi message signature") return message
[ "def", "receive_message", "(", "self", ")", ":", "while", "not", "self", ".", "recv_message_queue", ":", "self", ".", "transport", ".", "fill_inbuffer", "(", ")", "message", "=", "self", ".", "recv_message_queue", ".", "pop", "(", "0", ")", "assert", "mess...
Read the next message from the connection. @rtype: OmapiMessage @raises OmapiError: @raises socket.error:
[ "Read", "the", "next", "message", "from", "the", "connection", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1005-L1018
15,013
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.receive_response
def receive_response(self, message, insecure=False): """Read the response for the given message. @type message: OmapiMessage @type insecure: bool @param insecure: avoid an OmapiError about a wrong authenticator @rtype: OmapiMessage @raises OmapiError: @raises socket.error: """ response = self.receive_message() if not response.is_response(message): raise OmapiError("received message is not the desired response") # signature already verified if response.authid != self.protocol.defauth and not insecure: raise OmapiError("received message is signed with wrong authenticator") return response
python
def receive_response(self, message, insecure=False): response = self.receive_message() if not response.is_response(message): raise OmapiError("received message is not the desired response") # signature already verified if response.authid != self.protocol.defauth and not insecure: raise OmapiError("received message is signed with wrong authenticator") return response
[ "def", "receive_response", "(", "self", ",", "message", ",", "insecure", "=", "False", ")", ":", "response", "=", "self", ".", "receive_message", "(", ")", "if", "not", "response", ".", "is_response", "(", "message", ")", ":", "raise", "OmapiError", "(", ...
Read the response for the given message. @type message: OmapiMessage @type insecure: bool @param insecure: avoid an OmapiError about a wrong authenticator @rtype: OmapiMessage @raises OmapiError: @raises socket.error:
[ "Read", "the", "response", "for", "the", "given", "message", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1020-L1035
15,014
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.send_message
def send_message(self, message, sign=True): """Sends the given message to the connection. @type message: OmapiMessage @type sign: bool @param sign: whether the message needs to be signed @raises OmapiError: @raises socket.error: """ self.check_connected() self.protocol.send_message(message, sign)
python
def send_message(self, message, sign=True): self.check_connected() self.protocol.send_message(message, sign)
[ "def", "send_message", "(", "self", ",", "message", ",", "sign", "=", "True", ")", ":", "self", ".", "check_connected", "(", ")", "self", ".", "protocol", ".", "send_message", "(", "message", ",", "sign", ")" ]
Sends the given message to the connection. @type message: OmapiMessage @type sign: bool @param sign: whether the message needs to be signed @raises OmapiError: @raises socket.error:
[ "Sends", "the", "given", "message", "to", "the", "connection", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1037-L1046
15,015
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.lookup_ip_host
def lookup_ip_host(self, mac): """Lookup a host object with with given mac address. @type mac: str @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given mac could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a ip @raises socket.error: """ res = self.lookup_by_host(mac=mac) try: return res["ip-address"] except KeyError: raise OmapiErrorAttributeNotFound()
python
def lookup_ip_host(self, mac): res = self.lookup_by_host(mac=mac) try: return res["ip-address"] except KeyError: raise OmapiErrorAttributeNotFound()
[ "def", "lookup_ip_host", "(", "self", ",", "mac", ")", ":", "res", "=", "self", ".", "lookup_by_host", "(", "mac", "=", "mac", ")", "try", ":", "return", "res", "[", "\"ip-address\"", "]", "except", "KeyError", ":", "raise", "OmapiErrorAttributeNotFound", ...
Lookup a host object with with given mac address. @type mac: str @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given mac could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a ip @raises socket.error:
[ "Lookup", "a", "host", "object", "with", "with", "given", "mac", "address", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1077-L1091
15,016
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.lookup_ip
def lookup_ip(self, mac): """Look for a lease object with given mac address and return the assigned ip address. @type mac: str @rtype: str or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given mac could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a ip @raises socket.error: """ res = self.lookup_by_lease(mac=mac) try: return res["ip-address"] except KeyError: raise OmapiErrorAttributeNotFound()
python
def lookup_ip(self, mac): res = self.lookup_by_lease(mac=mac) try: return res["ip-address"] except KeyError: raise OmapiErrorAttributeNotFound()
[ "def", "lookup_ip", "(", "self", ",", "mac", ")", ":", "res", "=", "self", ".", "lookup_by_lease", "(", "mac", "=", "mac", ")", "try", ":", "return", "res", "[", "\"ip-address\"", "]", "except", "KeyError", ":", "raise", "OmapiErrorAttributeNotFound", "(",...
Look for a lease object with given mac address and return the assigned ip address. @type mac: str @rtype: str or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given mac could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a ip @raises socket.error:
[ "Look", "for", "a", "lease", "object", "with", "given", "mac", "address", "and", "return", "the", "assigned", "ip", "address", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1093-L1109
15,017
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.lookup_mac
def lookup_mac(self, ip): """Look up a lease object with given ip address and return the associated mac address. @type ip: str @rtype: str or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given ip could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a mac @raises socket.error: """ res = self.lookup_by_lease(ip=ip) try: return res["hardware-address"] except KeyError: raise OmapiErrorAttributeNotFound()
python
def lookup_mac(self, ip): res = self.lookup_by_lease(ip=ip) try: return res["hardware-address"] except KeyError: raise OmapiErrorAttributeNotFound()
[ "def", "lookup_mac", "(", "self", ",", "ip", ")", ":", "res", "=", "self", ".", "lookup_by_lease", "(", "ip", "=", "ip", ")", "try", ":", "return", "res", "[", "\"hardware-address\"", "]", "except", "KeyError", ":", "raise", "OmapiErrorAttributeNotFound", ...
Look up a lease object with given ip address and return the associated mac address. @type ip: str @rtype: str or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given ip could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a mac @raises socket.error:
[ "Look", "up", "a", "lease", "object", "with", "given", "ip", "address", "and", "return", "the", "associated", "mac", "address", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1111-L1127
15,018
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.lookup_host
def lookup_host(self, name): """Look for a host object with given name and return the name, mac, and ip address @type name: str @rtype: dict or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no host object with the given name could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks ip, mac or name @raises socket.error: """ res = self.lookup_by_host(name=name) try: return dict(ip=res["ip-address"], mac=res["hardware-address"], hostname=res["name"].decode('utf-8')) except KeyError: raise OmapiErrorAttributeNotFound()
python
def lookup_host(self, name): res = self.lookup_by_host(name=name) try: return dict(ip=res["ip-address"], mac=res["hardware-address"], hostname=res["name"].decode('utf-8')) except KeyError: raise OmapiErrorAttributeNotFound()
[ "def", "lookup_host", "(", "self", ",", "name", ")", ":", "res", "=", "self", ".", "lookup_by_host", "(", "name", "=", "name", ")", "try", ":", "return", "dict", "(", "ip", "=", "res", "[", "\"ip-address\"", "]", ",", "mac", "=", "res", "[", "\"har...
Look for a host object with given name and return the name, mac, and ip address @type name: str @rtype: dict or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no host object with the given name could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks ip, mac or name @raises socket.error:
[ "Look", "for", "a", "host", "object", "with", "given", "name", "and", "return", "the", "name", "mac", "and", "ip", "address" ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1129-L1145
15,019
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.lookup_host_host
def lookup_host_host(self, mac): """Look for a host object with given mac address and return the name, mac, and ip address @type mac: str @rtype: dict or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no host object with the given mac address could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks ip, mac or name @raises socket.error: """ res = self.lookup_by_host(mac=mac) try: return dict(ip=res["ip-address"], mac=res["hardware-address"], name=res["name"].decode('utf-8')) except KeyError: raise OmapiErrorAttributeNotFound()
python
def lookup_host_host(self, mac): res = self.lookup_by_host(mac=mac) try: return dict(ip=res["ip-address"], mac=res["hardware-address"], name=res["name"].decode('utf-8')) except KeyError: raise OmapiErrorAttributeNotFound()
[ "def", "lookup_host_host", "(", "self", ",", "mac", ")", ":", "res", "=", "self", ".", "lookup_by_host", "(", "mac", "=", "mac", ")", "try", ":", "return", "dict", "(", "ip", "=", "res", "[", "\"ip-address\"", "]", ",", "mac", "=", "res", "[", "\"h...
Look for a host object with given mac address and return the name, mac, and ip address @type mac: str @rtype: dict or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no host object with the given mac address could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks ip, mac or name @raises socket.error:
[ "Look", "for", "a", "host", "object", "with", "given", "mac", "address", "and", "return", "the", "name", "mac", "and", "ip", "address" ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1147-L1163
15,020
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.lookup_hostname
def lookup_hostname(self, ip): """Look up a lease object with given ip address and return the associated client hostname. @type ip: str @rtype: str or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given ip address could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a hostname @raises socket.error: """ res = self.lookup_by_lease(ip=ip) if "client-hostname" not in res: raise OmapiErrorAttributeNotFound() return res["client-hostname"].decode('utf-8')
python
def lookup_hostname(self, ip): res = self.lookup_by_lease(ip=ip) if "client-hostname" not in res: raise OmapiErrorAttributeNotFound() return res["client-hostname"].decode('utf-8')
[ "def", "lookup_hostname", "(", "self", ",", "ip", ")", ":", "res", "=", "self", ".", "lookup_by_lease", "(", "ip", "=", "ip", ")", "if", "\"client-hostname\"", "not", "in", "res", ":", "raise", "OmapiErrorAttributeNotFound", "(", ")", "return", "res", "[",...
Look up a lease object with given ip address and return the associated client hostname. @type ip: str @rtype: str or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given ip address could be found @raises OmapiErrorAttributeNotFound: if lease could be found, but objects lacks a hostname @raises socket.error:
[ "Look", "up", "a", "lease", "object", "with", "given", "ip", "address", "and", "return", "the", "associated", "client", "hostname", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1165-L1179
15,021
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.__lookup
def __lookup(self, ltype, **kwargs): """Generic Lookup function @type ltype: str @type rvalues: list @type ip: str @type mac: str @type name: str @rtype: dict or str (if len(rvalues) == 1) or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no host object with the given name could be found or the object lacks an ip address or mac @raises socket.error: """ ltype_utf = ltype.encode("utf-8") assert ltype_utf in [b"host", b"lease"] msg = OmapiMessage.open(ltype_utf) for k in kwargs: if k == "raw": continue _k = k.replace("_", "-") if _k in ["ip", "ip-address"]: msg.obj.append((b"ip-address", pack_ip(kwargs[k]))) elif _k in ["mac", "hardware-address"]: msg.obj.append((b"hardware-address", pack_mac(kwargs[k]))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) elif _k == "name": msg.obj.append((b"name", kwargs[k].encode('utf-8'))) else: msg.obj.append((str(k).encode(), kwargs[k].encode('utf-8'))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiErrorNotFound() if "raw" in kwargs and kwargs["raw"]: return dict(response.obj) res = dict() for k, v in dict(response.obj).items(): _k = k.decode('utf-8') try: if _k == "ip-address": v = unpack_ip(v) elif _k in ["hardware-address"]: v = unpack_mac(v) elif _k in ["starts", "ends", "tstp", "tsfp", "atsfp", "cltt", "subnet", "pool", "state", "hardware-type"]: v = struct.unpack(">I", v)[0] elif _k in ["flags"]: v = struct.unpack(">I", v)[0] except struct.error: pass res[_k] = v return res
python
def __lookup(self, ltype, **kwargs): ltype_utf = ltype.encode("utf-8") assert ltype_utf in [b"host", b"lease"] msg = OmapiMessage.open(ltype_utf) for k in kwargs: if k == "raw": continue _k = k.replace("_", "-") if _k in ["ip", "ip-address"]: msg.obj.append((b"ip-address", pack_ip(kwargs[k]))) elif _k in ["mac", "hardware-address"]: msg.obj.append((b"hardware-address", pack_mac(kwargs[k]))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) elif _k == "name": msg.obj.append((b"name", kwargs[k].encode('utf-8'))) else: msg.obj.append((str(k).encode(), kwargs[k].encode('utf-8'))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiErrorNotFound() if "raw" in kwargs and kwargs["raw"]: return dict(response.obj) res = dict() for k, v in dict(response.obj).items(): _k = k.decode('utf-8') try: if _k == "ip-address": v = unpack_ip(v) elif _k in ["hardware-address"]: v = unpack_mac(v) elif _k in ["starts", "ends", "tstp", "tsfp", "atsfp", "cltt", "subnet", "pool", "state", "hardware-type"]: v = struct.unpack(">I", v)[0] elif _k in ["flags"]: v = struct.unpack(">I", v)[0] except struct.error: pass res[_k] = v return res
[ "def", "__lookup", "(", "self", ",", "ltype", ",", "*", "*", "kwargs", ")", ":", "ltype_utf", "=", "ltype", ".", "encode", "(", "\"utf-8\"", ")", "assert", "ltype_utf", "in", "[", "b\"host\"", ",", "b\"lease\"", "]", "msg", "=", "OmapiMessage", ".", "o...
Generic Lookup function @type ltype: str @type rvalues: list @type ip: str @type mac: str @type name: str @rtype: dict or str (if len(rvalues) == 1) or None @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no host object with the given name could be found or the object lacks an ip address or mac @raises socket.error:
[ "Generic", "Lookup", "function" ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1187-L1238
15,022
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.add_host
def add_host(self, ip, mac): """Create a host object with given ip address and and mac address. @type ip: str @type mac: str @raises ValueError: @raises OmapiError: @raises socket.error: """ msg = OmapiMessage.open(b"host") msg.message.append((b"create", struct.pack("!I", 1))) msg.message.append((b"exclusive", struct.pack("!I", 1))) msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) msg.obj.append((b"ip-address", pack_ip(ip))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
python
def add_host(self, ip, mac): msg = OmapiMessage.open(b"host") msg.message.append((b"create", struct.pack("!I", 1))) msg.message.append((b"exclusive", struct.pack("!I", 1))) msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) msg.obj.append((b"ip-address", pack_ip(ip))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
[ "def", "add_host", "(", "self", ",", "ip", ",", "mac", ")", ":", "msg", "=", "OmapiMessage", ".", "open", "(", "b\"host\"", ")", "msg", ".", "message", ".", "append", "(", "(", "b\"create\"", ",", "struct", ".", "pack", "(", "\"!I\"", ",", "1", ")"...
Create a host object with given ip address and and mac address. @type ip: str @type mac: str @raises ValueError: @raises OmapiError: @raises socket.error:
[ "Create", "a", "host", "object", "with", "given", "ip", "address", "and", "and", "mac", "address", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1240-L1257
15,023
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.add_host_supersede_name
def add_host_supersede_name(self, ip, mac, name): # pylint:disable=E0213 """Add a host with a fixed-address and override its hostname with the given name. @type self: Omapi @type ip: str @type mac: str @type name: str @raises ValueError: @raises OmapiError: @raises socket.error: """ msg = OmapiMessage.open(b"host") msg.message.append((b"create", struct.pack("!I", 1))) msg.message.append((b"exclusive", struct.pack("!I", 1))) msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) msg.obj.append((b"ip-address", pack_ip(ip))) msg.obj.append((b"name", name.encode('utf-8'))) msg.obj.append((b"statements", 'supersede host-name "{0}";'.format(name).encode('utf-8'))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
python
def add_host_supersede_name(self, ip, mac, name): # pylint:disable=E0213 msg = OmapiMessage.open(b"host") msg.message.append((b"create", struct.pack("!I", 1))) msg.message.append((b"exclusive", struct.pack("!I", 1))) msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) msg.obj.append((b"ip-address", pack_ip(ip))) msg.obj.append((b"name", name.encode('utf-8'))) msg.obj.append((b"statements", 'supersede host-name "{0}";'.format(name).encode('utf-8'))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
[ "def", "add_host_supersede_name", "(", "self", ",", "ip", ",", "mac", ",", "name", ")", ":", "# pylint:disable=E0213", "msg", "=", "OmapiMessage", ".", "open", "(", "b\"host\"", ")", "msg", ".", "message", ".", "append", "(", "(", "b\"create\"", ",", "stru...
Add a host with a fixed-address and override its hostname with the given name. @type self: Omapi @type ip: str @type mac: str @type name: str @raises ValueError: @raises OmapiError: @raises socket.error:
[ "Add", "a", "host", "with", "a", "fixed", "-", "address", "and", "override", "its", "hostname", "with", "the", "given", "name", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1259-L1279
15,024
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.add_host_supersede
def add_host_supersede(self, ip, mac, name, hostname=None, router=None, domain=None): # pylint:disable=too-many-arguments """Create a host object with given ip, mac, name, hostname, router and domain. hostname, router and domain are optional arguments. @type ip: str @type mac: str @type name: str @type hostname: str @type router: str @type domain: str @raises OmapiError: @raises socket.error: """ stmts = [] msg = OmapiMessage.open(b"host") msg.message.append((b"create", struct.pack("!I", 1))) msg.obj.append((b"name", name)) msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) msg.obj.append((b"ip-address", pack_ip(ip))) if hostname: stmts.append('supersede host-name "{0}";\n '.format(hostname)) if router: stmts.append('supersede routers {0};\n '.format(router)) if domain: stmts.append('supersede domain-name "{0}";'.format(domain)) if stmts: encoded_stmts = "".join(stmts).encode("utf-8") msg.obj.append((b"statements", encoded_stmts)) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
python
def add_host_supersede(self, ip, mac, name, hostname=None, router=None, domain=None): # pylint:disable=too-many-arguments stmts = [] msg = OmapiMessage.open(b"host") msg.message.append((b"create", struct.pack("!I", 1))) msg.obj.append((b"name", name)) msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) msg.obj.append((b"ip-address", pack_ip(ip))) if hostname: stmts.append('supersede host-name "{0}";\n '.format(hostname)) if router: stmts.append('supersede routers {0};\n '.format(router)) if domain: stmts.append('supersede domain-name "{0}";'.format(domain)) if stmts: encoded_stmts = "".join(stmts).encode("utf-8") msg.obj.append((b"statements", encoded_stmts)) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
[ "def", "add_host_supersede", "(", "self", ",", "ip", ",", "mac", ",", "name", ",", "hostname", "=", "None", ",", "router", "=", "None", ",", "domain", "=", "None", ")", ":", "# pylint:disable=too-many-arguments", "stmts", "=", "[", "]", "msg", "=", "Omap...
Create a host object with given ip, mac, name, hostname, router and domain. hostname, router and domain are optional arguments. @type ip: str @type mac: str @type name: str @type hostname: str @type router: str @type domain: str @raises OmapiError: @raises socket.error:
[ "Create", "a", "host", "object", "with", "given", "ip", "mac", "name", "hostname", "router", "and", "domain", ".", "hostname", "router", "and", "domain", "are", "optional", "arguments", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1297-L1330
15,025
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.del_host
def del_host(self, mac): """Delete a host object with with given mac address. @type mac: str @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given mac address could be found @raises socket.error: """ msg = OmapiMessage.open(b"host") msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiErrorNotFound() if response.handle == 0: raise OmapiError("received invalid handle from server") response = self.query_server(OmapiMessage.delete(response.handle)) if response.opcode != OMAPI_OP_STATUS: raise OmapiError("delete failed")
python
def del_host(self, mac): msg = OmapiMessage.open(b"host") msg.obj.append((b"hardware-address", pack_mac(mac))) msg.obj.append((b"hardware-type", struct.pack("!I", 1))) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiErrorNotFound() if response.handle == 0: raise OmapiError("received invalid handle from server") response = self.query_server(OmapiMessage.delete(response.handle)) if response.opcode != OMAPI_OP_STATUS: raise OmapiError("delete failed")
[ "def", "del_host", "(", "self", ",", "mac", ")", ":", "msg", "=", "OmapiMessage", ".", "open", "(", "b\"host\"", ")", "msg", ".", "obj", ".", "append", "(", "(", "b\"hardware-address\"", ",", "pack_mac", "(", "mac", ")", ")", ")", "msg", ".", "obj", ...
Delete a host object with with given mac address. @type mac: str @raises ValueError: @raises OmapiError: @raises OmapiErrorNotFound: if no lease object with the given mac address could be found @raises socket.error:
[ "Delete", "a", "host", "object", "with", "with", "given", "mac", "address", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1332-L1352
15,026
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.add_group
def add_group(self, groupname, statements): """ Adds a group @type groupname: bytes @type statements: str """ msg = OmapiMessage.open(b"group") msg.message.append(("create", struct.pack("!I", 1))) msg.obj.append(("name", groupname)) msg.obj.append(("statements", statements)) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add group failed")
python
def add_group(self, groupname, statements): msg = OmapiMessage.open(b"group") msg.message.append(("create", struct.pack("!I", 1))) msg.obj.append(("name", groupname)) msg.obj.append(("statements", statements)) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add group failed")
[ "def", "add_group", "(", "self", ",", "groupname", ",", "statements", ")", ":", "msg", "=", "OmapiMessage", ".", "open", "(", "b\"group\"", ")", "msg", ".", "message", ".", "append", "(", "(", "\"create\"", ",", "struct", ".", "pack", "(", "\"!I\"", ",...
Adds a group @type groupname: bytes @type statements: str
[ "Adds", "a", "group" ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1354-L1366
15,027
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.add_host_with_group
def add_host_with_group(self, ip, mac, groupname): """ Adds a host with given ip and mac in a group named groupname @type ip: str @type mac: str @type groupname: str """ msg = OmapiMessage.open(b"host") msg.message.append(("create", struct.pack("!I", 1))) msg.message.append(("exclusive", struct.pack("!I", 1))) msg.obj.append(("hardware-address", pack_mac(mac))) msg.obj.append(("hardware-type", struct.pack("!I", 1))) msg.obj.append(("ip-address", pack_ip(ip))) msg.obj.append(("group", groupname)) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
python
def add_host_with_group(self, ip, mac, groupname): msg = OmapiMessage.open(b"host") msg.message.append(("create", struct.pack("!I", 1))) msg.message.append(("exclusive", struct.pack("!I", 1))) msg.obj.append(("hardware-address", pack_mac(mac))) msg.obj.append(("hardware-type", struct.pack("!I", 1))) msg.obj.append(("ip-address", pack_ip(ip))) msg.obj.append(("group", groupname)) response = self.query_server(msg) if response.opcode != OMAPI_OP_UPDATE: raise OmapiError("add failed")
[ "def", "add_host_with_group", "(", "self", ",", "ip", ",", "mac", ",", "groupname", ")", ":", "msg", "=", "OmapiMessage", ".", "open", "(", "b\"host\"", ")", "msg", ".", "message", ".", "append", "(", "(", "\"create\"", ",", "struct", ".", "pack", "(",...
Adds a host with given ip and mac in a group named groupname @type ip: str @type mac: str @type groupname: str
[ "Adds", "a", "host", "with", "given", "ip", "and", "mac", "in", "a", "group", "named", "groupname" ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1368-L1384
15,028
CygnusNetworks/pypureomapi
pypureomapi.py
Omapi.change_group
def change_group(self, name, group): """Change the group of a host given the name of the host. @type name: str @type group: str """ m1 = OmapiMessage.open(b"host") m1.update_object(dict(name=name)) r1 = self.query_server(m1) if r1.opcode != OMAPI_OP_UPDATE: raise OmapiError("opening host %s failed" % name) m2 = OmapiMessage.update(r1.handle) m2.update_object(dict(group=group)) r2 = self.query_server(m2) if r2.opcode != OMAPI_OP_UPDATE: raise OmapiError("changing group of host %s to %s failed" % (name, group))
python
def change_group(self, name, group): m1 = OmapiMessage.open(b"host") m1.update_object(dict(name=name)) r1 = self.query_server(m1) if r1.opcode != OMAPI_OP_UPDATE: raise OmapiError("opening host %s failed" % name) m2 = OmapiMessage.update(r1.handle) m2.update_object(dict(group=group)) r2 = self.query_server(m2) if r2.opcode != OMAPI_OP_UPDATE: raise OmapiError("changing group of host %s to %s failed" % (name, group))
[ "def", "change_group", "(", "self", ",", "name", ",", "group", ")", ":", "m1", "=", "OmapiMessage", ".", "open", "(", "b\"host\"", ")", "m1", ".", "update_object", "(", "dict", "(", "name", "=", "name", ")", ")", "r1", "=", "self", ".", "query_server...
Change the group of a host given the name of the host. @type name: str @type group: str
[ "Change", "the", "group", "of", "a", "host", "given", "the", "name", "of", "the", "host", "." ]
ff4459678ec023fd56e64ce518a86860efec26bf
https://github.com/CygnusNetworks/pypureomapi/blob/ff4459678ec023fd56e64ce518a86860efec26bf/pypureomapi.py#L1386-L1400
15,029
sbg/sevenbridges-python
sevenbridges/meta/resource.py
Resource._query
def _query(cls, **kwargs): """ Generic query implementation that is used by the resources. """ from sevenbridges.models.link import Link from sevenbridges.meta.collection import Collection api = kwargs.pop('api', cls._API) url = kwargs.pop('url') extra = {'resource': cls.__name__, 'query': kwargs} logger.info('Querying {} resource'.format(cls), extra=extra) response = api.get(url=url, params=kwargs) data = response.json() total = response.headers['x-total-matching-query'] items = [cls(api=api, **item) for item in data['items']] links = [Link(**link) for link in data['links']] href = data['href'] return Collection( resource=cls, href=href, total=total, items=items, links=links, api=api )
python
def _query(cls, **kwargs): from sevenbridges.models.link import Link from sevenbridges.meta.collection import Collection api = kwargs.pop('api', cls._API) url = kwargs.pop('url') extra = {'resource': cls.__name__, 'query': kwargs} logger.info('Querying {} resource'.format(cls), extra=extra) response = api.get(url=url, params=kwargs) data = response.json() total = response.headers['x-total-matching-query'] items = [cls(api=api, **item) for item in data['items']] links = [Link(**link) for link in data['links']] href = data['href'] return Collection( resource=cls, href=href, total=total, items=items, links=links, api=api )
[ "def", "_query", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "from", "sevenbridges", ".", "models", ".", "link", "import", "Link", "from", "sevenbridges", ".", "meta", ".", "collection", "import", "Collection", "api", "=", "kwargs", ".", "pop", "(", ...
Generic query implementation that is used by the resources.
[ "Generic", "query", "implementation", "that", "is", "used", "by", "the", "resources", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/meta/resource.py#L118-L140
15,030
sbg/sevenbridges-python
sevenbridges/meta/resource.py
Resource.delete
def delete(self): """ Deletes the resource on the server. """ if 'delete' in self._URL: extra = {'resource': self.__class__.__name__, 'query': { 'id': self.id}} logger.info("Deleting {} resource.".format(self), extra=extra) self._api.delete(url=self._URL['delete'].format(id=self.id)) else: raise SbgError('Resource can not be deleted!')
python
def delete(self): if 'delete' in self._URL: extra = {'resource': self.__class__.__name__, 'query': { 'id': self.id}} logger.info("Deleting {} resource.".format(self), extra=extra) self._api.delete(url=self._URL['delete'].format(id=self.id)) else: raise SbgError('Resource can not be deleted!')
[ "def", "delete", "(", "self", ")", ":", "if", "'delete'", "in", "self", ".", "_URL", ":", "extra", "=", "{", "'resource'", ":", "self", ".", "__class__", ".", "__name__", ",", "'query'", ":", "{", "'id'", ":", "self", ".", "id", "}", "}", "logger",...
Deletes the resource on the server.
[ "Deletes", "the", "resource", "on", "the", "server", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/meta/resource.py#L160-L170
15,031
sbg/sevenbridges-python
sevenbridges/meta/resource.py
Resource.reload
def reload(self): """ Refreshes the resource with the data from the server. """ try: if hasattr(self, 'href'): data = self._api.get(self.href, append_base=False).json() resource = self.__class__(api=self._api, **data) elif hasattr(self, 'id') and hasattr(self, '_URL') and \ 'get' in self._URL: data = self._api.get( self._URL['get'].format(id=self.id)).json() resource = self.__class__(api=self._api, **data) else: raise SbgError('Resource can not be refreshed!') query = {'id': self.id} if hasattr(self, 'id') else {} extra = {'resource': self.__class__.__name__, 'query': query} logger.info('Reloading {} resource.'.format(self), extra=extra) except Exception: raise SbgError('Resource can not be refreshed!') self._data = resource._data self._dirty = resource._dirty self._old = copy.deepcopy(self._data.data) return self
python
def reload(self): try: if hasattr(self, 'href'): data = self._api.get(self.href, append_base=False).json() resource = self.__class__(api=self._api, **data) elif hasattr(self, 'id') and hasattr(self, '_URL') and \ 'get' in self._URL: data = self._api.get( self._URL['get'].format(id=self.id)).json() resource = self.__class__(api=self._api, **data) else: raise SbgError('Resource can not be refreshed!') query = {'id': self.id} if hasattr(self, 'id') else {} extra = {'resource': self.__class__.__name__, 'query': query} logger.info('Reloading {} resource.'.format(self), extra=extra) except Exception: raise SbgError('Resource can not be refreshed!') self._data = resource._data self._dirty = resource._dirty self._old = copy.deepcopy(self._data.data) return self
[ "def", "reload", "(", "self", ")", ":", "try", ":", "if", "hasattr", "(", "self", ",", "'href'", ")", ":", "data", "=", "self", ".", "_api", ".", "get", "(", "self", ".", "href", ",", "append_base", "=", "False", ")", ".", "json", "(", ")", "re...
Refreshes the resource with the data from the server.
[ "Refreshes", "the", "resource", "with", "the", "data", "from", "the", "server", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/meta/resource.py#L172-L198
15,032
indico/indico-plugins
importer/indico_importer/converter.py
RecordConverter.convert
def convert(cls, record): """ Converts a single dictionary or list of dictionaries into converted list of dictionaries. """ if isinstance(record, list): return [cls._convert(r) for r in record] else: return [cls._convert(record)]
python
def convert(cls, record): if isinstance(record, list): return [cls._convert(r) for r in record] else: return [cls._convert(record)]
[ "def", "convert", "(", "cls", ",", "record", ")", ":", "if", "isinstance", "(", "record", ",", "list", ")", ":", "return", "[", "cls", ".", "_convert", "(", "r", ")", "for", "r", "in", "record", "]", "else", ":", "return", "[", "cls", ".", "_conv...
Converts a single dictionary or list of dictionaries into converted list of dictionaries.
[ "Converts", "a", "single", "dictionary", "or", "list", "of", "dictionaries", "into", "converted", "list", "of", "dictionaries", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/importer/indico_importer/converter.py#L55-L62
15,033
indico/indico-plugins
importer/indico_importer/converter.py
RecordConverter._convert_internal
def _convert_internal(cls, record): """ Converts a single dictionary into converted dictionary or list of dictionaries into converted list of dictionaries. Used while passing dictionaries to another converter. """ if isinstance(record, list): return [cls._convert(r) for r in record] else: return cls._convert(record)
python
def _convert_internal(cls, record): if isinstance(record, list): return [cls._convert(r) for r in record] else: return cls._convert(record)
[ "def", "_convert_internal", "(", "cls", ",", "record", ")", ":", "if", "isinstance", "(", "record", ",", "list", ")", ":", "return", "[", "cls", ".", "_convert", "(", "r", ")", "for", "r", "in", "record", "]", "else", ":", "return", "cls", ".", "_c...
Converts a single dictionary into converted dictionary or list of dictionaries into converted list of dictionaries. Used while passing dictionaries to another converter.
[ "Converts", "a", "single", "dictionary", "into", "converted", "dictionary", "or", "list", "of", "dictionaries", "into", "converted", "list", "of", "dictionaries", ".", "Used", "while", "passing", "dictionaries", "to", "another", "converter", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/importer/indico_importer/converter.py#L65-L73
15,034
indico/indico-plugins
importer/indico_importer/converter.py
RecordConverter._convert
def _convert(cls, record): """ Core method of the converter. Converts a single dictionary into another dictionary. """ if not record: return {} converted_dict = {} for field in cls.conversion: key = field[0] if len(field) >= 2 and field[1]: converted_key = field[1] else: converted_key = key if len(field) >= 3 and field[2]: conversion_method = field[2] else: conversion_method = cls.default_conversion_method if len(field) >= 4: converter = field[3] else: converter = None try: value = conversion_method(record[key]) except KeyError: continue if converter: value = converter._convert_internal(value) if converted_key is APPEND: if isinstance(value, list): for v in value: converted_dict.update(v) else: converted_dict.update(value) else: converted_dict[converted_key] = value return converted_dict
python
def _convert(cls, record): if not record: return {} converted_dict = {} for field in cls.conversion: key = field[0] if len(field) >= 2 and field[1]: converted_key = field[1] else: converted_key = key if len(field) >= 3 and field[2]: conversion_method = field[2] else: conversion_method = cls.default_conversion_method if len(field) >= 4: converter = field[3] else: converter = None try: value = conversion_method(record[key]) except KeyError: continue if converter: value = converter._convert_internal(value) if converted_key is APPEND: if isinstance(value, list): for v in value: converted_dict.update(v) else: converted_dict.update(value) else: converted_dict[converted_key] = value return converted_dict
[ "def", "_convert", "(", "cls", ",", "record", ")", ":", "if", "not", "record", ":", "return", "{", "}", "converted_dict", "=", "{", "}", "for", "field", "in", "cls", ".", "conversion", ":", "key", "=", "field", "[", "0", "]", "if", "len", "(", "f...
Core method of the converter. Converts a single dictionary into another dictionary.
[ "Core", "method", "of", "the", "converter", ".", "Converts", "a", "single", "dictionary", "into", "another", "dictionary", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/importer/indico_importer/converter.py#L76-L112
15,035
indico/indico-plugins
chat/indico_chat/xmpp.py
create_room
def create_room(room): """Creates a MUC room on the XMPP server.""" if room.custom_server: return def _create_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.joinMUC(room.jid, xmpp.requested_jid.user) muc.configureRoom(room.jid, _set_form_values(xmpp, room)) current_plugin.logger.info('Creating room %s', room.jid) _execute_xmpp(_create_room)
python
def create_room(room): if room.custom_server: return def _create_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.joinMUC(room.jid, xmpp.requested_jid.user) muc.configureRoom(room.jid, _set_form_values(xmpp, room)) current_plugin.logger.info('Creating room %s', room.jid) _execute_xmpp(_create_room)
[ "def", "create_room", "(", "room", ")", ":", "if", "room", ".", "custom_server", ":", "return", "def", "_create_room", "(", "xmpp", ")", ":", "muc", "=", "xmpp", ".", "plugin", "[", "'xep_0045'", "]", "muc", ".", "joinMUC", "(", "room", ".", "jid", "...
Creates a MUC room on the XMPP server.
[ "Creates", "a", "MUC", "room", "on", "the", "XMPP", "server", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L44-L56
15,036
indico/indico-plugins
chat/indico_chat/xmpp.py
update_room
def update_room(room): """Updates a MUC room on the XMPP server.""" if room.custom_server: return def _update_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.joinMUC(room.jid, xmpp.requested_jid.user) muc.configureRoom(room.jid, _set_form_values(xmpp, room, muc.getRoomConfig(room.jid))) current_plugin.logger.info('Updating room %s', room.jid) _execute_xmpp(_update_room)
python
def update_room(room): if room.custom_server: return def _update_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.joinMUC(room.jid, xmpp.requested_jid.user) muc.configureRoom(room.jid, _set_form_values(xmpp, room, muc.getRoomConfig(room.jid))) current_plugin.logger.info('Updating room %s', room.jid) _execute_xmpp(_update_room)
[ "def", "update_room", "(", "room", ")", ":", "if", "room", ".", "custom_server", ":", "return", "def", "_update_room", "(", "xmpp", ")", ":", "muc", "=", "xmpp", ".", "plugin", "[", "'xep_0045'", "]", "muc", ".", "joinMUC", "(", "room", ".", "jid", "...
Updates a MUC room on the XMPP server.
[ "Updates", "a", "MUC", "room", "on", "the", "XMPP", "server", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L59-L71
15,037
indico/indico-plugins
chat/indico_chat/xmpp.py
delete_room
def delete_room(room, reason=''): """Deletes a MUC room from the XMPP server.""" if room.custom_server: return def _delete_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.destroy(room.jid, reason=reason) current_plugin.logger.info('Deleting room %s', room.jid) _execute_xmpp(_delete_room) delete_logs(room)
python
def delete_room(room, reason=''): if room.custom_server: return def _delete_room(xmpp): muc = xmpp.plugin['xep_0045'] muc.destroy(room.jid, reason=reason) current_plugin.logger.info('Deleting room %s', room.jid) _execute_xmpp(_delete_room) delete_logs(room)
[ "def", "delete_room", "(", "room", ",", "reason", "=", "''", ")", ":", "if", "room", ".", "custom_server", ":", "return", "def", "_delete_room", "(", "xmpp", ")", ":", "muc", "=", "xmpp", ".", "plugin", "[", "'xep_0045'", "]", "muc", ".", "destroy", ...
Deletes a MUC room from the XMPP server.
[ "Deletes", "a", "MUC", "room", "from", "the", "XMPP", "server", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L74-L86
15,038
indico/indico-plugins
chat/indico_chat/xmpp.py
get_room_config
def get_room_config(jid): """Retrieves basic data of a MUC room from the XMPP server. :return: dict containing name, description and password of the room """ mapping = { 'name': 'muc#roomconfig_roomname', 'description': 'muc#roomconfig_roomdesc', 'password': 'muc#roomconfig_roomsecret' } def _get_room_config(xmpp): muc = xmpp.plugin['xep_0045'] try: form = muc.getRoomConfig(jid) except ValueError: # probably the room doesn't exist return None fields = form.values['fields'] return {key: fields[muc_key].values['value'] for key, muc_key in mapping.iteritems()} return _execute_xmpp(_get_room_config)
python
def get_room_config(jid): mapping = { 'name': 'muc#roomconfig_roomname', 'description': 'muc#roomconfig_roomdesc', 'password': 'muc#roomconfig_roomsecret' } def _get_room_config(xmpp): muc = xmpp.plugin['xep_0045'] try: form = muc.getRoomConfig(jid) except ValueError: # probably the room doesn't exist return None fields = form.values['fields'] return {key: fields[muc_key].values['value'] for key, muc_key in mapping.iteritems()} return _execute_xmpp(_get_room_config)
[ "def", "get_room_config", "(", "jid", ")", ":", "mapping", "=", "{", "'name'", ":", "'muc#roomconfig_roomname'", ",", "'description'", ":", "'muc#roomconfig_roomdesc'", ",", "'password'", ":", "'muc#roomconfig_roomsecret'", "}", "def", "_get_room_config", "(", "xmpp",...
Retrieves basic data of a MUC room from the XMPP server. :return: dict containing name, description and password of the room
[ "Retrieves", "basic", "data", "of", "a", "MUC", "room", "from", "the", "XMPP", "server", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L89-L110
15,039
indico/indico-plugins
chat/indico_chat/xmpp.py
room_exists
def room_exists(jid): """Checks if a MUC room exists on the server.""" def _room_exists(xmpp): disco = xmpp.plugin['xep_0030'] try: disco.get_info(jid) except IqError as e: if e.condition == 'item-not-found': return False raise else: return True return _execute_xmpp(_room_exists)
python
def room_exists(jid): def _room_exists(xmpp): disco = xmpp.plugin['xep_0030'] try: disco.get_info(jid) except IqError as e: if e.condition == 'item-not-found': return False raise else: return True return _execute_xmpp(_room_exists)
[ "def", "room_exists", "(", "jid", ")", ":", "def", "_room_exists", "(", "xmpp", ")", ":", "disco", "=", "xmpp", ".", "plugin", "[", "'xep_0030'", "]", "try", ":", "disco", ".", "get_info", "(", "jid", ")", "except", "IqError", "as", "e", ":", "if", ...
Checks if a MUC room exists on the server.
[ "Checks", "if", "a", "MUC", "room", "exists", "on", "the", "server", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L113-L127
15,040
indico/indico-plugins
chat/indico_chat/xmpp.py
sanitize_jid
def sanitize_jid(s): """Generates a valid JID node identifier from a string""" jid = unicode_to_ascii(s).lower() jid = WHITESPACE.sub('-', jid) jid = INVALID_JID_CHARS.sub('', jid) return jid.strip()[:256]
python
def sanitize_jid(s): jid = unicode_to_ascii(s).lower() jid = WHITESPACE.sub('-', jid) jid = INVALID_JID_CHARS.sub('', jid) return jid.strip()[:256]
[ "def", "sanitize_jid", "(", "s", ")", ":", "jid", "=", "unicode_to_ascii", "(", "s", ")", ".", "lower", "(", ")", "jid", "=", "WHITESPACE", ".", "sub", "(", "'-'", ",", "jid", ")", "jid", "=", "INVALID_JID_CHARS", ".", "sub", "(", "''", ",", "jid",...
Generates a valid JID node identifier from a string
[ "Generates", "a", "valid", "JID", "node", "identifier", "from", "a", "string" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L130-L135
15,041
indico/indico-plugins
chat/indico_chat/xmpp.py
generate_jid
def generate_jid(name, append_date=None): """Generates a v alid JID based on the room name. :param append_date: appends the given date to the JID """ if not append_date: return sanitize_jid(name) return '{}-{}'.format(sanitize_jid(name), append_date.strftime('%Y-%m-%d'))
python
def generate_jid(name, append_date=None): if not append_date: return sanitize_jid(name) return '{}-{}'.format(sanitize_jid(name), append_date.strftime('%Y-%m-%d'))
[ "def", "generate_jid", "(", "name", ",", "append_date", "=", "None", ")", ":", "if", "not", "append_date", ":", "return", "sanitize_jid", "(", "name", ")", "return", "'{}-{}'", ".", "format", "(", "sanitize_jid", "(", "name", ")", ",", "append_date", ".", ...
Generates a v alid JID based on the room name. :param append_date: appends the given date to the JID
[ "Generates", "a", "v", "alid", "JID", "based", "on", "the", "room", "name", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L138-L145
15,042
indico/indico-plugins
chat/indico_chat/xmpp.py
_execute_xmpp
def _execute_xmpp(connected_callback): """Connects to the XMPP server and executes custom code :param connected_callback: function to execute after connecting :return: return value of the callback """ from indico_chat.plugin import ChatPlugin check_config() jid = ChatPlugin.settings.get('bot_jid') password = ChatPlugin.settings.get('bot_password') if '@' not in jid: jid = '{}@{}'.format(jid, ChatPlugin.settings.get('server')) result = [None, None] # result, exception app = current_app._get_current_object() # callback runs in another thread def _session_start(event): try: with app.app_context(): result[0] = connected_callback(xmpp) except Exception as e: result[1] = e if isinstance(e, IqError): current_plugin.logger.exception('XMPP callback failed: %s', e.condition) else: current_plugin.logger.exception('XMPP callback failed') finally: xmpp.disconnect(wait=0) xmpp = ClientXMPP(jid, password) xmpp.register_plugin('xep_0045') xmpp.register_plugin('xep_0004') xmpp.register_plugin('xep_0030') xmpp.add_event_handler('session_start', _session_start) try: xmpp.connect() except Exception: current_plugin.logger.exception('XMPP connection failed') xmpp.disconnect() raise try: xmpp.process(threaded=False) finally: xmpp.disconnect(wait=0) if result[1] is not None: raise result[1] return result[0]
python
def _execute_xmpp(connected_callback): from indico_chat.plugin import ChatPlugin check_config() jid = ChatPlugin.settings.get('bot_jid') password = ChatPlugin.settings.get('bot_password') if '@' not in jid: jid = '{}@{}'.format(jid, ChatPlugin.settings.get('server')) result = [None, None] # result, exception app = current_app._get_current_object() # callback runs in another thread def _session_start(event): try: with app.app_context(): result[0] = connected_callback(xmpp) except Exception as e: result[1] = e if isinstance(e, IqError): current_plugin.logger.exception('XMPP callback failed: %s', e.condition) else: current_plugin.logger.exception('XMPP callback failed') finally: xmpp.disconnect(wait=0) xmpp = ClientXMPP(jid, password) xmpp.register_plugin('xep_0045') xmpp.register_plugin('xep_0004') xmpp.register_plugin('xep_0030') xmpp.add_event_handler('session_start', _session_start) try: xmpp.connect() except Exception: current_plugin.logger.exception('XMPP connection failed') xmpp.disconnect() raise try: xmpp.process(threaded=False) finally: xmpp.disconnect(wait=0) if result[1] is not None: raise result[1] return result[0]
[ "def", "_execute_xmpp", "(", "connected_callback", ")", ":", "from", "indico_chat", ".", "plugin", "import", "ChatPlugin", "check_config", "(", ")", "jid", "=", "ChatPlugin", ".", "settings", ".", "get", "(", "'bot_jid'", ")", "password", "=", "ChatPlugin", "....
Connects to the XMPP server and executes custom code :param connected_callback: function to execute after connecting :return: return value of the callback
[ "Connects", "to", "the", "XMPP", "server", "and", "executes", "custom", "code" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L176-L227
15,043
indico/indico-plugins
chat/indico_chat/xmpp.py
retrieve_logs
def retrieve_logs(room, start_date=None, end_date=None): """Retrieves chat logs :param room: the `Chatroom` :param start_date: the earliest date to get logs for :param end_date: the latest date to get logs for :return: logs in html format """ from indico_chat.plugin import ChatPlugin base_url = ChatPlugin.settings.get('log_url') if not base_url or room.custom_server: return None params = {'cr': room.jid} if start_date: params['sdate'] = start_date.strftime('%Y-%m-%d') if end_date: params['edate'] = end_date.strftime('%Y-%m-%d') try: response = requests.get(base_url, params=params) except RequestException: current_plugin.logger.exception('Could not retrieve logs for %s', room.jid) return None if response.headers.get('content-type') == 'application/json': current_plugin.logger.warning('Could not retrieve logs for %s: %s', room.jid, response.json().get('error')) return None return response.text
python
def retrieve_logs(room, start_date=None, end_date=None): from indico_chat.plugin import ChatPlugin base_url = ChatPlugin.settings.get('log_url') if not base_url or room.custom_server: return None params = {'cr': room.jid} if start_date: params['sdate'] = start_date.strftime('%Y-%m-%d') if end_date: params['edate'] = end_date.strftime('%Y-%m-%d') try: response = requests.get(base_url, params=params) except RequestException: current_plugin.logger.exception('Could not retrieve logs for %s', room.jid) return None if response.headers.get('content-type') == 'application/json': current_plugin.logger.warning('Could not retrieve logs for %s: %s', room.jid, response.json().get('error')) return None return response.text
[ "def", "retrieve_logs", "(", "room", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "from", "indico_chat", ".", "plugin", "import", "ChatPlugin", "base_url", "=", "ChatPlugin", ".", "settings", ".", "get", "(", "'log_url'", ")", "i...
Retrieves chat logs :param room: the `Chatroom` :param start_date: the earliest date to get logs for :param end_date: the latest date to get logs for :return: logs in html format
[ "Retrieves", "chat", "logs" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L230-L258
15,044
indico/indico-plugins
chat/indico_chat/xmpp.py
delete_logs
def delete_logs(room): """Deletes chat logs""" from indico_chat.plugin import ChatPlugin base_url = ChatPlugin.settings.get('log_url') if not base_url or room.custom_server: return try: response = requests.get(posixpath.join(base_url, 'delete'), params={'cr': room.jid}).json() except (RequestException, ValueError): current_plugin.logger.exception('Could not delete logs for %s', room.jid) return if not response.get('success'): current_plugin.logger.warning('Could not delete logs for %s: %s', room.jid, response.get('error'))
python
def delete_logs(room): from indico_chat.plugin import ChatPlugin base_url = ChatPlugin.settings.get('log_url') if not base_url or room.custom_server: return try: response = requests.get(posixpath.join(base_url, 'delete'), params={'cr': room.jid}).json() except (RequestException, ValueError): current_plugin.logger.exception('Could not delete logs for %s', room.jid) return if not response.get('success'): current_plugin.logger.warning('Could not delete logs for %s: %s', room.jid, response.get('error'))
[ "def", "delete_logs", "(", "room", ")", ":", "from", "indico_chat", ".", "plugin", "import", "ChatPlugin", "base_url", "=", "ChatPlugin", ".", "settings", ".", "get", "(", "'log_url'", ")", "if", "not", "base_url", "or", "room", ".", "custom_server", ":", ...
Deletes chat logs
[ "Deletes", "chat", "logs" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/xmpp.py#L261-L275
15,045
sbg/sevenbridges-python
sevenbridges/models/project.py
Project.create_task
def create_task(self, name, app, revision=None, batch_input=None, batch_by=None, inputs=None, description=None, run=False, disable_batch=False, interruptible=True, execution_settings=None): """ Creates a task for this project. :param name: Task name. :param app: CWL app identifier. :param revision: CWL app revision. :param batch_input: Batch input. :param batch_by: Batch criteria. :param inputs: Input map. :param description: Task description. :param run: True if you want to run a task upon creation. :param disable_batch: True if you want to disable batching. :param interruptible: True if you want to use interruptible instances. :param execution_settings: Execution settings for the task. :return: Task object. """ return self._api.tasks.create( name=name, project=self, app=app, revision=revision, batch_input=batch_input, batch_by=batch_by, inputs=inputs, description=description, run=run, disable_batch=disable_batch, interruptible=interruptible, execution_settings=execution_settings )
python
def create_task(self, name, app, revision=None, batch_input=None, batch_by=None, inputs=None, description=None, run=False, disable_batch=False, interruptible=True, execution_settings=None): return self._api.tasks.create( name=name, project=self, app=app, revision=revision, batch_input=batch_input, batch_by=batch_by, inputs=inputs, description=description, run=run, disable_batch=disable_batch, interruptible=interruptible, execution_settings=execution_settings )
[ "def", "create_task", "(", "self", ",", "name", ",", "app", ",", "revision", "=", "None", ",", "batch_input", "=", "None", ",", "batch_by", "=", "None", ",", "inputs", "=", "None", ",", "description", "=", "None", ",", "run", "=", "False", ",", "disa...
Creates a task for this project. :param name: Task name. :param app: CWL app identifier. :param revision: CWL app revision. :param batch_input: Batch input. :param batch_by: Batch criteria. :param inputs: Input map. :param description: Task description. :param run: True if you want to run a task upon creation. :param disable_batch: True if you want to disable batching. :param interruptible: True if you want to use interruptible instances. :param execution_settings: Execution settings for the task. :return: Task object.
[ "Creates", "a", "task", "for", "this", "project", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/project.py#L377-L402
15,046
indico/indico-plugins
payment_paypal/indico_payment_paypal/util.py
validate_business
def validate_business(form, field): """Valiates a PayPal business string. It can either be an email address or a paypal business account ID. """ if not is_valid_mail(field.data, multi=False) and not re.match(r'^[a-zA-Z0-9]{13}$', field.data): raise ValidationError(_('Invalid email address / paypal ID'))
python
def validate_business(form, field): if not is_valid_mail(field.data, multi=False) and not re.match(r'^[a-zA-Z0-9]{13}$', field.data): raise ValidationError(_('Invalid email address / paypal ID'))
[ "def", "validate_business", "(", "form", ",", "field", ")", ":", "if", "not", "is_valid_mail", "(", "field", ".", "data", ",", "multi", "=", "False", ")", "and", "not", "re", ".", "match", "(", "r'^[a-zA-Z0-9]{13}$'", ",", "field", ".", "data", ")", ":...
Valiates a PayPal business string. It can either be an email address or a paypal business account ID.
[ "Valiates", "a", "PayPal", "business", "string", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/payment_paypal/indico_payment_paypal/util.py#L28-L34
15,047
sbg/sevenbridges-python
sevenbridges/transfer/download.py
DPartedFile.submit
def submit(self): """ Partitions the file into chunks and submits them into group of 4 for download on the api download pool. """ futures = [] while self.submitted < 4 and not self.done(): part = self.parts.pop(0) futures.append( self.pool.submit( _download_part, self.file_path, self.session, self.url, self.retry, self.timeout, *part) ) self.submitted += 1 self.total_submitted += 1 return futures
python
def submit(self): futures = [] while self.submitted < 4 and not self.done(): part = self.parts.pop(0) futures.append( self.pool.submit( _download_part, self.file_path, self.session, self.url, self.retry, self.timeout, *part) ) self.submitted += 1 self.total_submitted += 1 return futures
[ "def", "submit", "(", "self", ")", ":", "futures", "=", "[", "]", "while", "self", ".", "submitted", "<", "4", "and", "not", "self", ".", "done", "(", ")", ":", "part", "=", "self", ".", "parts", ".", "pop", "(", "0", ")", "futures", ".", "appe...
Partitions the file into chunks and submits them into group of 4 for download on the api download pool.
[ "Partitions", "the", "file", "into", "chunks", "and", "submits", "them", "into", "group", "of", "4", "for", "download", "on", "the", "api", "download", "pool", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/transfer/download.py#L112-L128
15,048
sbg/sevenbridges-python
sevenbridges/transfer/download.py
DPartedFile.get_parts
def get_parts(self): """ Partitions the file and saves the part information in memory. """ parts = [] start_b = 0 end_byte = start_b + PartSize.DOWNLOAD_MINIMUM_PART_SIZE - 1 for i in range(self.total): parts.append([start_b, end_byte]) start_b = end_byte + 1 end_byte = start_b + PartSize.DOWNLOAD_MINIMUM_PART_SIZE - 1 return parts
python
def get_parts(self): parts = [] start_b = 0 end_byte = start_b + PartSize.DOWNLOAD_MINIMUM_PART_SIZE - 1 for i in range(self.total): parts.append([start_b, end_byte]) start_b = end_byte + 1 end_byte = start_b + PartSize.DOWNLOAD_MINIMUM_PART_SIZE - 1 return parts
[ "def", "get_parts", "(", "self", ")", ":", "parts", "=", "[", "]", "start_b", "=", "0", "end_byte", "=", "start_b", "+", "PartSize", ".", "DOWNLOAD_MINIMUM_PART_SIZE", "-", "1", "for", "i", "in", "range", "(", "self", ".", "total", ")", ":", "parts", ...
Partitions the file and saves the part information in memory.
[ "Partitions", "the", "file", "and", "saves", "the", "part", "information", "in", "memory", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/transfer/download.py#L142-L153
15,049
indico/indico-plugins
livesync/indico_livesync/base.py
LiveSyncBackendBase.run
def run(self): """Runs the livesync export""" if self.uploader is None: # pragma: no cover raise NotImplementedError records = self.fetch_records() uploader = self.uploader(self) LiveSyncPlugin.logger.info('Uploading %d records', len(records)) uploader.run(records) self.update_last_run()
python
def run(self): if self.uploader is None: # pragma: no cover raise NotImplementedError records = self.fetch_records() uploader = self.uploader(self) LiveSyncPlugin.logger.info('Uploading %d records', len(records)) uploader.run(records) self.update_last_run()
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "uploader", "is", "None", ":", "# pragma: no cover", "raise", "NotImplementedError", "records", "=", "self", ".", "fetch_records", "(", ")", "uploader", "=", "self", ".", "uploader", "(", "self", ")",...
Runs the livesync export
[ "Runs", "the", "livesync", "export" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/livesync/indico_livesync/base.py#L91-L100
15,050
indico/indico-plugins
livesync/indico_livesync/base.py
LiveSyncBackendBase.run_initial_export
def run_initial_export(self, events): """Runs the initial export. This process is expected to take a very long time. :param events: iterable of all events in this indico instance """ if self.uploader is None: # pragma: no cover raise NotImplementedError uploader = self.uploader(self) uploader.run_initial(events)
python
def run_initial_export(self, events): if self.uploader is None: # pragma: no cover raise NotImplementedError uploader = self.uploader(self) uploader.run_initial(events)
[ "def", "run_initial_export", "(", "self", ",", "events", ")", ":", "if", "self", ".", "uploader", "is", "None", ":", "# pragma: no cover", "raise", "NotImplementedError", "uploader", "=", "self", ".", "uploader", "(", "self", ")", "uploader", ".", "run_initial...
Runs the initial export. This process is expected to take a very long time. :param events: iterable of all events in this indico instance
[ "Runs", "the", "initial", "export", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/livesync/indico_livesync/base.py#L102-L113
15,051
indico/indico-plugins
chat/indico_chat/util.py
check_config
def check_config(quiet=False): """Checks if all required config options are set :param quiet: if True, return the result as a bool, otherwise raise `IndicoError` if any setting is missing """ from indico_chat.plugin import ChatPlugin settings = ChatPlugin.settings.get_all() missing = not all(settings[x] for x in ('server', 'muc_server', 'bot_jid', 'bot_password')) if missing and not quiet: raise IndicoError(_('Chat plugin is not configured properly')) return not missing
python
def check_config(quiet=False): from indico_chat.plugin import ChatPlugin settings = ChatPlugin.settings.get_all() missing = not all(settings[x] for x in ('server', 'muc_server', 'bot_jid', 'bot_password')) if missing and not quiet: raise IndicoError(_('Chat plugin is not configured properly')) return not missing
[ "def", "check_config", "(", "quiet", "=", "False", ")", ":", "from", "indico_chat", ".", "plugin", "import", "ChatPlugin", "settings", "=", "ChatPlugin", ".", "settings", ".", "get_all", "(", ")", "missing", "=", "not", "all", "(", "settings", "[", "x", ...
Checks if all required config options are set :param quiet: if True, return the result as a bool, otherwise raise `IndicoError` if any setting is missing
[ "Checks", "if", "all", "required", "config", "options", "are", "set" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/util.py#L24-L35
15,052
indico/indico-plugins
chat/indico_chat/util.py
is_chat_admin
def is_chat_admin(user): """Checks if a user is a chat admin""" from indico_chat.plugin import ChatPlugin return ChatPlugin.settings.acls.contains_user('admins', user)
python
def is_chat_admin(user): from indico_chat.plugin import ChatPlugin return ChatPlugin.settings.acls.contains_user('admins', user)
[ "def", "is_chat_admin", "(", "user", ")", ":", "from", "indico_chat", ".", "plugin", "import", "ChatPlugin", "return", "ChatPlugin", ".", "settings", ".", "acls", ".", "contains_user", "(", "'admins'", ",", "user", ")" ]
Checks if a user is a chat admin
[ "Checks", "if", "a", "user", "is", "a", "chat", "admin" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/chat/indico_chat/util.py#L38-L41
15,053
sbg/sevenbridges-python
sevenbridges/decorators.py
inplace_reload
def inplace_reload(method): """ Executes the wrapped function and reloads the object with data returned from the server. """ # noinspection PyProtectedMember def wrapped(obj, *args, **kwargs): in_place = True if kwargs.get('inplace') in (True, None) else False api_object = method(obj, *args, **kwargs) if in_place and api_object: obj._data = api_object._data obj._dirty = api_object._dirty obj._data.fetched = False return obj elif api_object: return api_object else: return obj return wrapped
python
def inplace_reload(method): # noinspection PyProtectedMember def wrapped(obj, *args, **kwargs): in_place = True if kwargs.get('inplace') in (True, None) else False api_object = method(obj, *args, **kwargs) if in_place and api_object: obj._data = api_object._data obj._dirty = api_object._dirty obj._data.fetched = False return obj elif api_object: return api_object else: return obj return wrapped
[ "def", "inplace_reload", "(", "method", ")", ":", "# noinspection PyProtectedMember", "def", "wrapped", "(", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "in_place", "=", "True", "if", "kwargs", ".", "get", "(", "'inplace'", ")", "in", "("...
Executes the wrapped function and reloads the object with data returned from the server.
[ "Executes", "the", "wrapped", "function", "and", "reloads", "the", "object", "with", "data", "returned", "from", "the", "server", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/decorators.py#L24-L44
15,054
sbg/sevenbridges-python
sevenbridges/decorators.py
retry_on_excs
def retry_on_excs(excs, retry_count=3, delay=5): """Retry decorator used to retry callables on for specific exceptions. :param excs: Exceptions tuple. :param retry_count: Retry count. :param delay: Delay in seconds between retries. :return: Wrapped function object. """ def wrapper(f): @functools.wraps(f) def deco(*args, **kwargs): for i in range(0, retry_count): try: return f(*args, **kwargs) except excs: if logger: logger.warning( 'HTTPError caught.Retrying ...'.format(f.__name__), exc_info=True ) time.sleep(delay) else: logger.error( '{} failed after {} retries'.format( f.__name__, retry_count) ) return f(*args, **kwargs) return deco return wrapper
python
def retry_on_excs(excs, retry_count=3, delay=5): def wrapper(f): @functools.wraps(f) def deco(*args, **kwargs): for i in range(0, retry_count): try: return f(*args, **kwargs) except excs: if logger: logger.warning( 'HTTPError caught.Retrying ...'.format(f.__name__), exc_info=True ) time.sleep(delay) else: logger.error( '{} failed after {} retries'.format( f.__name__, retry_count) ) return f(*args, **kwargs) return deco return wrapper
[ "def", "retry_on_excs", "(", "excs", ",", "retry_count", "=", "3", ",", "delay", "=", "5", ")", ":", "def", "wrapper", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "deco", "(", "*", "args", ",", "*", "*", "kwargs", ...
Retry decorator used to retry callables on for specific exceptions. :param excs: Exceptions tuple. :param retry_count: Retry count. :param delay: Delay in seconds between retries. :return: Wrapped function object.
[ "Retry", "decorator", "used", "to", "retry", "callables", "on", "for", "specific", "exceptions", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/decorators.py#L47-L78
15,055
sbg/sevenbridges-python
sevenbridges/decorators.py
retry
def retry(retry_count): """ Retry decorator used during file upload and download. """ def func(f): @functools.wraps(f) def wrapper(*args, **kwargs): for backoff in range(retry_count): try: return f(*args, **kwargs) except Exception: time.sleep(2 ** backoff) else: raise SbgError('{}: failed to complete: {}'.format( threading.current_thread().getName(), f.__name__) ) return wrapper return func
python
def retry(retry_count): def func(f): @functools.wraps(f) def wrapper(*args, **kwargs): for backoff in range(retry_count): try: return f(*args, **kwargs) except Exception: time.sleep(2 ** backoff) else: raise SbgError('{}: failed to complete: {}'.format( threading.current_thread().getName(), f.__name__) ) return wrapper return func
[ "def", "retry", "(", "retry_count", ")", ":", "def", "func", "(", "f", ")", ":", "@", "functools", ".", "wraps", "(", "f", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "backoff", "in", "range", "(", "retry_co...
Retry decorator used during file upload and download.
[ "Retry", "decorator", "used", "during", "file", "upload", "and", "download", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/decorators.py#L81-L101
15,056
sbg/sevenbridges-python
sevenbridges/decorators.py
check_for_error
def check_for_error(func): """ Executes the wrapped function and inspects the response object for specific errors. """ @functools.wraps(func) def wrapper(*args, **kwargs): try: response = func(*args, **kwargs) status_code = response.status_code if status_code in range(200, 204): return response if status_code == 204: return data = response.json() e = { 400: BadRequest, 401: Unauthorized, 403: Forbidden, 404: NotFound, 405: MethodNotAllowed, 408: RequestTimeout, 409: Conflict, 429: TooManyRequests, 500: ServerError, 503: ServiceUnavailable, }.get(status_code, SbgError)() if 'message' in data: e.message = data['message'] if 'code' in data: e.code = data['code'] if 'status' in data: e.status = data['status'] if 'more_info' in data: e.more_info = data['more_info'] raise e except requests.RequestException as e: raise SbgError(message=six.text_type(e)) except JSONDecodeError: message = ( 'Service might be unavailable. Can also occur by providing ' 'too many query parameters.' ) raise_from( ServiceUnavailable(message=six.text_type(message)), None ) except ValueError as e: raise SbgError(message=six.text_type(e)) return wrapper
python
def check_for_error(func): @functools.wraps(func) def wrapper(*args, **kwargs): try: response = func(*args, **kwargs) status_code = response.status_code if status_code in range(200, 204): return response if status_code == 204: return data = response.json() e = { 400: BadRequest, 401: Unauthorized, 403: Forbidden, 404: NotFound, 405: MethodNotAllowed, 408: RequestTimeout, 409: Conflict, 429: TooManyRequests, 500: ServerError, 503: ServiceUnavailable, }.get(status_code, SbgError)() if 'message' in data: e.message = data['message'] if 'code' in data: e.code = data['code'] if 'status' in data: e.status = data['status'] if 'more_info' in data: e.more_info = data['more_info'] raise e except requests.RequestException as e: raise SbgError(message=six.text_type(e)) except JSONDecodeError: message = ( 'Service might be unavailable. Can also occur by providing ' 'too many query parameters.' ) raise_from( ServiceUnavailable(message=six.text_type(message)), None ) except ValueError as e: raise SbgError(message=six.text_type(e)) return wrapper
[ "def", "check_for_error", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "response", "=", "func", "(", "*", "args", ",", "*", "*", "kwarg...
Executes the wrapped function and inspects the response object for specific errors.
[ "Executes", "the", "wrapped", "function", "and", "inspects", "the", "response", "object", "for", "specific", "errors", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/decorators.py#L104-L154
15,057
indico/indico-plugins
piwik/indico_piwik/reports.py
ReportBase.get
def get(cls, *args, **kwargs): """Create and return a serializable Report object, retrieved from cache if possible""" from indico_piwik.plugin import PiwikPlugin if not PiwikPlugin.settings.get('cache_enabled'): return cls(*args, **kwargs).to_serializable() cache = GenericCache('Piwik.Report') key = u'{}-{}-{}'.format(cls.__name__, args, kwargs) report = cache.get(key) if not report: report = cls(*args, **kwargs) cache.set(key, report, PiwikPlugin.settings.get('cache_ttl')) return report.to_serializable()
python
def get(cls, *args, **kwargs): from indico_piwik.plugin import PiwikPlugin if not PiwikPlugin.settings.get('cache_enabled'): return cls(*args, **kwargs).to_serializable() cache = GenericCache('Piwik.Report') key = u'{}-{}-{}'.format(cls.__name__, args, kwargs) report = cache.get(key) if not report: report = cls(*args, **kwargs) cache.set(key, report, PiwikPlugin.settings.get('cache_ttl')) return report.to_serializable()
[ "def", "get", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", "indico_piwik", ".", "plugin", "import", "PiwikPlugin", "if", "not", "PiwikPlugin", ".", "settings", ".", "get", "(", "'cache_enabled'", ")", ":", "return", "cls", "...
Create and return a serializable Report object, retrieved from cache if possible
[ "Create", "and", "return", "a", "serializable", "Report", "object", "retrieved", "from", "cache", "if", "possible" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/reports.py#L59-L74
15,058
indico/indico-plugins
piwik/indico_piwik/reports.py
ReportBase._init_date_range
def _init_date_range(self, start_date=None, end_date=None): """Set date range defaults if no dates are passed""" self.end_date = end_date self.start_date = start_date if self.end_date is None: today = now_utc().date() end_date = self.event.end_dt.date() self.end_date = end_date if end_date < today else today if self.start_date is None: self.start_date = self.end_date - timedelta(days=ReportBase.default_report_interval)
python
def _init_date_range(self, start_date=None, end_date=None): self.end_date = end_date self.start_date = start_date if self.end_date is None: today = now_utc().date() end_date = self.event.end_dt.date() self.end_date = end_date if end_date < today else today if self.start_date is None: self.start_date = self.end_date - timedelta(days=ReportBase.default_report_interval)
[ "def", "_init_date_range", "(", "self", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "self", ".", "end_date", "=", "end_date", "self", ".", "start_date", "=", "start_date", "if", "self", ".", "end_date", "is", "None", ":", "tod...
Set date range defaults if no dates are passed
[ "Set", "date", "range", "defaults", "if", "no", "dates", "are", "passed" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/reports.py#L80-L89
15,059
indico/indico-plugins
piwik/indico_piwik/reports.py
ReportGeneral._build_report
def _build_report(self): """Build the report by performing queries to Piwik""" self.metrics = {} queries = {'visits': PiwikQueryReportEventMetricVisits(**self.params), 'unique_visits': PiwikQueryReportEventMetricUniqueVisits(**self.params), 'visit_duration': PiwikQueryReportEventMetricVisitDuration(**self.params), 'referrers': PiwikQueryReportEventMetricReferrers(**self.params), 'peak': PiwikQueryReportEventMetricPeakDateAndVisitors(**self.params)} for query_name, query in queries.iteritems(): self.metrics[query_name] = query.get_result() self._fetch_contribution_info()
python
def _build_report(self): self.metrics = {} queries = {'visits': PiwikQueryReportEventMetricVisits(**self.params), 'unique_visits': PiwikQueryReportEventMetricUniqueVisits(**self.params), 'visit_duration': PiwikQueryReportEventMetricVisitDuration(**self.params), 'referrers': PiwikQueryReportEventMetricReferrers(**self.params), 'peak': PiwikQueryReportEventMetricPeakDateAndVisitors(**self.params)} for query_name, query in queries.iteritems(): self.metrics[query_name] = query.get_result() self._fetch_contribution_info()
[ "def", "_build_report", "(", "self", ")", ":", "self", ".", "metrics", "=", "{", "}", "queries", "=", "{", "'visits'", ":", "PiwikQueryReportEventMetricVisits", "(", "*", "*", "self", ".", "params", ")", ",", "'unique_visits'", ":", "PiwikQueryReportEventMetri...
Build the report by performing queries to Piwik
[ "Build", "the", "report", "by", "performing", "queries", "to", "Piwik" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/reports.py#L116-L128
15,060
indico/indico-plugins
piwik/indico_piwik/reports.py
ReportGeneral._fetch_contribution_info
def _fetch_contribution_info(self): """Build the list of information entries for contributions of the event""" self.contributions = {} query = (Contribution.query .with_parent(self.event) .options(joinedload('legacy_mapping'), joinedload('timetable_entry').lazyload('*'))) for contribution in query: if not contribution.start_dt: continue cid = (contribution.legacy_mapping.legacy_contribution_id if contribution.legacy_mapping else contribution.id) key = '{}t{}'.format(contribution.event_id, cid) self.contributions[key] = u'{} ({})'.format(contribution.title, to_unicode(format_time(contribution.start_dt)))
python
def _fetch_contribution_info(self): self.contributions = {} query = (Contribution.query .with_parent(self.event) .options(joinedload('legacy_mapping'), joinedload('timetable_entry').lazyload('*'))) for contribution in query: if not contribution.start_dt: continue cid = (contribution.legacy_mapping.legacy_contribution_id if contribution.legacy_mapping else contribution.id) key = '{}t{}'.format(contribution.event_id, cid) self.contributions[key] = u'{} ({})'.format(contribution.title, to_unicode(format_time(contribution.start_dt)))
[ "def", "_fetch_contribution_info", "(", "self", ")", ":", "self", ".", "contributions", "=", "{", "}", "query", "=", "(", "Contribution", ".", "query", ".", "with_parent", "(", "self", ".", "event", ")", ".", "options", "(", "joinedload", "(", "'legacy_map...
Build the list of information entries for contributions of the event
[ "Build", "the", "list", "of", "information", "entries", "for", "contributions", "of", "the", "event" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/reports.py#L130-L144
15,061
Kane610/deconz
pydeconz/deconzdevice.py
DeconzDevice.remove_callback
def remove_callback(self, callback): """Remove callback previously registered.""" if callback in self._async_callbacks: self._async_callbacks.remove(callback)
python
def remove_callback(self, callback): if callback in self._async_callbacks: self._async_callbacks.remove(callback)
[ "def", "remove_callback", "(", "self", ",", "callback", ")", ":", "if", "callback", "in", "self", ".", "_async_callbacks", ":", "self", ".", "_async_callbacks", ".", "remove", "(", "callback", ")" ]
Remove callback previously registered.
[ "Remove", "callback", "previously", "registered", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/deconzdevice.py#L37-L40
15,062
Kane610/deconz
pydeconz/deconzdevice.py
DeconzDevice.update_attr
def update_attr(self, attr): """Update input attr in self. Return list of attributes with changed values. """ changed_attr = [] for key, value in attr.items(): if value is None: continue if getattr(self, "_{0}".format(key), None) != value: changed_attr.append(key) self.__setattr__("_{0}".format(key), value) _LOGGER.debug('%s: update %s with %s', self.name, key, value) return changed_attr
python
def update_attr(self, attr): changed_attr = [] for key, value in attr.items(): if value is None: continue if getattr(self, "_{0}".format(key), None) != value: changed_attr.append(key) self.__setattr__("_{0}".format(key), value) _LOGGER.debug('%s: update %s with %s', self.name, key, value) return changed_attr
[ "def", "update_attr", "(", "self", ",", "attr", ")", ":", "changed_attr", "=", "[", "]", "for", "key", ",", "value", "in", "attr", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "continue", "if", "getattr", "(", "self", ",", "\"_{0}...
Update input attr in self. Return list of attributes with changed values.
[ "Update", "input", "attr", "in", "self", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/deconzdevice.py#L42-L55
15,063
Kane610/deconz
pydeconz/group.py
DeconzGroup.async_set_state
async def async_set_state(self, data): """Set state of light group. { "on": true, "bri": 180, "hue": 43680, "sat": 255, "transitiontime": 10 } Also update local values of group since websockets doesn't. """ field = self.deconz_id + '/action' await self._async_set_state_callback(field, data) self.async_update({'state': data})
python
async def async_set_state(self, data): field = self.deconz_id + '/action' await self._async_set_state_callback(field, data) self.async_update({'state': data})
[ "async", "def", "async_set_state", "(", "self", ",", "data", ")", ":", "field", "=", "self", ".", "deconz_id", "+", "'/action'", "await", "self", ".", "_async_set_state_callback", "(", "field", ",", "data", ")", "self", ".", "async_update", "(", "{", "'sta...
Set state of light group. { "on": true, "bri": 180, "hue": 43680, "sat": 255, "transitiontime": 10 } Also update local values of group since websockets doesn't.
[ "Set", "state", "of", "light", "group", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/group.py#L46-L61
15,064
Kane610/deconz
pydeconz/group.py
DeconzGroup.async_add_scenes
def async_add_scenes(self, scenes, async_set_state_callback): """Add scenes belonging to group.""" self._scenes = { scene['id']: DeconzScene(self, scene, async_set_state_callback) for scene in scenes if scene['id'] not in self._scenes }
python
def async_add_scenes(self, scenes, async_set_state_callback): self._scenes = { scene['id']: DeconzScene(self, scene, async_set_state_callback) for scene in scenes if scene['id'] not in self._scenes }
[ "def", "async_add_scenes", "(", "self", ",", "scenes", ",", "async_set_state_callback", ")", ":", "self", ".", "_scenes", "=", "{", "scene", "[", "'id'", "]", ":", "DeconzScene", "(", "self", ",", "scene", ",", "async_set_state_callback", ")", "for", "scene"...
Add scenes belonging to group.
[ "Add", "scenes", "belonging", "to", "group", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/group.py#L132-L138
15,065
Kane610/deconz
pydeconz/group.py
DeconzGroup.update_color_state
def update_color_state(self, light): """Sync color state with light.""" x, y = light.xy or (None, None) self.async_update({ 'state': { 'bri': light.brightness, 'hue': light.hue, 'sat': light.sat, 'ct': light.ct, 'x': x, 'y': y, 'colormode': light.colormode, }, })
python
def update_color_state(self, light): x, y = light.xy or (None, None) self.async_update({ 'state': { 'bri': light.brightness, 'hue': light.hue, 'sat': light.sat, 'ct': light.ct, 'x': x, 'y': y, 'colormode': light.colormode, }, })
[ "def", "update_color_state", "(", "self", ",", "light", ")", ":", "x", ",", "y", "=", "light", ".", "xy", "or", "(", "None", ",", "None", ")", "self", ".", "async_update", "(", "{", "'state'", ":", "{", "'bri'", ":", "light", ".", "brightness", ","...
Sync color state with light.
[ "Sync", "color", "state", "with", "light", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/group.py#L140-L153
15,066
Kane610/deconz
pydeconz/group.py
DeconzScene.async_set_state
async def async_set_state(self, data): """Recall scene to group.""" field = self._deconz_id + '/recall' await self._async_set_state_callback(field, data)
python
async def async_set_state(self, data): field = self._deconz_id + '/recall' await self._async_set_state_callback(field, data)
[ "async", "def", "async_set_state", "(", "self", ",", "data", ")", ":", "field", "=", "self", ".", "_deconz_id", "+", "'/recall'", "await", "self", ".", "_async_set_state_callback", "(", "field", ",", "data", ")" ]
Recall scene to group.
[ "Recall", "scene", "to", "group", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/group.py#L175-L178
15,067
Kane610/deconz
pydeconz/light.py
DeconzLightBase.async_update
def async_update(self, event): """New event for light. Check that state is part of event. Signal that light has updated state. """ self.update_attr(event.get('state', {})) super().async_update(event)
python
def async_update(self, event): self.update_attr(event.get('state', {})) super().async_update(event)
[ "def", "async_update", "(", "self", ",", "event", ")", ":", "self", ".", "update_attr", "(", "event", ".", "get", "(", "'state'", ",", "{", "}", ")", ")", "super", "(", ")", ".", "async_update", "(", "event", ")" ]
New event for light. Check that state is part of event. Signal that light has updated state.
[ "New", "event", "for", "light", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/light.py#L25-L32
15,068
sbg/sevenbridges-python
sevenbridges/models/file.py
File.upload
def upload(cls, path, project=None, parent=None, file_name=None, overwrite=False, retry=5, timeout=10, part_size=PartSize.UPLOAD_MINIMUM_PART_SIZE, wait=True, api=None): """ Uploads a file using multipart upload and returns an upload handle if the wait parameter is set to False. If wait is set to True it will block until the upload is completed. :param path: File path on local disc. :param project: Project identifier :param parent: Parent folder identifier :param file_name: Optional file name. :param overwrite: If true will overwrite the file on the server. :param retry: Number of retries if error occurs during upload. :param timeout: Timeout for http requests. :param part_size: Part size in bytes. :param wait: If true will wait for upload to complete. :param api: Api instance. """ api = api or cls._API extra = {'resource': cls.__name__, 'query': { 'path': path, 'project': project, 'file_name': file_name, 'overwrite': overwrite, 'retry': retry, 'timeout': timeout, 'part_size': part_size, 'wait': wait, }} logger.info('Uploading file', extra=extra) if not project and not parent: raise SbgError('A project or parent identifier is required.') if project and parent: raise SbgError( 'Project and parent identifiers are mutually exclusive.' ) if project: project = Transform.to_project(project) if parent: parent = Transform.to_file(parent) upload = Upload( file_path=path, project=project, parent=parent, file_name=file_name, overwrite=overwrite, retry_count=retry, timeout=timeout, part_size=part_size, api=api ) if wait: upload.start() upload.wait() return upload else: return upload
python
def upload(cls, path, project=None, parent=None, file_name=None, overwrite=False, retry=5, timeout=10, part_size=PartSize.UPLOAD_MINIMUM_PART_SIZE, wait=True, api=None): api = api or cls._API extra = {'resource': cls.__name__, 'query': { 'path': path, 'project': project, 'file_name': file_name, 'overwrite': overwrite, 'retry': retry, 'timeout': timeout, 'part_size': part_size, 'wait': wait, }} logger.info('Uploading file', extra=extra) if not project and not parent: raise SbgError('A project or parent identifier is required.') if project and parent: raise SbgError( 'Project and parent identifiers are mutually exclusive.' ) if project: project = Transform.to_project(project) if parent: parent = Transform.to_file(parent) upload = Upload( file_path=path, project=project, parent=parent, file_name=file_name, overwrite=overwrite, retry_count=retry, timeout=timeout, part_size=part_size, api=api ) if wait: upload.start() upload.wait() return upload else: return upload
[ "def", "upload", "(", "cls", ",", "path", ",", "project", "=", "None", ",", "parent", "=", "None", ",", "file_name", "=", "None", ",", "overwrite", "=", "False", ",", "retry", "=", "5", ",", "timeout", "=", "10", ",", "part_size", "=", "PartSize", ...
Uploads a file using multipart upload and returns an upload handle if the wait parameter is set to False. If wait is set to True it will block until the upload is completed. :param path: File path on local disc. :param project: Project identifier :param parent: Parent folder identifier :param file_name: Optional file name. :param overwrite: If true will overwrite the file on the server. :param retry: Number of retries if error occurs during upload. :param timeout: Timeout for http requests. :param part_size: Part size in bytes. :param wait: If true will wait for upload to complete. :param api: Api instance.
[ "Uploads", "a", "file", "using", "multipart", "upload", "and", "returns", "an", "upload", "handle", "if", "the", "wait", "parameter", "is", "set", "to", "False", ".", "If", "wait", "is", "set", "to", "True", "it", "will", "block", "until", "the", "upload...
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/file.py#L158-L216
15,069
sbg/sevenbridges-python
sevenbridges/models/file.py
File.reload
def reload(self): """ Refreshes the file with the data from the server. """ try: data = self._api.get(self.href, append_base=False).json() resource = File(api=self._api, **data) except Exception: try: data = self._api.get( self._URL['get'].format(id=self.id)).json() resource = File(api=self._api, **data) except Exception: raise SbgError('Resource can not be refreshed!') self._data = resource._data self._dirty = resource._dirty self._old = copy.deepcopy(self._data.data) # If file.metadata = value was executed # file object will have attribute _method='PUT', which tells us # to force overwrite of metadata on the server. This is metadata # specific. Once we reload the resource we delete the attribute # _method from the instance. try: delattr(self, '_method') except AttributeError: pass
python
def reload(self): try: data = self._api.get(self.href, append_base=False).json() resource = File(api=self._api, **data) except Exception: try: data = self._api.get( self._URL['get'].format(id=self.id)).json() resource = File(api=self._api, **data) except Exception: raise SbgError('Resource can not be refreshed!') self._data = resource._data self._dirty = resource._dirty self._old = copy.deepcopy(self._data.data) # If file.metadata = value was executed # file object will have attribute _method='PUT', which tells us # to force overwrite of metadata on the server. This is metadata # specific. Once we reload the resource we delete the attribute # _method from the instance. try: delattr(self, '_method') except AttributeError: pass
[ "def", "reload", "(", "self", ")", ":", "try", ":", "data", "=", "self", ".", "_api", ".", "get", "(", "self", ".", "href", ",", "append_base", "=", "False", ")", ".", "json", "(", ")", "resource", "=", "File", "(", "api", "=", "self", ".", "_a...
Refreshes the file with the data from the server.
[ "Refreshes", "the", "file", "with", "the", "data", "from", "the", "server", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/file.py#L345-L372
15,070
sbg/sevenbridges-python
sevenbridges/models/file.py
File.content
def content(self, path=None, overwrite=True, encoding='utf-8'): """ Downloads file to the specified path or as temporary file and reads the file content in memory. Should not be used on very large files. :param path: Path for file download If omitted tmp file will be used. :param overwrite: Overwrite file if exists locally :param encoding: File encoding, by default it is UTF-8 :return: File content. """ if path: self.download(wait=True, path=path, overwrite=overwrite) with io.open(path, 'r', encoding=encoding) as fp: return fp.read() with tempfile.NamedTemporaryFile() as tmpfile: self.download(wait=True, path=tmpfile.name, overwrite=overwrite) with io.open(tmpfile.name, 'r', encoding=encoding) as fp: return fp.read()
python
def content(self, path=None, overwrite=True, encoding='utf-8'): if path: self.download(wait=True, path=path, overwrite=overwrite) with io.open(path, 'r', encoding=encoding) as fp: return fp.read() with tempfile.NamedTemporaryFile() as tmpfile: self.download(wait=True, path=tmpfile.name, overwrite=overwrite) with io.open(tmpfile.name, 'r', encoding=encoding) as fp: return fp.read()
[ "def", "content", "(", "self", ",", "path", "=", "None", ",", "overwrite", "=", "True", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "path", ":", "self", ".", "download", "(", "wait", "=", "True", ",", "path", "=", "path", ",", "overwrite", "="...
Downloads file to the specified path or as temporary file and reads the file content in memory. Should not be used on very large files. :param path: Path for file download If omitted tmp file will be used. :param overwrite: Overwrite file if exists locally :param encoding: File encoding, by default it is UTF-8 :return: File content.
[ "Downloads", "file", "to", "the", "specified", "path", "or", "as", "temporary", "file", "and", "reads", "the", "file", "content", "in", "memory", ".", "Should", "not", "be", "used", "on", "very", "large", "files", "." ]
f62640d1018d959f0b686f2dbe5e183085336607
https://github.com/sbg/sevenbridges-python/blob/f62640d1018d959f0b686f2dbe5e183085336607/sevenbridges/models/file.py#L374-L393
15,071
indico/indico-plugins
piwik/indico_piwik/queries/utils.py
get_json_from_remote_server
def get_json_from_remote_server(func, **kwargs): """ Safely manage calls to the remote server by encapsulating JSON creation from Piwik data. """ rawjson = func(**kwargs) if rawjson is None: # If the request failed we already logged in in PiwikRequest; # no need to get into the exception handler below. return {} try: data = json.loads(rawjson) if isinstance(data, dict) and data.get('result') == 'error': current_plugin.logger.error('The Piwik server responded with an error: %s', data['message']) return {} return data except Exception: current_plugin.logger.exception('Unable to load JSON from source %s', rawjson) return {}
python
def get_json_from_remote_server(func, **kwargs): rawjson = func(**kwargs) if rawjson is None: # If the request failed we already logged in in PiwikRequest; # no need to get into the exception handler below. return {} try: data = json.loads(rawjson) if isinstance(data, dict) and data.get('result') == 'error': current_plugin.logger.error('The Piwik server responded with an error: %s', data['message']) return {} return data except Exception: current_plugin.logger.exception('Unable to load JSON from source %s', rawjson) return {}
[ "def", "get_json_from_remote_server", "(", "func", ",", "*", "*", "kwargs", ")", ":", "rawjson", "=", "func", "(", "*", "*", "kwargs", ")", "if", "rawjson", "is", "None", ":", "# If the request failed we already logged in in PiwikRequest;", "# no need to get into the ...
Safely manage calls to the remote server by encapsulating JSON creation from Piwik data.
[ "Safely", "manage", "calls", "to", "the", "remote", "server", "by", "encapsulating", "JSON", "creation", "from", "Piwik", "data", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/queries/utils.py#L22-L40
15,072
indico/indico-plugins
piwik/indico_piwik/queries/utils.py
reduce_json
def reduce_json(data): """Reduce a JSON object""" return reduce(lambda x, y: int(x) + int(y), data.values())
python
def reduce_json(data): return reduce(lambda x, y: int(x) + int(y), data.values())
[ "def", "reduce_json", "(", "data", ")", ":", "return", "reduce", "(", "lambda", "x", ",", "y", ":", "int", "(", "x", ")", "+", "int", "(", "y", ")", ",", "data", ".", "values", "(", ")", ")" ]
Reduce a JSON object
[ "Reduce", "a", "JSON", "object" ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/queries/utils.py#L43-L45
15,073
indico/indico-plugins
piwik/indico_piwik/queries/utils.py
stringify_seconds
def stringify_seconds(seconds=0): """ Takes time as a value of seconds and deduces the delta in human-readable HHh MMm SSs format. """ seconds = int(seconds) minutes = seconds / 60 ti = {'h': 0, 'm': 0, 's': 0} if seconds > 0: ti['s'] = seconds % 60 ti['m'] = minutes % 60 ti['h'] = minutes / 60 return "%dh %dm %ds" % (ti['h'], ti['m'], ti['s'])
python
def stringify_seconds(seconds=0): seconds = int(seconds) minutes = seconds / 60 ti = {'h': 0, 'm': 0, 's': 0} if seconds > 0: ti['s'] = seconds % 60 ti['m'] = minutes % 60 ti['h'] = minutes / 60 return "%dh %dm %ds" % (ti['h'], ti['m'], ti['s'])
[ "def", "stringify_seconds", "(", "seconds", "=", "0", ")", ":", "seconds", "=", "int", "(", "seconds", ")", "minutes", "=", "seconds", "/", "60", "ti", "=", "{", "'h'", ":", "0", ",", "'m'", ":", "0", ",", "'s'", ":", "0", "}", "if", "seconds", ...
Takes time as a value of seconds and deduces the delta in human-readable HHh MMm SSs format.
[ "Takes", "time", "as", "a", "value", "of", "seconds", "and", "deduces", "the", "delta", "in", "human", "-", "readable", "HHh", "MMm", "SSs", "format", "." ]
fe50085cc63be9b8161b09539e662e7b04e4b38e
https://github.com/indico/indico-plugins/blob/fe50085cc63be9b8161b09539e662e7b04e4b38e/piwik/indico_piwik/queries/utils.py#L48-L62
15,074
Kane610/deconz
pydeconz/sensor.py
create_sensor
def create_sensor(sensor_id, sensor, async_set_state_callback): """Simplify creating sensor by not needing to know type.""" if sensor['type'] in CONSUMPTION: return Consumption(sensor_id, sensor) if sensor['type'] in CARBONMONOXIDE: return CarbonMonoxide(sensor_id, sensor) if sensor['type'] in DAYLIGHT: return Daylight(sensor_id, sensor) if sensor['type'] in FIRE: return Fire(sensor_id, sensor) if sensor['type'] in GENERICFLAG: return GenericFlag(sensor_id, sensor) if sensor['type'] in GENERICSTATUS: return GenericStatus(sensor_id, sensor) if sensor['type'] in HUMIDITY: return Humidity(sensor_id, sensor) if sensor['type'] in LIGHTLEVEL: return LightLevel(sensor_id, sensor) if sensor['type'] in OPENCLOSE: return OpenClose(sensor_id, sensor) if sensor['type'] in POWER: return Power(sensor_id, sensor) if sensor['type'] in PRESENCE: return Presence(sensor_id, sensor) if sensor['type'] in PRESSURE: return Pressure(sensor_id, sensor) if sensor['type'] in SWITCH: return Switch(sensor_id, sensor) if sensor['type'] in TEMPERATURE: return Temperature(sensor_id, sensor) if sensor['type'] in THERMOSTAT: return Thermostat(sensor_id, sensor, async_set_state_callback) if sensor['type'] in VIBRATION: return Vibration(sensor_id, sensor) if sensor['type'] in WATER: return Water(sensor_id, sensor)
python
def create_sensor(sensor_id, sensor, async_set_state_callback): if sensor['type'] in CONSUMPTION: return Consumption(sensor_id, sensor) if sensor['type'] in CARBONMONOXIDE: return CarbonMonoxide(sensor_id, sensor) if sensor['type'] in DAYLIGHT: return Daylight(sensor_id, sensor) if sensor['type'] in FIRE: return Fire(sensor_id, sensor) if sensor['type'] in GENERICFLAG: return GenericFlag(sensor_id, sensor) if sensor['type'] in GENERICSTATUS: return GenericStatus(sensor_id, sensor) if sensor['type'] in HUMIDITY: return Humidity(sensor_id, sensor) if sensor['type'] in LIGHTLEVEL: return LightLevel(sensor_id, sensor) if sensor['type'] in OPENCLOSE: return OpenClose(sensor_id, sensor) if sensor['type'] in POWER: return Power(sensor_id, sensor) if sensor['type'] in PRESENCE: return Presence(sensor_id, sensor) if sensor['type'] in PRESSURE: return Pressure(sensor_id, sensor) if sensor['type'] in SWITCH: return Switch(sensor_id, sensor) if sensor['type'] in TEMPERATURE: return Temperature(sensor_id, sensor) if sensor['type'] in THERMOSTAT: return Thermostat(sensor_id, sensor, async_set_state_callback) if sensor['type'] in VIBRATION: return Vibration(sensor_id, sensor) if sensor['type'] in WATER: return Water(sensor_id, sensor)
[ "def", "create_sensor", "(", "sensor_id", ",", "sensor", ",", "async_set_state_callback", ")", ":", "if", "sensor", "[", "'type'", "]", "in", "CONSUMPTION", ":", "return", "Consumption", "(", "sensor_id", ",", "sensor", ")", "if", "sensor", "[", "'type'", "]...
Simplify creating sensor by not needing to know type.
[ "Simplify", "creating", "sensor", "by", "not", "needing", "to", "know", "type", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/sensor.py#L1012-L1047
15,075
Kane610/deconz
pydeconz/sensor.py
supported_sensor
def supported_sensor(sensor): """Check if sensor is supported by pydeconz.""" if sensor['type'] in DECONZ_BINARY_SENSOR + DECONZ_SENSOR + OTHER_SENSOR: return True _LOGGER.info('Unsupported sensor type %s (%s)', sensor['type'], sensor['name']) return False
python
def supported_sensor(sensor): if sensor['type'] in DECONZ_BINARY_SENSOR + DECONZ_SENSOR + OTHER_SENSOR: return True _LOGGER.info('Unsupported sensor type %s (%s)', sensor['type'], sensor['name']) return False
[ "def", "supported_sensor", "(", "sensor", ")", ":", "if", "sensor", "[", "'type'", "]", "in", "DECONZ_BINARY_SENSOR", "+", "DECONZ_SENSOR", "+", "OTHER_SENSOR", ":", "return", "True", "_LOGGER", ".", "info", "(", "'Unsupported sensor type %s (%s)'", ",", "sensor",...
Check if sensor is supported by pydeconz.
[ "Check", "if", "sensor", "is", "supported", "by", "pydeconz", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/sensor.py#L1050-L1056
15,076
Kane610/deconz
pydeconz/sensor.py
DeconzSensor.async_update
def async_update(self, event, reason={}): """New event for sensor. Check if state or config is part of event. Signal that sensor has updated attributes. Inform what attributes got changed values. """ reason['attr'] = [] for data in ['state', 'config']: changed_attr = self.update_attr(event.get(data, {})) reason[data] = data in event reason['attr'] += changed_attr super().async_update(event, reason)
python
def async_update(self, event, reason={}): reason['attr'] = [] for data in ['state', 'config']: changed_attr = self.update_attr(event.get(data, {})) reason[data] = data in event reason['attr'] += changed_attr super().async_update(event, reason)
[ "def", "async_update", "(", "self", ",", "event", ",", "reason", "=", "{", "}", ")", ":", "reason", "[", "'attr'", "]", "=", "[", "]", "for", "data", "in", "[", "'state'", ",", "'config'", "]", ":", "changed_attr", "=", "self", ".", "update_attr", ...
New event for sensor. Check if state or config is part of event. Signal that sensor has updated attributes. Inform what attributes got changed values.
[ "New", "event", "for", "sensor", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/sensor.py#L57-L69
15,077
Kane610/deconz
pydeconz/sensor.py
Daylight.status
def status(self): """Return the daylight status string.""" if self._status == 100: return "nadir" elif self._status == 110: return "night_end" elif self._status == 120: return "nautical_dawn" elif self._status == 130: return "dawn" elif self._status == 140: return "sunrise_start" elif self._status == 150: return "sunrise_end" elif self._status == 160: return "golden_hour_1" elif self._status == 170: return "solar_noon" elif self._status == 180: return "golden_hour_2" elif self._status == 190: return "sunset_start" elif self._status == 200: return "sunset_end" elif self._status == 210: return "dusk" elif self._status == 220: return "nautical_dusk" elif self._status == 230: return "night_start" else: return "unknown"
python
def status(self): if self._status == 100: return "nadir" elif self._status == 110: return "night_end" elif self._status == 120: return "nautical_dawn" elif self._status == 130: return "dawn" elif self._status == 140: return "sunrise_start" elif self._status == 150: return "sunrise_end" elif self._status == 160: return "golden_hour_1" elif self._status == 170: return "solar_noon" elif self._status == 180: return "golden_hour_2" elif self._status == 190: return "sunset_start" elif self._status == 200: return "sunset_end" elif self._status == 210: return "dusk" elif self._status == 220: return "nautical_dusk" elif self._status == 230: return "night_start" else: return "unknown"
[ "def", "status", "(", "self", ")", ":", "if", "self", ".", "_status", "==", "100", ":", "return", "\"nadir\"", "elif", "self", ".", "_status", "==", "110", ":", "return", "\"night_end\"", "elif", "self", ".", "_status", "==", "120", ":", "return", "\"n...
Return the daylight status string.
[ "Return", "the", "daylight", "status", "string", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/sensor.py#L316-L347
15,078
Kane610/deconz
pydeconz/sensor.py
Thermostat.async_set_config
async def async_set_config(self, data): """Set config of thermostat. { "mode": "auto", "heatsetpoint": 180, } """ field = self.deconz_id + '/config' await self._async_set_state_callback(field, data)
python
async def async_set_config(self, data): field = self.deconz_id + '/config' await self._async_set_state_callback(field, data)
[ "async", "def", "async_set_config", "(", "self", ",", "data", ")", ":", "field", "=", "self", ".", "deconz_id", "+", "'/config'", "await", "self", ".", "_async_set_state_callback", "(", "field", ",", "data", ")" ]
Set config of thermostat. { "mode": "auto", "heatsetpoint": 180, }
[ "Set", "config", "of", "thermostat", "." ]
8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6
https://github.com/Kane610/deconz/blob/8a9498dbbc8c168d4a081173ad6c3b1e17fffdf6/pydeconz/sensor.py#L842-L851
15,079
zhmcclient/python-zhmcclient
zhmcclient/_metrics.py
_metric_value
def _metric_value(value_str, metric_type): """ Return a Python-typed metric value from a metric value string. """ if metric_type in (int, float): try: return metric_type(value_str) except ValueError: raise ValueError("Invalid {} metric value: {!r}". format(metric_type.__class__.__name__, value_str)) elif metric_type is six.text_type: # In Python 3, decode('unicode_escape) requires bytes, so we need # to encode to bytes. This also works in Python 2. return value_str.strip('"').encode('utf-8').decode('unicode_escape') else: assert metric_type is bool lower_str = value_str.lower() if lower_str == 'true': return True elif lower_str == 'false': return False else: raise ValueError("Invalid boolean metric value: {!r}". format(value_str))
python
def _metric_value(value_str, metric_type): if metric_type in (int, float): try: return metric_type(value_str) except ValueError: raise ValueError("Invalid {} metric value: {!r}". format(metric_type.__class__.__name__, value_str)) elif metric_type is six.text_type: # In Python 3, decode('unicode_escape) requires bytes, so we need # to encode to bytes. This also works in Python 2. return value_str.strip('"').encode('utf-8').decode('unicode_escape') else: assert metric_type is bool lower_str = value_str.lower() if lower_str == 'true': return True elif lower_str == 'false': return False else: raise ValueError("Invalid boolean metric value: {!r}". format(value_str))
[ "def", "_metric_value", "(", "value_str", ",", "metric_type", ")", ":", "if", "metric_type", "in", "(", "int", ",", "float", ")", ":", "try", ":", "return", "metric_type", "(", "value_str", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"I...
Return a Python-typed metric value from a metric value string.
[ "Return", "a", "Python", "-", "typed", "metric", "value", "from", "a", "metric", "value", "string", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_metrics.py#L484-L507
15,080
zhmcclient/python-zhmcclient
zhmcclient/_metrics.py
_metric_unit_from_name
def _metric_unit_from_name(metric_name): """ Return a metric unit string for human consumption, that is inferred from the metric name. If a unit cannot be inferred, `None` is returned. """ for item in _PATTERN_UNIT_LIST: pattern, unit = item if pattern.match(metric_name): return unit return None
python
def _metric_unit_from_name(metric_name): for item in _PATTERN_UNIT_LIST: pattern, unit = item if pattern.match(metric_name): return unit return None
[ "def", "_metric_unit_from_name", "(", "metric_name", ")", ":", "for", "item", "in", "_PATTERN_UNIT_LIST", ":", "pattern", ",", "unit", "=", "item", "if", "pattern", ".", "match", "(", "metric_name", ")", ":", "return", "unit", "return", "None" ]
Return a metric unit string for human consumption, that is inferred from the metric name. If a unit cannot be inferred, `None` is returned.
[ "Return", "a", "metric", "unit", "string", "for", "human", "consumption", "that", "is", "inferred", "from", "the", "metric", "name", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_metrics.py#L510-L521
15,081
zhmcclient/python-zhmcclient
zhmcclient/_metrics.py
MetricsContext._setup_metric_group_definitions
def _setup_metric_group_definitions(self): """ Return the dict of MetricGroupDefinition objects for this metrics context, by processing its 'metric-group-infos' property. """ # Dictionary of MetricGroupDefinition objects, by metric group name metric_group_definitions = dict() for mg_info in self.properties['metric-group-infos']: mg_name = mg_info['group-name'] mg_def = MetricGroupDefinition( name=mg_name, resource_class=_resource_class_from_group(mg_name), metric_definitions=dict()) for i, m_info in enumerate(mg_info['metric-infos']): m_name = m_info['metric-name'] m_def = MetricDefinition( index=i, name=m_name, type=_metric_type(m_info['metric-type']), unit=_metric_unit_from_name(m_name)) mg_def.metric_definitions[m_name] = m_def metric_group_definitions[mg_name] = mg_def return metric_group_definitions
python
def _setup_metric_group_definitions(self): # Dictionary of MetricGroupDefinition objects, by metric group name metric_group_definitions = dict() for mg_info in self.properties['metric-group-infos']: mg_name = mg_info['group-name'] mg_def = MetricGroupDefinition( name=mg_name, resource_class=_resource_class_from_group(mg_name), metric_definitions=dict()) for i, m_info in enumerate(mg_info['metric-infos']): m_name = m_info['metric-name'] m_def = MetricDefinition( index=i, name=m_name, type=_metric_type(m_info['metric-type']), unit=_metric_unit_from_name(m_name)) mg_def.metric_definitions[m_name] = m_def metric_group_definitions[mg_name] = mg_def return metric_group_definitions
[ "def", "_setup_metric_group_definitions", "(", "self", ")", ":", "# Dictionary of MetricGroupDefinition objects, by metric group name", "metric_group_definitions", "=", "dict", "(", ")", "for", "mg_info", "in", "self", ".", "properties", "[", "'metric-group-infos'", "]", ":...
Return the dict of MetricGroupDefinition objects for this metrics context, by processing its 'metric-group-infos' property.
[ "Return", "the", "dict", "of", "MetricGroupDefinition", "objects", "for", "this", "metrics", "context", "by", "processing", "its", "metric", "-", "group", "-", "infos", "property", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_metrics.py#L272-L294
15,082
zhmcclient/python-zhmcclient
zhmcclient/_metrics.py
MetricsResponse._setup_metric_group_values
def _setup_metric_group_values(self): """ Return the list of MetricGroupValues objects for this metrics response, by processing its metrics response string. The lines in the metrics response string are:: MetricsResponse: MetricsGroup{0,*} <emptyline> a third empty line at the end MetricsGroup: MetricsGroupName ObjectValues{0,*} <emptyline> a second empty line after each MG ObjectValues: ObjectURI Timestamp ValueRow{1,*} <emptyline> a first empty line after this blk """ mg_defs = self._metrics_context.metric_group_definitions metric_group_name = None resource_uri = None dt_timestamp = None object_values = None metric_group_values = list() state = 0 for mr_line in self._metrics_response_str.splitlines(): if state == 0: if object_values is not None: # Store the result from the previous metric group mgv = MetricGroupValues(metric_group_name, object_values) metric_group_values.append(mgv) object_values = None if mr_line == '': # Skip initial (or trailing) empty lines pass else: # Process the next metrics group metric_group_name = mr_line.strip('"') # No " or \ inside assert metric_group_name in mg_defs m_defs = mg_defs[metric_group_name].metric_definitions object_values = list() state = 1 elif state == 1: if mr_line == '': # There are no (or no more) ObjectValues items in this # metrics group state = 0 else: # There are ObjectValues items resource_uri = mr_line.strip('"') # No " or \ inside state = 2 elif state == 2: # Process the timestamp assert mr_line != '' try: dt_timestamp = datetime_from_timestamp(int(mr_line)) except ValueError: # Sometimes, the returned epoch timestamp values are way # too large, e.g. 3651584404810066 (which would translate # to the year 115791 A.D.). Python datetime supports # up to the year 9999. We circumvent this issue by # simply using the current date&time. # TODO: Remove the circumvention for too large timestamps. dt_timestamp = datetime.now(pytz.utc) state = 3 elif state == 3: if mr_line != '': # Process the metric values in the ValueRow line str_values = mr_line.split(',') metrics = dict() for m_name in m_defs: m_def = m_defs[m_name] m_type = m_def.type m_value_str = str_values[m_def.index] m_value = _metric_value(m_value_str, m_type) metrics[m_name] = m_value ov = MetricObjectValues( self._client, mg_defs[metric_group_name], resource_uri, dt_timestamp, metrics) object_values.append(ov) # stay in this state, for more ValueRow lines else: # On the empty line after the last ValueRow line state = 1 return metric_group_values
python
def _setup_metric_group_values(self): mg_defs = self._metrics_context.metric_group_definitions metric_group_name = None resource_uri = None dt_timestamp = None object_values = None metric_group_values = list() state = 0 for mr_line in self._metrics_response_str.splitlines(): if state == 0: if object_values is not None: # Store the result from the previous metric group mgv = MetricGroupValues(metric_group_name, object_values) metric_group_values.append(mgv) object_values = None if mr_line == '': # Skip initial (or trailing) empty lines pass else: # Process the next metrics group metric_group_name = mr_line.strip('"') # No " or \ inside assert metric_group_name in mg_defs m_defs = mg_defs[metric_group_name].metric_definitions object_values = list() state = 1 elif state == 1: if mr_line == '': # There are no (or no more) ObjectValues items in this # metrics group state = 0 else: # There are ObjectValues items resource_uri = mr_line.strip('"') # No " or \ inside state = 2 elif state == 2: # Process the timestamp assert mr_line != '' try: dt_timestamp = datetime_from_timestamp(int(mr_line)) except ValueError: # Sometimes, the returned epoch timestamp values are way # too large, e.g. 3651584404810066 (which would translate # to the year 115791 A.D.). Python datetime supports # up to the year 9999. We circumvent this issue by # simply using the current date&time. # TODO: Remove the circumvention for too large timestamps. dt_timestamp = datetime.now(pytz.utc) state = 3 elif state == 3: if mr_line != '': # Process the metric values in the ValueRow line str_values = mr_line.split(',') metrics = dict() for m_name in m_defs: m_def = m_defs[m_name] m_type = m_def.type m_value_str = str_values[m_def.index] m_value = _metric_value(m_value_str, m_type) metrics[m_name] = m_value ov = MetricObjectValues( self._client, mg_defs[metric_group_name], resource_uri, dt_timestamp, metrics) object_values.append(ov) # stay in this state, for more ValueRow lines else: # On the empty line after the last ValueRow line state = 1 return metric_group_values
[ "def", "_setup_metric_group_values", "(", "self", ")", ":", "mg_defs", "=", "self", ".", "_metrics_context", ".", "metric_group_definitions", "metric_group_name", "=", "None", "resource_uri", "=", "None", "dt_timestamp", "=", "None", "object_values", "=", "None", "m...
Return the list of MetricGroupValues objects for this metrics response, by processing its metrics response string. The lines in the metrics response string are:: MetricsResponse: MetricsGroup{0,*} <emptyline> a third empty line at the end MetricsGroup: MetricsGroupName ObjectValues{0,*} <emptyline> a second empty line after each MG ObjectValues: ObjectURI Timestamp ValueRow{1,*} <emptyline> a first empty line after this blk
[ "Return", "the", "list", "of", "MetricGroupValues", "objects", "for", "this", "metrics", "response", "by", "processing", "its", "metrics", "response", "string", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_metrics.py#L617-L706
15,083
zhmcclient/python-zhmcclient
zhmcclient_mock/_idpool.py
IdPool._expand
def _expand(self): """ Expand the free pool, if possible. If out of capacity w.r.t. the defined ID value range, ValueError is raised. """ assert not self._free # free pool is empty expand_end = self._expand_start + self._expand_len if expand_end > self._range_end: # This happens if the size of the value range is not a multiple # of the expansion chunk size. expand_end = self._range_end if self._expand_start == expand_end: raise ValueError("Out of capacity in ID pool") self._free = set(range(self._expand_start, expand_end)) self._expand_start = expand_end
python
def _expand(self): assert not self._free # free pool is empty expand_end = self._expand_start + self._expand_len if expand_end > self._range_end: # This happens if the size of the value range is not a multiple # of the expansion chunk size. expand_end = self._range_end if self._expand_start == expand_end: raise ValueError("Out of capacity in ID pool") self._free = set(range(self._expand_start, expand_end)) self._expand_start = expand_end
[ "def", "_expand", "(", "self", ")", ":", "assert", "not", "self", ".", "_free", "# free pool is empty", "expand_end", "=", "self", ".", "_expand_start", "+", "self", ".", "_expand_len", "if", "expand_end", ">", "self", ".", "_range_end", ":", "# This happens i...
Expand the free pool, if possible. If out of capacity w.r.t. the defined ID value range, ValueError is raised.
[ "Expand", "the", "free", "pool", "if", "possible", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_idpool.py#L67-L83
15,084
zhmcclient/python-zhmcclient
zhmcclient_mock/_idpool.py
IdPool.alloc
def alloc(self): """ Allocate an ID value and return it. Raises: ValueError: Out of capacity in ID pool. """ if not self._free: self._expand() id = self._free.pop() self._used.add(id) return id
python
def alloc(self): if not self._free: self._expand() id = self._free.pop() self._used.add(id) return id
[ "def", "alloc", "(", "self", ")", ":", "if", "not", "self", ".", "_free", ":", "self", ".", "_expand", "(", ")", "id", "=", "self", ".", "_free", ".", "pop", "(", ")", "self", ".", "_used", ".", "add", "(", "id", ")", "return", "id" ]
Allocate an ID value and return it. Raises: ValueError: Out of capacity in ID pool.
[ "Allocate", "an", "ID", "value", "and", "return", "it", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_idpool.py#L85-L96
15,085
zhmcclient/python-zhmcclient
zhmcclient/_nic.py
NicManager.create
def create(self, properties): """ Create and configure a NIC in this Partition. The NIC must be backed by an adapter port (on an OSA, ROCE, or Hipersockets adapter). The way the backing adapter port is specified in the "properties" parameter of this method depends on the adapter type, as follows: * For OSA and Hipersockets adapters, the "virtual-switch-uri" property is used to specify the URI of the virtual switch that is associated with the backing adapter port. This virtual switch is a resource that automatically exists as soon as the adapter resource exists. Note that these virtual switches do not show up in the HMC GUI; but they do show up at the HMC REST API and thus also at the zhmcclient API as the :class:`~zhmcclient.VirtualSwitch` class. The value for the "virtual-switch-uri" property can be determined from a given adapter name and port index as shown in the following example code (omitting any error handling): .. code-block:: python partition = ... # Partition object for the new NIC adapter_name = 'OSA #1' # name of adapter with backing port adapter_port_index = 0 # port index of backing port adapter = partition.manager.cpc.adapters.find(name=adapter_name) vswitches = partition.manager.cpc.virtual_switches.findall( **{'backing-adapter-uri': adapter.uri}) vswitch = None for vs in vswitches: if vs.get_property('port') == adapter_port_index: vswitch = vs break properties['virtual-switch-uri'] = vswitch.uri * For RoCE adapters, the "network-adapter-port-uri" property is used to specify the URI of the backing adapter port, directly. The value for the "network-adapter-port-uri" property can be determined from a given adapter name and port index as shown in the following example code (omitting any error handling): .. code-block:: python partition = ... # Partition object for the new NIC adapter_name = 'ROCE #1' # name of adapter with backing port adapter_port_index = 0 # port index of backing port adapter = partition.manager.cpc.adapters.find(name=adapter_name) port = adapter.ports.find(index=adapter_port_index) properties['network-adapter-port-uri'] = port.uri Authorization requirements: * Object-access permission to this Partition. * Object-access permission to the backing Adapter for the new NIC. * Task permission to the "Partition Details" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create NIC' in the :term:`HMC API` book. Returns: Nic: The resource object for the new NIC. The object will have its 'element-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ result = self.session.post(self.partition.uri + '/nics', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] nic = Nic(self, uri, name, props) self._name_uri_cache.update(name, uri) return nic
python
def create(self, properties): result = self.session.post(self.partition.uri + '/nics', body=properties) # There should not be overlaps, but just in case there are, the # returned props should overwrite the input props: props = copy.deepcopy(properties) props.update(result) name = props.get(self._name_prop, None) uri = props[self._uri_prop] nic = Nic(self, uri, name, props) self._name_uri_cache.update(name, uri) return nic
[ "def", "create", "(", "self", ",", "properties", ")", ":", "result", "=", "self", ".", "session", ".", "post", "(", "self", ".", "partition", ".", "uri", "+", "'/nics'", ",", "body", "=", "properties", ")", "# There should not be overlaps, but just in case the...
Create and configure a NIC in this Partition. The NIC must be backed by an adapter port (on an OSA, ROCE, or Hipersockets adapter). The way the backing adapter port is specified in the "properties" parameter of this method depends on the adapter type, as follows: * For OSA and Hipersockets adapters, the "virtual-switch-uri" property is used to specify the URI of the virtual switch that is associated with the backing adapter port. This virtual switch is a resource that automatically exists as soon as the adapter resource exists. Note that these virtual switches do not show up in the HMC GUI; but they do show up at the HMC REST API and thus also at the zhmcclient API as the :class:`~zhmcclient.VirtualSwitch` class. The value for the "virtual-switch-uri" property can be determined from a given adapter name and port index as shown in the following example code (omitting any error handling): .. code-block:: python partition = ... # Partition object for the new NIC adapter_name = 'OSA #1' # name of adapter with backing port adapter_port_index = 0 # port index of backing port adapter = partition.manager.cpc.adapters.find(name=adapter_name) vswitches = partition.manager.cpc.virtual_switches.findall( **{'backing-adapter-uri': adapter.uri}) vswitch = None for vs in vswitches: if vs.get_property('port') == adapter_port_index: vswitch = vs break properties['virtual-switch-uri'] = vswitch.uri * For RoCE adapters, the "network-adapter-port-uri" property is used to specify the URI of the backing adapter port, directly. The value for the "network-adapter-port-uri" property can be determined from a given adapter name and port index as shown in the following example code (omitting any error handling): .. code-block:: python partition = ... # Partition object for the new NIC adapter_name = 'ROCE #1' # name of adapter with backing port adapter_port_index = 0 # port index of backing port adapter = partition.manager.cpc.adapters.find(name=adapter_name) port = adapter.ports.find(index=adapter_port_index) properties['network-adapter-port-uri'] = port.uri Authorization requirements: * Object-access permission to this Partition. * Object-access permission to the backing Adapter for the new NIC. * Task permission to the "Partition Details" task. Parameters: properties (dict): Initial property values. Allowable properties are defined in section 'Request body contents' in section 'Create NIC' in the :term:`HMC API` book. Returns: Nic: The resource object for the new NIC. The object will have its 'element-uri' property set as returned by the HMC, and will also have the input properties set. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Create", "and", "configure", "a", "NIC", "in", "this", "Partition", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_nic.py#L134-L234
15,086
zhmcclient/python-zhmcclient
zhmcclient/_nic.py
Nic.delete
def delete(self): """ Delete this NIC. Authorization requirements: * Object-access permission to the Partition containing this HBA. * Task permission to the "Partition Details" task. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ self.manager.session.delete(self._uri) self.manager._name_uri_cache.delete( self.properties.get(self.manager._name_prop, None))
python
def delete(self): self.manager.session.delete(self._uri) self.manager._name_uri_cache.delete( self.properties.get(self.manager._name_prop, None))
[ "def", "delete", "(", "self", ")", ":", "self", ".", "manager", ".", "session", ".", "delete", "(", "self", ".", "_uri", ")", "self", ".", "manager", ".", "_name_uri_cache", ".", "delete", "(", "self", ".", "properties", ".", "get", "(", "self", ".",...
Delete this NIC. Authorization requirements: * Object-access permission to the Partition containing this HBA. * Task permission to the "Partition Details" task. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Delete", "this", "NIC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_nic.py#L270-L288
15,087
zhmcclient/python-zhmcclient
zhmcclient/_nic.py
Nic.update_properties
def update_properties(self, properties): """ Update writeable properties of this NIC. Authorization requirements: * Object-access permission to the Partition containing this NIC. * Object-access permission to the backing Adapter for this NIC. * Task permission to the "Partition Details" task. Parameters: properties (dict): New values for the properties to be updated. Properties not to be updated are omitted. Allowable properties are the properties with qualifier (w) in section 'Data model - NIC Element Object' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError` """ self.manager.session.post(self.uri, body=properties) is_rename = self.manager._name_prop in properties if is_rename: # Delete the old name from the cache self.manager._name_uri_cache.delete(self.name) self.properties.update(copy.deepcopy(properties)) if is_rename: # Add the new name to the cache self.manager._name_uri_cache.update(self.name, self.uri)
python
def update_properties(self, properties): self.manager.session.post(self.uri, body=properties) is_rename = self.manager._name_prop in properties if is_rename: # Delete the old name from the cache self.manager._name_uri_cache.delete(self.name) self.properties.update(copy.deepcopy(properties)) if is_rename: # Add the new name to the cache self.manager._name_uri_cache.update(self.name, self.uri)
[ "def", "update_properties", "(", "self", ",", "properties", ")", ":", "self", ".", "manager", ".", "session", ".", "post", "(", "self", ".", "uri", ",", "body", "=", "properties", ")", "is_rename", "=", "self", ".", "manager", ".", "_name_prop", "in", ...
Update writeable properties of this NIC. Authorization requirements: * Object-access permission to the Partition containing this NIC. * Object-access permission to the backing Adapter for this NIC. * Task permission to the "Partition Details" task. Parameters: properties (dict): New values for the properties to be updated. Properties not to be updated are omitted. Allowable properties are the properties with qualifier (w) in section 'Data model - NIC Element Object' in the :term:`HMC API` book. Raises: :exc:`~zhmcclient.HTTPError` :exc:`~zhmcclient.ParseError` :exc:`~zhmcclient.AuthError` :exc:`~zhmcclient.ConnectionError`
[ "Update", "writeable", "properties", "of", "this", "NIC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_nic.py#L291-L324
15,088
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
_NameUriCache.get
def get(self, name): """ Get the resource URI for a specified resource name. If an entry for the specified resource name does not exist in the Name-URI cache, the cache is refreshed from the HMC with all resources of the manager holding this cache. If an entry for the specified resource name still does not exist after that, ``NotFound`` is raised. """ self.auto_invalidate() try: return self._uris[name] except KeyError: self.refresh() try: return self._uris[name] except KeyError: raise NotFound({self._manager._name_prop: name}, self._manager)
python
def get(self, name): self.auto_invalidate() try: return self._uris[name] except KeyError: self.refresh() try: return self._uris[name] except KeyError: raise NotFound({self._manager._name_prop: name}, self._manager)
[ "def", "get", "(", "self", ",", "name", ")", ":", "self", ".", "auto_invalidate", "(", ")", "try", ":", "return", "self", ".", "_uris", "[", "name", "]", "except", "KeyError", ":", "self", ".", "refresh", "(", ")", "try", ":", "return", "self", "."...
Get the resource URI for a specified resource name. If an entry for the specified resource name does not exist in the Name-URI cache, the cache is refreshed from the HMC with all resources of the manager holding this cache. If an entry for the specified resource name still does not exist after that, ``NotFound`` is raised.
[ "Get", "the", "resource", "URI", "for", "a", "specified", "resource", "name", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L75-L94
15,089
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
_NameUriCache.auto_invalidate
def auto_invalidate(self): """ Invalidate the cache if the current time is past the time to live. """ current = datetime.now() if current > self._invalidated + timedelta(seconds=self._timetolive): self.invalidate()
python
def auto_invalidate(self): current = datetime.now() if current > self._invalidated + timedelta(seconds=self._timetolive): self.invalidate()
[ "def", "auto_invalidate", "(", "self", ")", ":", "current", "=", "datetime", ".", "now", "(", ")", "if", "current", ">", "self", ".", "_invalidated", "+", "timedelta", "(", "seconds", "=", "self", ".", "_timetolive", ")", ":", "self", ".", "invalidate", ...
Invalidate the cache if the current time is past the time to live.
[ "Invalidate", "the", "cache", "if", "the", "current", "time", "is", "past", "the", "time", "to", "live", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L96-L102
15,090
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
_NameUriCache.refresh
def refresh(self): """ Refresh the Name-URI cache from the HMC. This is done by invalidating the cache, listing the resources of this manager from the HMC, and populating the cache with that information. """ self.invalidate() full = not self._manager._list_has_name res_list = self._manager.list(full_properties=full) self.update_from(res_list)
python
def refresh(self): self.invalidate() full = not self._manager._list_has_name res_list = self._manager.list(full_properties=full) self.update_from(res_list)
[ "def", "refresh", "(", "self", ")", ":", "self", ".", "invalidate", "(", ")", "full", "=", "not", "self", ".", "_manager", ".", "_list_has_name", "res_list", "=", "self", ".", "_manager", ".", "list", "(", "full_properties", "=", "full", ")", "self", "...
Refresh the Name-URI cache from the HMC. This is done by invalidating the cache, listing the resources of this manager from the HMC, and populating the cache with that information.
[ "Refresh", "the", "Name", "-", "URI", "cache", "from", "the", "HMC", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L114-L124
15,091
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
_NameUriCache.update_from
def update_from(self, res_list): """ Update the Name-URI cache from the provided resource list. This is done by going through the resource list and updating any cache entries for non-empty resource names in that list. Other cache entries remain unchanged. """ for res in res_list: # We access the properties dictionary, in order to make sure # we don't drive additional HMC interactions. name = res.properties.get(self._manager._name_prop, None) uri = res.properties.get(self._manager._uri_prop, None) self.update(name, uri)
python
def update_from(self, res_list): for res in res_list: # We access the properties dictionary, in order to make sure # we don't drive additional HMC interactions. name = res.properties.get(self._manager._name_prop, None) uri = res.properties.get(self._manager._uri_prop, None) self.update(name, uri)
[ "def", "update_from", "(", "self", ",", "res_list", ")", ":", "for", "res", "in", "res_list", ":", "# We access the properties dictionary, in order to make sure", "# we don't drive additional HMC interactions.", "name", "=", "res", ".", "properties", ".", "get", "(", "s...
Update the Name-URI cache from the provided resource list. This is done by going through the resource list and updating any cache entries for non-empty resource names in that list. Other cache entries remain unchanged.
[ "Update", "the", "Name", "-", "URI", "cache", "from", "the", "provided", "resource", "list", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L126-L139
15,092
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
BaseManager._divide_filter_args
def _divide_filter_args(self, filter_args): """ Divide the filter arguments into filter query parameters for filtering on the server side, and the remaining client-side filters. Parameters: filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : tuple (query_parms_str, client_filter_args) """ query_parms = [] # query parameter strings client_filter_args = {} if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if prop_name in self._query_props: self._append_query_parms(query_parms, prop_name, prop_match) else: client_filter_args[prop_name] = prop_match query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?{}'.format(query_parms_str) return query_parms_str, client_filter_args
python
def _divide_filter_args(self, filter_args): query_parms = [] # query parameter strings client_filter_args = {} if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if prop_name in self._query_props: self._append_query_parms(query_parms, prop_name, prop_match) else: client_filter_args[prop_name] = prop_match query_parms_str = '&'.join(query_parms) if query_parms_str: query_parms_str = '?{}'.format(query_parms_str) return query_parms_str, client_filter_args
[ "def", "_divide_filter_args", "(", "self", ",", "filter_args", ")", ":", "query_parms", "=", "[", "]", "# query parameter strings", "client_filter_args", "=", "{", "}", "if", "filter_args", "is", "not", "None", ":", "for", "prop_name", "in", "filter_args", ":", ...
Divide the filter arguments into filter query parameters for filtering on the server side, and the remaining client-side filters. Parameters: filter_args (dict): Filter arguments that narrow the list of returned resources to those that match the specified filter arguments. For details, see :ref:`Filtering`. `None` causes no filtering to happen, i.e. all resources are returned. Returns: : tuple (query_parms_str, client_filter_args)
[ "Divide", "the", "filter", "arguments", "into", "filter", "query", "parameters", "for", "filtering", "on", "the", "server", "side", "and", "the", "remaining", "client", "-", "side", "filters", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L380-L414
15,093
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
BaseManager._matches_filters
def _matches_filters(self, obj, filter_args): """ Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. `None` causes the resource to always match. Returns: bool: Boolean indicating whether the resource object matches the filter arguments. """ if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if not self._matches_prop(obj, prop_name, prop_match): return False return True
python
def _matches_filters(self, obj, filter_args): if filter_args is not None: for prop_name in filter_args: prop_match = filter_args[prop_name] if not self._matches_prop(obj, prop_name, prop_match): return False return True
[ "def", "_matches_filters", "(", "self", ",", "obj", ",", "filter_args", ")", ":", "if", "filter_args", "is", "not", "None", ":", "for", "prop_name", "in", "filter_args", ":", "prop_match", "=", "filter_args", "[", "prop_name", "]", "if", "not", "self", "."...
Return a boolean indicating whether a resource object matches a set of filter arguments. This is used for client-side filtering. Depending on the properties specified in the filter arguments, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. filter_args (dict): Filter arguments. For details, see :ref:`Filtering`. `None` causes the resource to always match. Returns: bool: Boolean indicating whether the resource object matches the filter arguments.
[ "Return", "a", "boolean", "indicating", "whether", "a", "resource", "object", "matches", "a", "set", "of", "filter", "arguments", ".", "This", "is", "used", "for", "client", "-", "side", "filtering", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L427-L455
15,094
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
BaseManager._matches_prop
def _matches_prop(self, obj, prop_name, prop_match): """ Return a boolean indicating whether a resource object matches with a single property against a property match value. This is used for client-side filtering. Depending on the specified property, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. prop_match: Property match value that is used to match the actual value of the specified property against, as follows: - If the match value is a list or tuple, this method is invoked recursively to find whether one or more match values inthe list match. - Else if the property is of string type, its value is matched by interpreting the match value as a regular expression. - Else the property value is matched by exact value comparison with the match value. Returns: bool: Boolean indicating whether the resource object matches w.r.t. the specified property and the match value. """ if isinstance(prop_match, (list, tuple)): # List items are logically ORed, so one matching item suffices. for pm in prop_match: if self._matches_prop(obj, prop_name, pm): return True else: # Some lists of resources do not have all properties, for example # Hipersocket adapters do not have a "card-location" property. # If a filter property does not exist on a resource, the resource # does not match. try: prop_value = obj.get_property(prop_name) except KeyError: return False if isinstance(prop_value, six.string_types): # HMC resource property is Enum String or (non-enum) String, # and is both matched by regexp matching. Ideally, regexp # matching should only be done for non-enum strings, but # distinguishing them is not possible given that the client # has no knowledge about the properties. # The regexp matching implemented in the HMC requires begin and # end of the string value to match, even if the '^' for begin # and '$' for end are not specified in the pattern. The code # here is consistent with that: We add end matching to the # pattern, and begin matching is done by re.match() # automatically. re_match = prop_match + '$' m = re.match(re_match, prop_value) if m: return True else: if prop_value == prop_match: return True return False
python
def _matches_prop(self, obj, prop_name, prop_match): if isinstance(prop_match, (list, tuple)): # List items are logically ORed, so one matching item suffices. for pm in prop_match: if self._matches_prop(obj, prop_name, pm): return True else: # Some lists of resources do not have all properties, for example # Hipersocket adapters do not have a "card-location" property. # If a filter property does not exist on a resource, the resource # does not match. try: prop_value = obj.get_property(prop_name) except KeyError: return False if isinstance(prop_value, six.string_types): # HMC resource property is Enum String or (non-enum) String, # and is both matched by regexp matching. Ideally, regexp # matching should only be done for non-enum strings, but # distinguishing them is not possible given that the client # has no knowledge about the properties. # The regexp matching implemented in the HMC requires begin and # end of the string value to match, even if the '^' for begin # and '$' for end are not specified in the pattern. The code # here is consistent with that: We add end matching to the # pattern, and begin matching is done by re.match() # automatically. re_match = prop_match + '$' m = re.match(re_match, prop_value) if m: return True else: if prop_value == prop_match: return True return False
[ "def", "_matches_prop", "(", "self", ",", "obj", ",", "prop_name", ",", "prop_match", ")", ":", "if", "isinstance", "(", "prop_match", ",", "(", "list", ",", "tuple", ")", ")", ":", "# List items are logically ORed, so one matching item suffices.", "for", "pm", ...
Return a boolean indicating whether a resource object matches with a single property against a property match value. This is used for client-side filtering. Depending on the specified property, this method retrieves the resource properties from the HMC. Parameters: obj (BaseResource): Resource object. prop_match: Property match value that is used to match the actual value of the specified property against, as follows: - If the match value is a list or tuple, this method is invoked recursively to find whether one or more match values inthe list match. - Else if the property is of string type, its value is matched by interpreting the match value as a regular expression. - Else the property value is matched by exact value comparison with the match value. Returns: bool: Boolean indicating whether the resource object matches w.r.t. the specified property and the match value.
[ "Return", "a", "boolean", "indicating", "whether", "a", "resource", "object", "matches", "with", "a", "single", "property", "against", "a", "property", "match", "value", ".", "This", "is", "used", "for", "client", "-", "side", "filtering", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L457-L524
15,095
zhmcclient/python-zhmcclient
zhmcclient/_manager.py
BaseManager.resource_object
def resource_object(self, uri_or_oid, props=None): """ Return a minimalistic Python resource object for this resource class, that is scoped to this manager. This method is an internal helper function and is not normally called by users. The returned resource object will have the following minimal set of properties set automatically: * `object-uri` * `object-id` * `parent` * `class` Additional properties for the Python resource object can be specified by the caller. Parameters: uri_or_oid (string): `object-uri` or `object-id` of the resource. props (dict): Property values in addition to the minimal list of properties that are set automatically (see above). Returns: Subclass of :class:`~zhmcclient.BaseResource`: A Python resource object for this resource class. """ if uri_or_oid.startswith('/api/'): assert uri_or_oid[-1] != '/' uri = uri_or_oid oid = uri.split('/')[-1] else: assert '/' not in uri_or_oid oid = uri_or_oid uri = '{}/{}'.format(self._base_uri, oid) res_props = { self._oid_prop: oid, 'parent': self.parent.uri if self.parent is not None else None, 'class': self.class_name, } name = None if props: res_props.update(props) try: name = props[self._name_prop] except KeyError: pass return self.resource_class(self, uri, name, res_props)
python
def resource_object(self, uri_or_oid, props=None): if uri_or_oid.startswith('/api/'): assert uri_or_oid[-1] != '/' uri = uri_or_oid oid = uri.split('/')[-1] else: assert '/' not in uri_or_oid oid = uri_or_oid uri = '{}/{}'.format(self._base_uri, oid) res_props = { self._oid_prop: oid, 'parent': self.parent.uri if self.parent is not None else None, 'class': self.class_name, } name = None if props: res_props.update(props) try: name = props[self._name_prop] except KeyError: pass return self.resource_class(self, uri, name, res_props)
[ "def", "resource_object", "(", "self", ",", "uri_or_oid", ",", "props", "=", "None", ")", ":", "if", "uri_or_oid", ".", "startswith", "(", "'/api/'", ")", ":", "assert", "uri_or_oid", "[", "-", "1", "]", "!=", "'/'", "uri", "=", "uri_or_oid", "oid", "=...
Return a minimalistic Python resource object for this resource class, that is scoped to this manager. This method is an internal helper function and is not normally called by users. The returned resource object will have the following minimal set of properties set automatically: * `object-uri` * `object-id` * `parent` * `class` Additional properties for the Python resource object can be specified by the caller. Parameters: uri_or_oid (string): `object-uri` or `object-id` of the resource. props (dict): Property values in addition to the minimal list of properties that are set automatically (see above). Returns: Subclass of :class:`~zhmcclient.BaseResource`: A Python resource object for this resource class.
[ "Return", "a", "minimalistic", "Python", "resource", "object", "for", "this", "resource", "class", "that", "is", "scoped", "to", "this", "manager", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient/_manager.py#L562-L613
15,096
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedBaseResource.add_resources
def add_resources(self, resources): """ Add faked child resources to this resource, from the provided resource definitions. Duplicate resource names in the same scope are not permitted. Although this method is typically used to initially load the faked HMC with resource state just once, it can be invoked multiple times and can also be invoked on faked resources (e.g. on a faked CPC). Parameters: resources (dict): resource dictionary with definitions of faked child resources to be added. For an explanation of how the resource dictionary is set up, see the examples below. For requirements on and auto-generation of certain resource properties, see the ``add()`` methods of the various faked resource managers (e.g. :meth:`zhmcclient_mock.FakedCpcManager.add`). For example, the object-id or element-id properties and the corresponding uri properties are always auto-generated. The resource dictionary specifies a tree of resource managers and resources, in an alternating manner. It starts with the resource managers of child resources of the target resource, which contains a list of those child resources. For an HMC, the CPCs managed by the HMC would be its child resources. Each resource specifies its own properties (``properties`` key) and the resource managers for its child resources. For example, the CPC resource specifies its adapter child resources using the ``adapters`` key. The keys for the child resource managers are the attribute names of these resource managers in the parent resource. For example, the ``adapters`` key is named after the :attr:`zhmcclient.Cpc.adapters` attribute (which has the same name as in its corresponding faked CPC resource: :attr:`zhmcclient_mock.FakedCpc.adapters`). Raises: :exc:`zhmcclient_mock.InputError`: Some issue with the input resources. Examples: Example for targeting a faked HMC for adding a CPC with one adapter:: resources = { 'cpcs': [ # name of manager attribute for this resource { 'properties': { 'name': 'cpc_1', }, 'adapters': [ # name of manager attribute for this # resource { 'properties': { 'object-id': '12', 'name': 'ad_1', }, 'ports': [ { 'properties': { 'name': 'port_1', } }, ], }, ], }, ], } Example for targeting a faked CPC for adding an LPAR and a load activation profile:: resources = { 'lpars': [ # name of manager attribute for this resource { 'properties': { # object-id is not provided -> auto-generated # object-uri is not provided -> auto-generated 'name': 'lpar_1', }, }, ], 'load_activation_profiles': [ # name of manager attribute { 'properties': { # object-id is not provided -> auto-generated # object-uri is not provided -> auto-generated 'name': 'lpar_1', }, }, ], } """ for child_attr in resources: child_list = resources[child_attr] self._process_child_list(self, child_attr, child_list)
python
def add_resources(self, resources): for child_attr in resources: child_list = resources[child_attr] self._process_child_list(self, child_attr, child_list)
[ "def", "add_resources", "(", "self", ",", "resources", ")", ":", "for", "child_attr", "in", "resources", ":", "child_list", "=", "resources", "[", "child_attr", "]", "self", ".", "_process_child_list", "(", "self", ",", "child_attr", ",", "child_list", ")" ]
Add faked child resources to this resource, from the provided resource definitions. Duplicate resource names in the same scope are not permitted. Although this method is typically used to initially load the faked HMC with resource state just once, it can be invoked multiple times and can also be invoked on faked resources (e.g. on a faked CPC). Parameters: resources (dict): resource dictionary with definitions of faked child resources to be added. For an explanation of how the resource dictionary is set up, see the examples below. For requirements on and auto-generation of certain resource properties, see the ``add()`` methods of the various faked resource managers (e.g. :meth:`zhmcclient_mock.FakedCpcManager.add`). For example, the object-id or element-id properties and the corresponding uri properties are always auto-generated. The resource dictionary specifies a tree of resource managers and resources, in an alternating manner. It starts with the resource managers of child resources of the target resource, which contains a list of those child resources. For an HMC, the CPCs managed by the HMC would be its child resources. Each resource specifies its own properties (``properties`` key) and the resource managers for its child resources. For example, the CPC resource specifies its adapter child resources using the ``adapters`` key. The keys for the child resource managers are the attribute names of these resource managers in the parent resource. For example, the ``adapters`` key is named after the :attr:`zhmcclient.Cpc.adapters` attribute (which has the same name as in its corresponding faked CPC resource: :attr:`zhmcclient_mock.FakedCpc.adapters`). Raises: :exc:`zhmcclient_mock.InputError`: Some issue with the input resources. Examples: Example for targeting a faked HMC for adding a CPC with one adapter:: resources = { 'cpcs': [ # name of manager attribute for this resource { 'properties': { 'name': 'cpc_1', }, 'adapters': [ # name of manager attribute for this # resource { 'properties': { 'object-id': '12', 'name': 'ad_1', }, 'ports': [ { 'properties': { 'name': 'port_1', } }, ], }, ], }, ], } Example for targeting a faked CPC for adding an LPAR and a load activation profile:: resources = { 'lpars': [ # name of manager attribute for this resource { 'properties': { # object-id is not provided -> auto-generated # object-uri is not provided -> auto-generated 'name': 'lpar_1', }, }, ], 'load_activation_profiles': [ # name of manager attribute { 'properties': { # object-id is not provided -> auto-generated # object-uri is not provided -> auto-generated 'name': 'lpar_1', }, }, ], }
[ "Add", "faked", "child", "resources", "to", "this", "resource", "from", "the", "provided", "resource", "definitions", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L192-L294
15,097
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedBaseManager.add
def add(self, properties): """ Add a faked resource to this manager. For URI-based lookup, the resource is also added to the faked HMC. Parameters: properties (dict): Resource properties. If the URI property (e.g. 'object-uri') or the object ID property (e.g. 'object-id') are not specified, they will be auto-generated. Returns: FakedBaseResource: The faked resource object. """ resource = self.resource_class(self, properties) self._resources[resource.oid] = resource self._hmc.all_resources[resource.uri] = resource return resource
python
def add(self, properties): resource = self.resource_class(self, properties) self._resources[resource.oid] = resource self._hmc.all_resources[resource.uri] = resource return resource
[ "def", "add", "(", "self", ",", "properties", ")", ":", "resource", "=", "self", ".", "resource_class", "(", "self", ",", "properties", ")", "self", ".", "_resources", "[", "resource", ".", "oid", "]", "=", "resource", "self", ".", "_hmc", ".", "all_re...
Add a faked resource to this manager. For URI-based lookup, the resource is also added to the faked HMC. Parameters: properties (dict): Resource properties. If the URI property (e.g. 'object-uri') or the object ID property (e.g. 'object-id') are not specified, they will be auto-generated. Returns: FakedBaseResource: The faked resource object.
[ "Add", "a", "faked", "resource", "to", "this", "manager", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L521-L540
15,098
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedBaseManager.remove
def remove(self, oid): """ Remove a faked resource from this manager. Parameters: oid (string): The object ID of the resource (e.g. value of the 'object-uri' property). """ uri = self._resources[oid].uri del self._resources[oid] del self._hmc.all_resources[uri]
python
def remove(self, oid): uri = self._resources[oid].uri del self._resources[oid] del self._hmc.all_resources[uri]
[ "def", "remove", "(", "self", ",", "oid", ")", ":", "uri", "=", "self", ".", "_resources", "[", "oid", "]", ".", "uri", "del", "self", ".", "_resources", "[", "oid", "]", "del", "self", ".", "_hmc", ".", "all_resources", "[", "uri", "]" ]
Remove a faked resource from this manager. Parameters: oid (string): The object ID of the resource (e.g. value of the 'object-uri' property).
[ "Remove", "a", "faked", "resource", "from", "this", "manager", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L542-L554
15,099
zhmcclient/python-zhmcclient
zhmcclient_mock/_hmc.py
FakedBaseManager.list
def list(self, filter_args=None): """ List the faked resources of this manager. Parameters: filter_args (dict): Filter arguments. `None` causes no filtering to happen. See :meth:`~zhmcclient.BaseManager.list()` for details. Returns: list of FakedBaseResource: The faked resource objects of this manager. """ res = list() for oid in self._resources: resource = self._resources[oid] if self._matches_filters(resource, filter_args): res.append(resource) return res
python
def list(self, filter_args=None): res = list() for oid in self._resources: resource = self._resources[oid] if self._matches_filters(resource, filter_args): res.append(resource) return res
[ "def", "list", "(", "self", ",", "filter_args", "=", "None", ")", ":", "res", "=", "list", "(", ")", "for", "oid", "in", "self", ".", "_resources", ":", "resource", "=", "self", ".", "_resources", "[", "oid", "]", "if", "self", ".", "_matches_filters...
List the faked resources of this manager. Parameters: filter_args (dict): Filter arguments. `None` causes no filtering to happen. See :meth:`~zhmcclient.BaseManager.list()` for details. Returns: list of FakedBaseResource: The faked resource objects of this manager.
[ "List", "the", "faked", "resources", "of", "this", "manager", "." ]
9657563e5d9184c51d3c903442a58b9725fdf335
https://github.com/zhmcclient/python-zhmcclient/blob/9657563e5d9184c51d3c903442a58b9725fdf335/zhmcclient_mock/_hmc.py#L556-L575