repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
napalm-automation/napalm-logs
napalm_logs/device.py
NapalmLogsDeviceProc._publish
def _publish(self, obj): ''' Publish the OC object. ''' bin_obj = umsgpack.packb(obj) self.pub.send(bin_obj)
python
def _publish(self, obj): ''' Publish the OC object. ''' bin_obj = umsgpack.packb(obj) self.pub.send(bin_obj)
[ "def", "_publish", "(", "self", ",", "obj", ")", ":", "bin_obj", "=", "umsgpack", ".", "packb", "(", "obj", ")", "self", ".", "pub", ".", "send", "(", "bin_obj", ")" ]
Publish the OC object.
[ "Publish", "the", "OC", "object", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/device.py#L202-L207
train
233,500
napalm-automation/napalm-logs
napalm_logs/auth.py
NapalmLogsAuthProc._handshake
def _handshake(self, conn, addr): ''' Ensures that the client receives the AES key. ''' # waiting for the magic request message msg = conn.recv(len(MAGIC_REQ)) log.debug('Received message %s from %s', msg, addr) if msg != MAGIC_REQ: log.warning('%s is not a valid REQ message from %s', msg, addr) return log.debug('Sending the private key') conn.send(self.__key) # wait for explicit ACK log.debug('Waiting for the client to confirm') msg = conn.recv(len(MAGIC_ACK)) if msg != MAGIC_ACK: return log.debug('Sending the signature key') conn.send(self.__sgn) # wait for explicit ACK log.debug('Waiting for the client to confirm') msg = conn.recv(len(MAGIC_ACK)) if msg != MAGIC_ACK: return log.info('%s is now authenticated', addr) self.keep_alive(conn)
python
def _handshake(self, conn, addr): ''' Ensures that the client receives the AES key. ''' # waiting for the magic request message msg = conn.recv(len(MAGIC_REQ)) log.debug('Received message %s from %s', msg, addr) if msg != MAGIC_REQ: log.warning('%s is not a valid REQ message from %s', msg, addr) return log.debug('Sending the private key') conn.send(self.__key) # wait for explicit ACK log.debug('Waiting for the client to confirm') msg = conn.recv(len(MAGIC_ACK)) if msg != MAGIC_ACK: return log.debug('Sending the signature key') conn.send(self.__sgn) # wait for explicit ACK log.debug('Waiting for the client to confirm') msg = conn.recv(len(MAGIC_ACK)) if msg != MAGIC_ACK: return log.info('%s is now authenticated', addr) self.keep_alive(conn)
[ "def", "_handshake", "(", "self", ",", "conn", ",", "addr", ")", ":", "# waiting for the magic request message", "msg", "=", "conn", ".", "recv", "(", "len", "(", "MAGIC_REQ", ")", ")", "log", ".", "debug", "(", "'Received message %s from %s'", ",", "msg", ",", "addr", ")", "if", "msg", "!=", "MAGIC_REQ", ":", "log", ".", "warning", "(", "'%s is not a valid REQ message from %s'", ",", "msg", ",", "addr", ")", "return", "log", ".", "debug", "(", "'Sending the private key'", ")", "conn", ".", "send", "(", "self", ".", "__key", ")", "# wait for explicit ACK", "log", ".", "debug", "(", "'Waiting for the client to confirm'", ")", "msg", "=", "conn", ".", "recv", "(", "len", "(", "MAGIC_ACK", ")", ")", "if", "msg", "!=", "MAGIC_ACK", ":", "return", "log", ".", "debug", "(", "'Sending the signature key'", ")", "conn", ".", "send", "(", "self", ".", "__sgn", ")", "# wait for explicit ACK", "log", ".", "debug", "(", "'Waiting for the client to confirm'", ")", "msg", "=", "conn", ".", "recv", "(", "len", "(", "MAGIC_ACK", ")", ")", "if", "msg", "!=", "MAGIC_ACK", ":", "return", "log", ".", "info", "(", "'%s is now authenticated'", ",", "addr", ")", "self", ".", "keep_alive", "(", "conn", ")" ]
Ensures that the client receives the AES key.
[ "Ensures", "that", "the", "client", "receives", "the", "AES", "key", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/auth.py#L79-L104
train
233,501
napalm-automation/napalm-logs
napalm_logs/auth.py
NapalmLogsAuthProc.keep_alive
def keep_alive(self, conn): ''' Maintains auth sessions ''' while self.__up: msg = conn.recv(len(AUTH_KEEP_ALIVE)) if msg != AUTH_KEEP_ALIVE: log.error('Received something other than %s', AUTH_KEEP_ALIVE) conn.close() return try: conn.send(AUTH_KEEP_ALIVE_ACK) except (IOError, socket.error) as err: log.error('Unable to send auth keep alive: %s', err) conn.close() return
python
def keep_alive(self, conn): ''' Maintains auth sessions ''' while self.__up: msg = conn.recv(len(AUTH_KEEP_ALIVE)) if msg != AUTH_KEEP_ALIVE: log.error('Received something other than %s', AUTH_KEEP_ALIVE) conn.close() return try: conn.send(AUTH_KEEP_ALIVE_ACK) except (IOError, socket.error) as err: log.error('Unable to send auth keep alive: %s', err) conn.close() return
[ "def", "keep_alive", "(", "self", ",", "conn", ")", ":", "while", "self", ".", "__up", ":", "msg", "=", "conn", ".", "recv", "(", "len", "(", "AUTH_KEEP_ALIVE", ")", ")", "if", "msg", "!=", "AUTH_KEEP_ALIVE", ":", "log", ".", "error", "(", "'Received something other than %s'", ",", "AUTH_KEEP_ALIVE", ")", "conn", ".", "close", "(", ")", "return", "try", ":", "conn", ".", "send", "(", "AUTH_KEEP_ALIVE_ACK", ")", "except", "(", "IOError", ",", "socket", ".", "error", ")", "as", "err", ":", "log", ".", "error", "(", "'Unable to send auth keep alive: %s'", ",", "err", ")", "conn", ".", "close", "(", ")", "return" ]
Maintains auth sessions
[ "Maintains", "auth", "sessions" ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/auth.py#L106-L121
train
233,502
napalm-automation/napalm-logs
napalm_logs/auth.py
NapalmLogsAuthProc.verify_cert
def verify_cert(self): ''' Checks that the provided cert and key are valid and usable ''' log.debug('Verifying the %s certificate, keyfile: %s', self.certificate, self.keyfile) try: ssl.create_default_context().load_cert_chain(self.certificate, keyfile=self.keyfile) except ssl.SSLError: error_string = 'SSL certificate and key do not match' log.error(error_string) raise SSLMismatchException(error_string) except IOError: log.error('Unable to open either certificate or key file') raise log.debug('Certificate looks good.')
python
def verify_cert(self): ''' Checks that the provided cert and key are valid and usable ''' log.debug('Verifying the %s certificate, keyfile: %s', self.certificate, self.keyfile) try: ssl.create_default_context().load_cert_chain(self.certificate, keyfile=self.keyfile) except ssl.SSLError: error_string = 'SSL certificate and key do not match' log.error(error_string) raise SSLMismatchException(error_string) except IOError: log.error('Unable to open either certificate or key file') raise log.debug('Certificate looks good.')
[ "def", "verify_cert", "(", "self", ")", ":", "log", ".", "debug", "(", "'Verifying the %s certificate, keyfile: %s'", ",", "self", ".", "certificate", ",", "self", ".", "keyfile", ")", "try", ":", "ssl", ".", "create_default_context", "(", ")", ".", "load_cert_chain", "(", "self", ".", "certificate", ",", "keyfile", "=", "self", ".", "keyfile", ")", "except", "ssl", ".", "SSLError", ":", "error_string", "=", "'SSL certificate and key do not match'", "log", ".", "error", "(", "error_string", ")", "raise", "SSLMismatchException", "(", "error_string", ")", "except", "IOError", ":", "log", ".", "error", "(", "'Unable to open either certificate or key file'", ")", "raise", "log", ".", "debug", "(", "'Certificate looks good.'", ")" ]
Checks that the provided cert and key are valid and usable
[ "Checks", "that", "the", "provided", "cert", "and", "key", "are", "valid", "and", "usable" ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/auth.py#L123-L138
train
233,503
napalm-automation/napalm-logs
napalm_logs/auth.py
NapalmLogsAuthProc._create_skt
def _create_skt(self): ''' Create the authentication socket. ''' log.debug('Creating the auth socket') if ':' in self.auth_address: self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.bind((self.auth_address, self.auth_port)) except socket.error as msg: error_string = 'Unable to bind (auth) to port {} on {}: {}'.format(self.auth_port, self.auth_address, msg) log.error(error_string, exc_info=True) raise BindException(error_string)
python
def _create_skt(self): ''' Create the authentication socket. ''' log.debug('Creating the auth socket') if ':' in self.auth_address: self.socket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.bind((self.auth_address, self.auth_port)) except socket.error as msg: error_string = 'Unable to bind (auth) to port {} on {}: {}'.format(self.auth_port, self.auth_address, msg) log.error(error_string, exc_info=True) raise BindException(error_string)
[ "def", "_create_skt", "(", "self", ")", ":", "log", ".", "debug", "(", "'Creating the auth socket'", ")", "if", "':'", "in", "self", ".", "auth_address", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET6", ",", "socket", ".", "SOCK_STREAM", ")", "else", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "try", ":", "self", ".", "socket", ".", "bind", "(", "(", "self", ".", "auth_address", ",", "self", ".", "auth_port", ")", ")", "except", "socket", ".", "error", "as", "msg", ":", "error_string", "=", "'Unable to bind (auth) to port {} on {}: {}'", ".", "format", "(", "self", ".", "auth_port", ",", "self", ".", "auth_address", ",", "msg", ")", "log", ".", "error", "(", "error_string", ",", "exc_info", "=", "True", ")", "raise", "BindException", "(", "error_string", ")" ]
Create the authentication socket.
[ "Create", "the", "authentication", "socket", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/auth.py#L140-L154
train
233,504
napalm-automation/napalm-logs
napalm_logs/auth.py
NapalmLogsAuthProc.start
def start(self): ''' Listen to auth requests and send the AES key. Each client connection starts a new thread. ''' # Start suicide polling thread log.debug('Starting the auth process') self.verify_cert() self._create_skt() log.debug('The auth process can receive at most %d parallel connections', AUTH_MAX_CONN) self.socket.listen(AUTH_MAX_CONN) thread = threading.Thread(target=self._suicide_when_without_parent, args=(os.getppid(),)) thread.start() signal.signal(signal.SIGTERM, self._exit_gracefully) self.__up = True while self.__up: try: (clientsocket, address) = self.socket.accept() wrapped_auth_skt = ssl.wrap_socket(clientsocket, server_side=True, certfile=self.certificate, keyfile=self.keyfile) except ssl.SSLError: log.exception('SSL error', exc_info=True) continue except socket.error as error: if self.__up is False: return else: msg = 'Received auth socket error: {}'.format(error) log.error(msg, exc_info=True) raise NapalmLogsExit(msg) log.info('%s connected', address) log.debug('Starting the handshake') client_thread = threading.Thread(target=self._handshake, args=(wrapped_auth_skt, address)) client_thread.start()
python
def start(self): ''' Listen to auth requests and send the AES key. Each client connection starts a new thread. ''' # Start suicide polling thread log.debug('Starting the auth process') self.verify_cert() self._create_skt() log.debug('The auth process can receive at most %d parallel connections', AUTH_MAX_CONN) self.socket.listen(AUTH_MAX_CONN) thread = threading.Thread(target=self._suicide_when_without_parent, args=(os.getppid(),)) thread.start() signal.signal(signal.SIGTERM, self._exit_gracefully) self.__up = True while self.__up: try: (clientsocket, address) = self.socket.accept() wrapped_auth_skt = ssl.wrap_socket(clientsocket, server_side=True, certfile=self.certificate, keyfile=self.keyfile) except ssl.SSLError: log.exception('SSL error', exc_info=True) continue except socket.error as error: if self.__up is False: return else: msg = 'Received auth socket error: {}'.format(error) log.error(msg, exc_info=True) raise NapalmLogsExit(msg) log.info('%s connected', address) log.debug('Starting the handshake') client_thread = threading.Thread(target=self._handshake, args=(wrapped_auth_skt, address)) client_thread.start()
[ "def", "start", "(", "self", ")", ":", "# Start suicide polling thread", "log", ".", "debug", "(", "'Starting the auth process'", ")", "self", ".", "verify_cert", "(", ")", "self", ".", "_create_skt", "(", ")", "log", ".", "debug", "(", "'The auth process can receive at most %d parallel connections'", ",", "AUTH_MAX_CONN", ")", "self", ".", "socket", ".", "listen", "(", "AUTH_MAX_CONN", ")", "thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_suicide_when_without_parent", ",", "args", "=", "(", "os", ".", "getppid", "(", ")", ",", ")", ")", "thread", ".", "start", "(", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "self", ".", "_exit_gracefully", ")", "self", ".", "__up", "=", "True", "while", "self", ".", "__up", ":", "try", ":", "(", "clientsocket", ",", "address", ")", "=", "self", ".", "socket", ".", "accept", "(", ")", "wrapped_auth_skt", "=", "ssl", ".", "wrap_socket", "(", "clientsocket", ",", "server_side", "=", "True", ",", "certfile", "=", "self", ".", "certificate", ",", "keyfile", "=", "self", ".", "keyfile", ")", "except", "ssl", ".", "SSLError", ":", "log", ".", "exception", "(", "'SSL error'", ",", "exc_info", "=", "True", ")", "continue", "except", "socket", ".", "error", "as", "error", ":", "if", "self", ".", "__up", "is", "False", ":", "return", "else", ":", "msg", "=", "'Received auth socket error: {}'", ".", "format", "(", "error", ")", "log", ".", "error", "(", "msg", ",", "exc_info", "=", "True", ")", "raise", "NapalmLogsExit", "(", "msg", ")", "log", ".", "info", "(", "'%s connected'", ",", "address", ")", "log", ".", "debug", "(", "'Starting the handshake'", ")", "client_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_handshake", ",", "args", "=", "(", "wrapped_auth_skt", ",", "address", ")", ")", "client_thread", ".", "start", "(", ")" ]
Listen to auth requests and send the AES key. Each client connection starts a new thread.
[ "Listen", "to", "auth", "requests", "and", "send", "the", "AES", "key", ".", "Each", "client", "connection", "starts", "a", "new", "thread", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/auth.py#L156-L192
train
233,505
napalm-automation/napalm-logs
napalm_logs/auth.py
NapalmLogsAuthProc.stop
def stop(self): ''' Stop the auth proc. ''' log.info('Stopping auth process') self.__up = False self.socket.close()
python
def stop(self): ''' Stop the auth proc. ''' log.info('Stopping auth process') self.__up = False self.socket.close()
[ "def", "stop", "(", "self", ")", ":", "log", ".", "info", "(", "'Stopping auth process'", ")", "self", ".", "__up", "=", "False", "self", ".", "socket", ".", "close", "(", ")" ]
Stop the auth proc.
[ "Stop", "the", "auth", "proc", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/auth.py#L194-L200
train
233,506
napalm-automation/napalm-logs
napalm_logs/listener/kafka.py
KafkaListener.start
def start(self): ''' Startup the kafka consumer. ''' log.debug('Creating the consumer using the bootstrap servers: %s and the group ID: %s', self.bootstrap_servers, self.group_id) try: self.consumer = kafka.KafkaConsumer(bootstrap_servers=self.bootstrap_servers, group_id=self.group_id) except kafka.errors.NoBrokersAvailable as err: log.error(err, exc_info=True) raise ListenerException(err) log.debug('Subscribing to the %s topic', self.topic) self.consumer.subscribe(topics=[self.topic])
python
def start(self): ''' Startup the kafka consumer. ''' log.debug('Creating the consumer using the bootstrap servers: %s and the group ID: %s', self.bootstrap_servers, self.group_id) try: self.consumer = kafka.KafkaConsumer(bootstrap_servers=self.bootstrap_servers, group_id=self.group_id) except kafka.errors.NoBrokersAvailable as err: log.error(err, exc_info=True) raise ListenerException(err) log.debug('Subscribing to the %s topic', self.topic) self.consumer.subscribe(topics=[self.topic])
[ "def", "start", "(", "self", ")", ":", "log", ".", "debug", "(", "'Creating the consumer using the bootstrap servers: %s and the group ID: %s'", ",", "self", ".", "bootstrap_servers", ",", "self", ".", "group_id", ")", "try", ":", "self", ".", "consumer", "=", "kafka", ".", "KafkaConsumer", "(", "bootstrap_servers", "=", "self", ".", "bootstrap_servers", ",", "group_id", "=", "self", ".", "group_id", ")", "except", "kafka", ".", "errors", ".", "NoBrokersAvailable", "as", "err", ":", "log", ".", "error", "(", "err", ",", "exc_info", "=", "True", ")", "raise", "ListenerException", "(", "err", ")", "log", ".", "debug", "(", "'Subscribing to the %s topic'", ",", "self", ".", "topic", ")", "self", ".", "consumer", ".", "subscribe", "(", "topics", "=", "[", "self", ".", "topic", "]", ")" ]
Startup the kafka consumer.
[ "Startup", "the", "kafka", "consumer", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/kafka.py#L41-L55
train
233,507
napalm-automation/napalm-logs
napalm_logs/listener/kafka.py
KafkaListener.stop
def stop(self): ''' Shutdown kafka consumer. ''' log.info('Stopping te kafka listener class') self.consumer.unsubscribe() self.consumer.close()
python
def stop(self): ''' Shutdown kafka consumer. ''' log.info('Stopping te kafka listener class') self.consumer.unsubscribe() self.consumer.close()
[ "def", "stop", "(", "self", ")", ":", "log", ".", "info", "(", "'Stopping te kafka listener class'", ")", "self", ".", "consumer", ".", "unsubscribe", "(", ")", "self", ".", "consumer", ".", "close", "(", ")" ]
Shutdown kafka consumer.
[ "Shutdown", "kafka", "consumer", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/kafka.py#L76-L82
train
233,508
napalm-automation/napalm-logs
napalm_logs/transport/__init__.py
get_transport
def get_transport(name): ''' Return the transport class. ''' try: log.debug('Using %s as transport', name) return TRANSPORT_LOOKUP[name] except KeyError: msg = 'Transport {} is not available. Are the dependencies installed?'.format(name) log.error(msg, exc_info=True) raise InvalidTransportException(msg)
python
def get_transport(name): ''' Return the transport class. ''' try: log.debug('Using %s as transport', name) return TRANSPORT_LOOKUP[name] except KeyError: msg = 'Transport {} is not available. Are the dependencies installed?'.format(name) log.error(msg, exc_info=True) raise InvalidTransportException(msg)
[ "def", "get_transport", "(", "name", ")", ":", "try", ":", "log", ".", "debug", "(", "'Using %s as transport'", ",", "name", ")", "return", "TRANSPORT_LOOKUP", "[", "name", "]", "except", "KeyError", ":", "msg", "=", "'Transport {} is not available. Are the dependencies installed?'", ".", "format", "(", "name", ")", "log", ".", "error", "(", "msg", ",", "exc_info", "=", "True", ")", "raise", "InvalidTransportException", "(", "msg", ")" ]
Return the transport class.
[ "Return", "the", "transport", "class", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/transport/__init__.py#L50-L60
train
233,509
napalm-automation/napalm-logs
napalm_logs/listener/zeromq.py
ZMQListener.start
def start(self): ''' Startup the zmq consumer. ''' zmq_uri = '{protocol}://{address}:{port}'.format( protocol=self.protocol, address=self.address, port=self.port ) if self.port else\ '{protocol}://{address}'.format( # noqa protocol=self.protocol, address=self.address ) log.debug('ZMQ URI: %s', zmq_uri) self.ctx = zmq.Context() if hasattr(zmq, self.type): skt_type = getattr(zmq, self.type) else: skt_type = zmq.PULL self.sub = self.ctx.socket(skt_type) self.sub.connect(zmq_uri) if self.hwm is not None: try: self.sub.setsockopt(zmq.HWM, self.hwm) except AttributeError: self.sub.setsockopt(zmq.RCVHWM, self.hwm) if self.recvtimeout is not None: log.debug('Setting RCVTIMEO to %d', self.recvtimeout) self.sub.setsockopt(zmq.RCVTIMEO, self.recvtimeout) if self.keepalive is not None: log.debug('Setting TCP_KEEPALIVE to %d', self.keepalive) self.sub.setsockopt(zmq.TCP_KEEPALIVE, self.keepalive) if self.keepalive_idle is not None: log.debug('Setting TCP_KEEPALIVE_IDLE to %d', self.keepalive_idle) self.sub.setsockopt(zmq.TCP_KEEPALIVE_IDLE, self.keepalive_idle) if self.keepalive_interval is not None: log.debug('Setting TCP_KEEPALIVE_INTVL to %d', self.keepalive_interval) self.sub.setsockopt(zmq.TCP_KEEPALIVE_INTVL, self.keepalive_interval)
python
def start(self): ''' Startup the zmq consumer. ''' zmq_uri = '{protocol}://{address}:{port}'.format( protocol=self.protocol, address=self.address, port=self.port ) if self.port else\ '{protocol}://{address}'.format( # noqa protocol=self.protocol, address=self.address ) log.debug('ZMQ URI: %s', zmq_uri) self.ctx = zmq.Context() if hasattr(zmq, self.type): skt_type = getattr(zmq, self.type) else: skt_type = zmq.PULL self.sub = self.ctx.socket(skt_type) self.sub.connect(zmq_uri) if self.hwm is not None: try: self.sub.setsockopt(zmq.HWM, self.hwm) except AttributeError: self.sub.setsockopt(zmq.RCVHWM, self.hwm) if self.recvtimeout is not None: log.debug('Setting RCVTIMEO to %d', self.recvtimeout) self.sub.setsockopt(zmq.RCVTIMEO, self.recvtimeout) if self.keepalive is not None: log.debug('Setting TCP_KEEPALIVE to %d', self.keepalive) self.sub.setsockopt(zmq.TCP_KEEPALIVE, self.keepalive) if self.keepalive_idle is not None: log.debug('Setting TCP_KEEPALIVE_IDLE to %d', self.keepalive_idle) self.sub.setsockopt(zmq.TCP_KEEPALIVE_IDLE, self.keepalive_idle) if self.keepalive_interval is not None: log.debug('Setting TCP_KEEPALIVE_INTVL to %d', self.keepalive_interval) self.sub.setsockopt(zmq.TCP_KEEPALIVE_INTVL, self.keepalive_interval)
[ "def", "start", "(", "self", ")", ":", "zmq_uri", "=", "'{protocol}://{address}:{port}'", ".", "format", "(", "protocol", "=", "self", ".", "protocol", ",", "address", "=", "self", ".", "address", ",", "port", "=", "self", ".", "port", ")", "if", "self", ".", "port", "else", "'{protocol}://{address}'", ".", "format", "(", "# noqa", "protocol", "=", "self", ".", "protocol", ",", "address", "=", "self", ".", "address", ")", "log", ".", "debug", "(", "'ZMQ URI: %s'", ",", "zmq_uri", ")", "self", ".", "ctx", "=", "zmq", ".", "Context", "(", ")", "if", "hasattr", "(", "zmq", ",", "self", ".", "type", ")", ":", "skt_type", "=", "getattr", "(", "zmq", ",", "self", ".", "type", ")", "else", ":", "skt_type", "=", "zmq", ".", "PULL", "self", ".", "sub", "=", "self", ".", "ctx", ".", "socket", "(", "skt_type", ")", "self", ".", "sub", ".", "connect", "(", "zmq_uri", ")", "if", "self", ".", "hwm", "is", "not", "None", ":", "try", ":", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "HWM", ",", "self", ".", "hwm", ")", "except", "AttributeError", ":", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "RCVHWM", ",", "self", ".", "hwm", ")", "if", "self", ".", "recvtimeout", "is", "not", "None", ":", "log", ".", "debug", "(", "'Setting RCVTIMEO to %d'", ",", "self", ".", "recvtimeout", ")", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "RCVTIMEO", ",", "self", ".", "recvtimeout", ")", "if", "self", ".", "keepalive", "is", "not", "None", ":", "log", ".", "debug", "(", "'Setting TCP_KEEPALIVE to %d'", ",", "self", ".", "keepalive", ")", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "TCP_KEEPALIVE", ",", "self", ".", "keepalive", ")", "if", "self", ".", "keepalive_idle", "is", "not", "None", ":", "log", ".", "debug", "(", "'Setting TCP_KEEPALIVE_IDLE to %d'", ",", "self", ".", "keepalive_idle", ")", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "TCP_KEEPALIVE_IDLE", ",", "self", ".", "keepalive_idle", ")", "if", "self", ".", "keepalive_interval", "is", "not", "None", ":", "log", ".", "debug", "(", "'Setting TCP_KEEPALIVE_INTVL to %d'", ",", "self", ".", "keepalive_interval", ")", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "TCP_KEEPALIVE_INTVL", ",", "self", ".", "keepalive_interval", ")" ]
Startup the zmq consumer.
[ "Startup", "the", "zmq", "consumer", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/zeromq.py#L45-L82
train
233,510
napalm-automation/napalm-logs
napalm_logs/listener/zeromq.py
ZMQListener.receive
def receive(self): ''' Return the message received. ..note:: In ZMQ we are unable to get the address where we got the message from. ''' try: msg = self.sub.recv() except zmq.Again as error: log.error('Unable to receive messages: %s', error, exc_info=True) raise ListenerException(error) log.debug('[%s] Received %s', time.time(), msg) return msg, ''
python
def receive(self): ''' Return the message received. ..note:: In ZMQ we are unable to get the address where we got the message from. ''' try: msg = self.sub.recv() except zmq.Again as error: log.error('Unable to receive messages: %s', error, exc_info=True) raise ListenerException(error) log.debug('[%s] Received %s', time.time(), msg) return msg, ''
[ "def", "receive", "(", "self", ")", ":", "try", ":", "msg", "=", "self", ".", "sub", ".", "recv", "(", ")", "except", "zmq", ".", "Again", "as", "error", ":", "log", ".", "error", "(", "'Unable to receive messages: %s'", ",", "error", ",", "exc_info", "=", "True", ")", "raise", "ListenerException", "(", "error", ")", "log", ".", "debug", "(", "'[%s] Received %s'", ",", "time", ".", "time", "(", ")", ",", "msg", ")", "return", "msg", ",", "''" ]
Return the message received. ..note:: In ZMQ we are unable to get the address where we got the message from.
[ "Return", "the", "message", "received", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/zeromq.py#L84-L97
train
233,511
napalm-automation/napalm-logs
napalm_logs/listener/zeromq.py
ZMQListener.stop
def stop(self): ''' Shutdown zmq listener. ''' log.info('Stopping the zmq listener class') self.sub.close() self.ctx.term()
python
def stop(self): ''' Shutdown zmq listener. ''' log.info('Stopping the zmq listener class') self.sub.close() self.ctx.term()
[ "def", "stop", "(", "self", ")", ":", "log", ".", "info", "(", "'Stopping the zmq listener class'", ")", "self", ".", "sub", ".", "close", "(", ")", "self", ".", "ctx", ".", "term", "(", ")" ]
Shutdown zmq listener.
[ "Shutdown", "zmq", "listener", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/zeromq.py#L99-L105
train
233,512
napalm-automation/napalm-logs
napalm_logs/listener/udp.py
UDPListener.start
def start(self): ''' Create the UDP listener socket. ''' if ':' in self.address: self.skt = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) else: self.skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self.reuse_port: self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'SO_REUSEPORT'): self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) else: log.error('SO_REUSEPORT not supported') try: self.skt.bind((self.address, int(self.port))) except socket.error as msg: error_string = 'Unable to bind to port {} on {}: {}'.format(self.port, self.address, msg) log.error(error_string, exc_info=True) raise BindException(error_string)
python
def start(self): ''' Create the UDP listener socket. ''' if ':' in self.address: self.skt = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) else: self.skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self.reuse_port: self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'SO_REUSEPORT'): self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) else: log.error('SO_REUSEPORT not supported') try: self.skt.bind((self.address, int(self.port))) except socket.error as msg: error_string = 'Unable to bind to port {} on {}: {}'.format(self.port, self.address, msg) log.error(error_string, exc_info=True) raise BindException(error_string)
[ "def", "start", "(", "self", ")", ":", "if", "':'", "in", "self", ".", "address", ":", "self", ".", "skt", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET6", ",", "socket", ".", "SOCK_DGRAM", ")", "else", ":", "self", ".", "skt", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_DGRAM", ")", "if", "self", ".", "reuse_port", ":", "self", ".", "skt", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "if", "hasattr", "(", "socket", ",", "'SO_REUSEPORT'", ")", ":", "self", ".", "skt", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEPORT", ",", "1", ")", "else", ":", "log", ".", "error", "(", "'SO_REUSEPORT not supported'", ")", "try", ":", "self", ".", "skt", ".", "bind", "(", "(", "self", ".", "address", ",", "int", "(", "self", ".", "port", ")", ")", ")", "except", "socket", ".", "error", "as", "msg", ":", "error_string", "=", "'Unable to bind to port {} on {}: {}'", ".", "format", "(", "self", ".", "port", ",", "self", ".", "address", ",", "msg", ")", "log", ".", "error", "(", "error_string", ",", "exc_info", "=", "True", ")", "raise", "BindException", "(", "error_string", ")" ]
Create the UDP listener socket.
[ "Create", "the", "UDP", "listener", "socket", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/udp.py#L43-L62
train
233,513
napalm-automation/napalm-logs
napalm_logs/proc.py
NapalmLogsProc._suicide_when_without_parent
def _suicide_when_without_parent(self, parent_pid): ''' Kill this process when the parent died. ''' while True: time.sleep(5) try: # Check pid alive os.kill(parent_pid, 0) except OSError: # Forcibly exit # Regular sys.exit raises an exception self.stop() log.warning('The parent is not alive, exiting.') os._exit(999)
python
def _suicide_when_without_parent(self, parent_pid): ''' Kill this process when the parent died. ''' while True: time.sleep(5) try: # Check pid alive os.kill(parent_pid, 0) except OSError: # Forcibly exit # Regular sys.exit raises an exception self.stop() log.warning('The parent is not alive, exiting.') os._exit(999)
[ "def", "_suicide_when_without_parent", "(", "self", ",", "parent_pid", ")", ":", "while", "True", ":", "time", ".", "sleep", "(", "5", ")", "try", ":", "# Check pid alive", "os", ".", "kill", "(", "parent_pid", ",", "0", ")", "except", "OSError", ":", "# Forcibly exit", "# Regular sys.exit raises an exception", "self", ".", "stop", "(", ")", "log", ".", "warning", "(", "'The parent is not alive, exiting.'", ")", "os", ".", "_exit", "(", "999", ")" ]
Kill this process when the parent died.
[ "Kill", "this", "process", "when", "the", "parent", "died", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/proc.py#L20-L34
train
233,514
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._setup_buffer
def _setup_buffer(self): ''' Setup the buffer subsystem. ''' if not self._buffer_cfg or not isinstance(self._buffer_cfg, dict): return buffer_name = list(self._buffer_cfg.keys())[0] buffer_class = napalm_logs.buffer.get_interface(buffer_name) log.debug('Setting up buffer interface "%s"', buffer_name) if 'expire_time' not in self._buffer_cfg[buffer_name]: self._buffer_cfg[buffer_name]['expire_time'] = CONFIG.BUFFER_EXPIRE_TIME self._buffer = buffer_class(**self._buffer_cfg[buffer_name])
python
def _setup_buffer(self): ''' Setup the buffer subsystem. ''' if not self._buffer_cfg or not isinstance(self._buffer_cfg, dict): return buffer_name = list(self._buffer_cfg.keys())[0] buffer_class = napalm_logs.buffer.get_interface(buffer_name) log.debug('Setting up buffer interface "%s"', buffer_name) if 'expire_time' not in self._buffer_cfg[buffer_name]: self._buffer_cfg[buffer_name]['expire_time'] = CONFIG.BUFFER_EXPIRE_TIME self._buffer = buffer_class(**self._buffer_cfg[buffer_name])
[ "def", "_setup_buffer", "(", "self", ")", ":", "if", "not", "self", ".", "_buffer_cfg", "or", "not", "isinstance", "(", "self", ".", "_buffer_cfg", ",", "dict", ")", ":", "return", "buffer_name", "=", "list", "(", "self", ".", "_buffer_cfg", ".", "keys", "(", ")", ")", "[", "0", "]", "buffer_class", "=", "napalm_logs", ".", "buffer", ".", "get_interface", "(", "buffer_name", ")", "log", ".", "debug", "(", "'Setting up buffer interface \"%s\"'", ",", "buffer_name", ")", "if", "'expire_time'", "not", "in", "self", ".", "_buffer_cfg", "[", "buffer_name", "]", ":", "self", ".", "_buffer_cfg", "[", "buffer_name", "]", "[", "'expire_time'", "]", "=", "CONFIG", ".", "BUFFER_EXPIRE_TIME", "self", ".", "_buffer", "=", "buffer_class", "(", "*", "*", "self", ".", "_buffer_cfg", "[", "buffer_name", "]", ")" ]
Setup the buffer subsystem.
[ "Setup", "the", "buffer", "subsystem", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L134-L145
train
233,515
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._setup_metrics
def _setup_metrics(self): """ Start metric exposition """ path = os.environ.get("prometheus_multiproc_dir") if not os.path.exists(self.metrics_dir): try: log.info("Creating metrics directory") os.makedirs(self.metrics_dir) except OSError: log.error("Failed to create metrics directory!") raise ConfigurationException("Failed to create metrics directory!") path = self.metrics_dir elif path != self.metrics_dir: path = self.metrics_dir os.environ['prometheus_multiproc_dir'] = path log.info("Cleaning metrics collection directory") log.debug("Metrics directory set to: {}".format(path)) files = os.listdir(path) for f in files: if f.endswith(".db"): os.remove(os.path.join(path, f)) log.debug("Starting metrics exposition") if self.metrics_enabled: registry = CollectorRegistry() multiprocess.MultiProcessCollector(registry) start_http_server( port=self.metrics_port, addr=self.metrics_address, registry=registry )
python
def _setup_metrics(self): """ Start metric exposition """ path = os.environ.get("prometheus_multiproc_dir") if not os.path.exists(self.metrics_dir): try: log.info("Creating metrics directory") os.makedirs(self.metrics_dir) except OSError: log.error("Failed to create metrics directory!") raise ConfigurationException("Failed to create metrics directory!") path = self.metrics_dir elif path != self.metrics_dir: path = self.metrics_dir os.environ['prometheus_multiproc_dir'] = path log.info("Cleaning metrics collection directory") log.debug("Metrics directory set to: {}".format(path)) files = os.listdir(path) for f in files: if f.endswith(".db"): os.remove(os.path.join(path, f)) log.debug("Starting metrics exposition") if self.metrics_enabled: registry = CollectorRegistry() multiprocess.MultiProcessCollector(registry) start_http_server( port=self.metrics_port, addr=self.metrics_address, registry=registry )
[ "def", "_setup_metrics", "(", "self", ")", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "\"prometheus_multiproc_dir\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "metrics_dir", ")", ":", "try", ":", "log", ".", "info", "(", "\"Creating metrics directory\"", ")", "os", ".", "makedirs", "(", "self", ".", "metrics_dir", ")", "except", "OSError", ":", "log", ".", "error", "(", "\"Failed to create metrics directory!\"", ")", "raise", "ConfigurationException", "(", "\"Failed to create metrics directory!\"", ")", "path", "=", "self", ".", "metrics_dir", "elif", "path", "!=", "self", ".", "metrics_dir", ":", "path", "=", "self", ".", "metrics_dir", "os", ".", "environ", "[", "'prometheus_multiproc_dir'", "]", "=", "path", "log", ".", "info", "(", "\"Cleaning metrics collection directory\"", ")", "log", ".", "debug", "(", "\"Metrics directory set to: {}\"", ".", "format", "(", "path", ")", ")", "files", "=", "os", ".", "listdir", "(", "path", ")", "for", "f", "in", "files", ":", "if", "f", ".", "endswith", "(", "\".db\"", ")", ":", "os", ".", "remove", "(", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", ")", "log", ".", "debug", "(", "\"Starting metrics exposition\"", ")", "if", "self", ".", "metrics_enabled", ":", "registry", "=", "CollectorRegistry", "(", ")", "multiprocess", ".", "MultiProcessCollector", "(", "registry", ")", "start_http_server", "(", "port", "=", "self", ".", "metrics_port", ",", "addr", "=", "self", ".", "metrics_address", ",", "registry", "=", "registry", ")" ]
Start metric exposition
[ "Start", "metric", "exposition" ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L147-L177
train
233,516
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._setup_log
def _setup_log(self): ''' Setup the log object. ''' logging_level = CONFIG.LOGGING_LEVEL.get(self.log_level.lower()) logging.basicConfig(format=self.log_format, level=logging_level)
python
def _setup_log(self): ''' Setup the log object. ''' logging_level = CONFIG.LOGGING_LEVEL.get(self.log_level.lower()) logging.basicConfig(format=self.log_format, level=logging_level)
[ "def", "_setup_log", "(", "self", ")", ":", "logging_level", "=", "CONFIG", ".", "LOGGING_LEVEL", ".", "get", "(", "self", ".", "log_level", ".", "lower", "(", ")", ")", "logging", ".", "basicConfig", "(", "format", "=", "self", ".", "log_format", ",", "level", "=", "logging_level", ")" ]
Setup the log object.
[ "Setup", "the", "log", "object", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L179-L185
train
233,517
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._whitelist_blacklist
def _whitelist_blacklist(self, os_name): ''' Determines if the OS should be ignored, depending on the whitelist-blacklist logic configured by the user. ''' return napalm_logs.ext.check_whitelist_blacklist(os_name, whitelist=self.device_whitelist, blacklist=self.device_blacklist)
python
def _whitelist_blacklist(self, os_name): ''' Determines if the OS should be ignored, depending on the whitelist-blacklist logic configured by the user. ''' return napalm_logs.ext.check_whitelist_blacklist(os_name, whitelist=self.device_whitelist, blacklist=self.device_blacklist)
[ "def", "_whitelist_blacklist", "(", "self", ",", "os_name", ")", ":", "return", "napalm_logs", ".", "ext", ".", "check_whitelist_blacklist", "(", "os_name", ",", "whitelist", "=", "self", ".", "device_whitelist", ",", "blacklist", "=", "self", ".", "device_blacklist", ")" ]
Determines if the OS should be ignored, depending on the whitelist-blacklist logic configured by the user.
[ "Determines", "if", "the", "OS", "should", "be", "ignored", "depending", "on", "the", "whitelist", "-", "blacklist", "logic", "configured", "by", "the", "user", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L223-L231
train
233,518
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._extract_yaml_docstring
def _extract_yaml_docstring(stream): ''' Extract the comments at the top of the YAML file, from the stream handler. Return the extracted comment as string. ''' comment_lines = [] lines = stream.read().splitlines() for line in lines: line_strip = line.strip() if not line_strip: continue if line_strip.startswith('#'): comment_lines.append( line_strip.replace('#', '', 1).strip() ) else: break return ' '.join(comment_lines)
python
def _extract_yaml_docstring(stream): ''' Extract the comments at the top of the YAML file, from the stream handler. Return the extracted comment as string. ''' comment_lines = [] lines = stream.read().splitlines() for line in lines: line_strip = line.strip() if not line_strip: continue if line_strip.startswith('#'): comment_lines.append( line_strip.replace('#', '', 1).strip() ) else: break return ' '.join(comment_lines)
[ "def", "_extract_yaml_docstring", "(", "stream", ")", ":", "comment_lines", "=", "[", "]", "lines", "=", "stream", ".", "read", "(", ")", ".", "splitlines", "(", ")", "for", "line", "in", "lines", ":", "line_strip", "=", "line", ".", "strip", "(", ")", "if", "not", "line_strip", ":", "continue", "if", "line_strip", ".", "startswith", "(", "'#'", ")", ":", "comment_lines", ".", "append", "(", "line_strip", ".", "replace", "(", "'#'", ",", "''", ",", "1", ")", ".", "strip", "(", ")", ")", "else", ":", "break", "return", "' '", ".", "join", "(", "comment_lines", ")" ]
Extract the comments at the top of the YAML file, from the stream handler. Return the extracted comment as string.
[ "Extract", "the", "comments", "at", "the", "top", "of", "the", "YAML", "file", "from", "the", "stream", "handler", ".", "Return", "the", "extracted", "comment", "as", "string", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L234-L252
train
233,519
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._verify_config_dict
def _verify_config_dict(self, valid, config, dev_os, key_path=None): ''' Verify if the config dict is valid. ''' if not key_path: key_path = [] for key, value in valid.items(): self._verify_config_key(key, value, valid, config, dev_os, key_path)
python
def _verify_config_dict(self, valid, config, dev_os, key_path=None): ''' Verify if the config dict is valid. ''' if not key_path: key_path = [] for key, value in valid.items(): self._verify_config_key(key, value, valid, config, dev_os, key_path)
[ "def", "_verify_config_dict", "(", "self", ",", "valid", ",", "config", ",", "dev_os", ",", "key_path", "=", "None", ")", ":", "if", "not", "key_path", ":", "key_path", "=", "[", "]", "for", "key", ",", "value", "in", "valid", ".", "items", "(", ")", ":", "self", ".", "_verify_config_key", "(", "key", ",", "value", ",", "valid", ",", "config", ",", "dev_os", ",", "key_path", ")" ]
Verify if the config dict is valid.
[ "Verify", "if", "the", "config", "dict", "is", "valid", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L461-L468
train
233,520
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._verify_config
def _verify_config(self): ''' Verify that the config is correct ''' if not self.config_dict: self._raise_config_exception('No config found') # Check for device conifg, if there isn't anything then just log, do not raise an exception for dev_os, dev_config in self.config_dict.items(): if not dev_config: log.warning('No config found for %s', dev_os) continue # Compare the valid opts with the conifg self._verify_config_dict(CONFIG.VALID_CONFIG, dev_config, dev_os) log.debug('Read the config without error')
python
def _verify_config(self): ''' Verify that the config is correct ''' if not self.config_dict: self._raise_config_exception('No config found') # Check for device conifg, if there isn't anything then just log, do not raise an exception for dev_os, dev_config in self.config_dict.items(): if not dev_config: log.warning('No config found for %s', dev_os) continue # Compare the valid opts with the conifg self._verify_config_dict(CONFIG.VALID_CONFIG, dev_config, dev_os) log.debug('Read the config without error')
[ "def", "_verify_config", "(", "self", ")", ":", "if", "not", "self", ".", "config_dict", ":", "self", ".", "_raise_config_exception", "(", "'No config found'", ")", "# Check for device conifg, if there isn't anything then just log, do not raise an exception", "for", "dev_os", ",", "dev_config", "in", "self", ".", "config_dict", ".", "items", "(", ")", ":", "if", "not", "dev_config", ":", "log", ".", "warning", "(", "'No config found for %s'", ",", "dev_os", ")", "continue", "# Compare the valid opts with the conifg", "self", ".", "_verify_config_dict", "(", "CONFIG", ".", "VALID_CONFIG", ",", "dev_config", ",", "dev_os", ")", "log", ".", "debug", "(", "'Read the config without error'", ")" ]
Verify that the config is correct
[ "Verify", "that", "the", "config", "is", "correct" ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L470-L483
train
233,521
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._build_config
def _build_config(self): ''' Build the config of the napalm syslog parser. ''' if not self.config_dict: if not self.config_path: # No custom config path requested # Read the native config files self.config_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'config' ) log.info('Reading the configuration from %s', self.config_path) self.config_dict = self._load_config(self.config_path) if not self.extension_config_dict and\ self.extension_config_path and\ os.path.normpath(self.extension_config_path) != os.path.normpath(self.config_path): # same path? # When extension config is not sent as dict # But `extension_config_path` is specified log.info('Reading extension configuration from %s', self.extension_config_path) self.extension_config_dict = self._load_config(self.extension_config_path) if self.extension_config_dict: napalm_logs.utils.dictupdate(self.config_dict, self.extension_config_dict)
python
def _build_config(self): ''' Build the config of the napalm syslog parser. ''' if not self.config_dict: if not self.config_path: # No custom config path requested # Read the native config files self.config_path = os.path.join( os.path.dirname(os.path.realpath(__file__)), 'config' ) log.info('Reading the configuration from %s', self.config_path) self.config_dict = self._load_config(self.config_path) if not self.extension_config_dict and\ self.extension_config_path and\ os.path.normpath(self.extension_config_path) != os.path.normpath(self.config_path): # same path? # When extension config is not sent as dict # But `extension_config_path` is specified log.info('Reading extension configuration from %s', self.extension_config_path) self.extension_config_dict = self._load_config(self.extension_config_path) if self.extension_config_dict: napalm_logs.utils.dictupdate(self.config_dict, self.extension_config_dict)
[ "def", "_build_config", "(", "self", ")", ":", "if", "not", "self", ".", "config_dict", ":", "if", "not", "self", ".", "config_path", ":", "# No custom config path requested", "# Read the native config files", "self", ".", "config_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ",", "'config'", ")", "log", ".", "info", "(", "'Reading the configuration from %s'", ",", "self", ".", "config_path", ")", "self", ".", "config_dict", "=", "self", ".", "_load_config", "(", "self", ".", "config_path", ")", "if", "not", "self", ".", "extension_config_dict", "and", "self", ".", "extension_config_path", "and", "os", ".", "path", ".", "normpath", "(", "self", ".", "extension_config_path", ")", "!=", "os", ".", "path", ".", "normpath", "(", "self", ".", "config_path", ")", ":", "# same path?", "# When extension config is not sent as dict", "# But `extension_config_path` is specified", "log", ".", "info", "(", "'Reading extension configuration from %s'", ",", "self", ".", "extension_config_path", ")", "self", ".", "extension_config_dict", "=", "self", ".", "_load_config", "(", "self", ".", "extension_config_path", ")", "if", "self", ".", "extension_config_dict", ":", "napalm_logs", ".", "utils", ".", "dictupdate", "(", "self", ".", "config_dict", ",", "self", ".", "extension_config_dict", ")" ]
Build the config of the napalm syslog parser.
[ "Build", "the", "config", "of", "the", "napalm", "syslog", "parser", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L485-L507
train
233,522
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._start_auth_proc
def _start_auth_proc(self): ''' Start the authenticator process. ''' log.debug('Computing the signing key hex') verify_key = self.__signing_key.verify_key sgn_verify_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder) log.debug('Starting the authenticator subprocess') auth = NapalmLogsAuthProc(self.certificate, self.keyfile, self.__priv_key, sgn_verify_hex, self.auth_address, self.auth_port) proc = Process(target=auth.start) proc.start() proc.description = 'Auth process' log.debug('Started auth process as %s with PID %s', proc._name, proc.pid) return proc
python
def _start_auth_proc(self): ''' Start the authenticator process. ''' log.debug('Computing the signing key hex') verify_key = self.__signing_key.verify_key sgn_verify_hex = verify_key.encode(encoder=nacl.encoding.HexEncoder) log.debug('Starting the authenticator subprocess') auth = NapalmLogsAuthProc(self.certificate, self.keyfile, self.__priv_key, sgn_verify_hex, self.auth_address, self.auth_port) proc = Process(target=auth.start) proc.start() proc.description = 'Auth process' log.debug('Started auth process as %s with PID %s', proc._name, proc.pid) return proc
[ "def", "_start_auth_proc", "(", "self", ")", ":", "log", ".", "debug", "(", "'Computing the signing key hex'", ")", "verify_key", "=", "self", ".", "__signing_key", ".", "verify_key", "sgn_verify_hex", "=", "verify_key", ".", "encode", "(", "encoder", "=", "nacl", ".", "encoding", ".", "HexEncoder", ")", "log", ".", "debug", "(", "'Starting the authenticator subprocess'", ")", "auth", "=", "NapalmLogsAuthProc", "(", "self", ".", "certificate", ",", "self", ".", "keyfile", ",", "self", ".", "__priv_key", ",", "sgn_verify_hex", ",", "self", ".", "auth_address", ",", "self", ".", "auth_port", ")", "proc", "=", "Process", "(", "target", "=", "auth", ".", "start", ")", "proc", ".", "start", "(", ")", "proc", ".", "description", "=", "'Auth process'", "log", ".", "debug", "(", "'Started auth process as %s with PID %s'", ",", "proc", ".", "_name", ",", "proc", ".", "pid", ")", "return", "proc" ]
Start the authenticator process.
[ "Start", "the", "authenticator", "process", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L509-L527
train
233,523
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._start_lst_proc
def _start_lst_proc(self, listener_type, listener_opts): ''' Start the listener process. ''' log.debug('Starting the listener process for %s', listener_type) listener = NapalmLogsListenerProc(self.opts, self.address, self.port, listener_type, listener_opts=listener_opts) proc = Process(target=listener.start) proc.start() proc.description = 'Listener process' log.debug('Started listener process as %s with PID %s', proc._name, proc.pid) return proc
python
def _start_lst_proc(self, listener_type, listener_opts): ''' Start the listener process. ''' log.debug('Starting the listener process for %s', listener_type) listener = NapalmLogsListenerProc(self.opts, self.address, self.port, listener_type, listener_opts=listener_opts) proc = Process(target=listener.start) proc.start() proc.description = 'Listener process' log.debug('Started listener process as %s with PID %s', proc._name, proc.pid) return proc
[ "def", "_start_lst_proc", "(", "self", ",", "listener_type", ",", "listener_opts", ")", ":", "log", ".", "debug", "(", "'Starting the listener process for %s'", ",", "listener_type", ")", "listener", "=", "NapalmLogsListenerProc", "(", "self", ".", "opts", ",", "self", ".", "address", ",", "self", ".", "port", ",", "listener_type", ",", "listener_opts", "=", "listener_opts", ")", "proc", "=", "Process", "(", "target", "=", "listener", ".", "start", ")", "proc", ".", "start", "(", ")", "proc", ".", "description", "=", "'Listener process'", "log", ".", "debug", "(", "'Started listener process as %s with PID %s'", ",", "proc", ".", "_name", ",", "proc", ".", "pid", ")", "return", "proc" ]
Start the listener process.
[ "Start", "the", "listener", "process", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L529-L545
train
233,524
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._start_srv_proc
def _start_srv_proc(self, started_os_proc): ''' Start the server process. ''' log.debug('Starting the server process') server = NapalmLogsServerProc(self.opts, self.config_dict, started_os_proc, buffer=self._buffer) proc = Process(target=server.start) proc.start() proc.description = 'Server process' log.debug('Started server process as %s with PID %s', proc._name, proc.pid) return proc
python
def _start_srv_proc(self, started_os_proc): ''' Start the server process. ''' log.debug('Starting the server process') server = NapalmLogsServerProc(self.opts, self.config_dict, started_os_proc, buffer=self._buffer) proc = Process(target=server.start) proc.start() proc.description = 'Server process' log.debug('Started server process as %s with PID %s', proc._name, proc.pid) return proc
[ "def", "_start_srv_proc", "(", "self", ",", "started_os_proc", ")", ":", "log", ".", "debug", "(", "'Starting the server process'", ")", "server", "=", "NapalmLogsServerProc", "(", "self", ".", "opts", ",", "self", ".", "config_dict", ",", "started_os_proc", ",", "buffer", "=", "self", ".", "_buffer", ")", "proc", "=", "Process", "(", "target", "=", "server", ".", "start", ")", "proc", ".", "start", "(", ")", "proc", ".", "description", "=", "'Server process'", "log", ".", "debug", "(", "'Started server process as %s with PID %s'", ",", "proc", ".", "_name", ",", "proc", ".", "pid", ")", "return", "proc" ]
Start the server process.
[ "Start", "the", "server", "process", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L547-L561
train
233,525
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._start_pub_proc
def _start_pub_proc(self, publisher_type, publisher_opts, pub_id): ''' Start the publisher process. ''' log.debug('Starting the publisher process for %s', publisher_type) publisher = NapalmLogsPublisherProc(self.opts, self.publish_address, self.publish_port, publisher_type, self.serializer, self.__priv_key, self.__signing_key, publisher_opts, disable_security=self.disable_security, pub_id=pub_id) proc = Process(target=publisher.start) proc.start() proc.description = 'Publisher process' log.debug('Started publisher process as %s with PID %s', proc._name, proc.pid) return proc
python
def _start_pub_proc(self, publisher_type, publisher_opts, pub_id): ''' Start the publisher process. ''' log.debug('Starting the publisher process for %s', publisher_type) publisher = NapalmLogsPublisherProc(self.opts, self.publish_address, self.publish_port, publisher_type, self.serializer, self.__priv_key, self.__signing_key, publisher_opts, disable_security=self.disable_security, pub_id=pub_id) proc = Process(target=publisher.start) proc.start() proc.description = 'Publisher process' log.debug('Started publisher process as %s with PID %s', proc._name, proc.pid) return proc
[ "def", "_start_pub_proc", "(", "self", ",", "publisher_type", ",", "publisher_opts", ",", "pub_id", ")", ":", "log", ".", "debug", "(", "'Starting the publisher process for %s'", ",", "publisher_type", ")", "publisher", "=", "NapalmLogsPublisherProc", "(", "self", ".", "opts", ",", "self", ".", "publish_address", ",", "self", ".", "publish_port", ",", "publisher_type", ",", "self", ".", "serializer", ",", "self", ".", "__priv_key", ",", "self", ".", "__signing_key", ",", "publisher_opts", ",", "disable_security", "=", "self", ".", "disable_security", ",", "pub_id", "=", "pub_id", ")", "proc", "=", "Process", "(", "target", "=", "publisher", ".", "start", ")", "proc", ".", "start", "(", ")", "proc", ".", "description", "=", "'Publisher process'", "log", ".", "debug", "(", "'Started publisher process as %s with PID %s'", ",", "proc", ".", "_name", ",", "proc", ".", "pid", ")", "return", "proc" ]
Start the publisher process.
[ "Start", "the", "publisher", "process", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L573-L595
train
233,526
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._start_dev_proc
def _start_dev_proc(self, device_os, device_config): ''' Start the device worker process. ''' log.info('Starting the child process for %s', device_os) dos = NapalmLogsDeviceProc(device_os, self.opts, device_config) os_proc = Process(target=dos.start) os_proc.start() os_proc.description = '%s device process' % device_os log.debug('Started process %s for %s, having PID %s', os_proc._name, device_os, os_proc.pid) return os_proc
python
def _start_dev_proc(self, device_os, device_config): ''' Start the device worker process. ''' log.info('Starting the child process for %s', device_os) dos = NapalmLogsDeviceProc(device_os, self.opts, device_config) os_proc = Process(target=dos.start) os_proc.start() os_proc.description = '%s device process' % device_os log.debug('Started process %s for %s, having PID %s', os_proc._name, device_os, os_proc.pid) return os_proc
[ "def", "_start_dev_proc", "(", "self", ",", "device_os", ",", "device_config", ")", ":", "log", ".", "info", "(", "'Starting the child process for %s'", ",", "device_os", ")", "dos", "=", "NapalmLogsDeviceProc", "(", "device_os", ",", "self", ".", "opts", ",", "device_config", ")", "os_proc", "=", "Process", "(", "target", "=", "dos", ".", "start", ")", "os_proc", ".", "start", "(", ")", "os_proc", ".", "description", "=", "'%s device process'", "%", "device_os", "log", ".", "debug", "(", "'Started process %s for %s, having PID %s'", ",", "os_proc", ".", "_name", ",", "device_os", ",", "os_proc", ".", "pid", ")", "return", "os_proc" ]
Start the device worker process.
[ "Start", "the", "device", "worker", "process", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L597-L611
train
233,527
napalm-automation/napalm-logs
napalm_logs/base.py
NapalmLogs._check_children
def _check_children(self): ''' Check all of the child processes are still running ''' while self.up: time.sleep(1) for process in self._processes: if process.is_alive() is True: continue log.debug('%s is dead. Stopping the napalm-logs engine.', process.description) self.stop_engine()
python
def _check_children(self): ''' Check all of the child processes are still running ''' while self.up: time.sleep(1) for process in self._processes: if process.is_alive() is True: continue log.debug('%s is dead. Stopping the napalm-logs engine.', process.description) self.stop_engine()
[ "def", "_check_children", "(", "self", ")", ":", "while", "self", ".", "up", ":", "time", ".", "sleep", "(", "1", ")", "for", "process", "in", "self", ".", "_processes", ":", "if", "process", ".", "is_alive", "(", ")", "is", "True", ":", "continue", "log", ".", "debug", "(", "'%s is dead. Stopping the napalm-logs engine.'", ",", "process", ".", "description", ")", "self", ".", "stop_engine", "(", ")" ]
Check all of the child processes are still running
[ "Check", "all", "of", "the", "child", "processes", "are", "still", "running" ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/base.py#L664-L674
train
233,528
napalm-automation/napalm-logs
napalm_logs/pub_proxy.py
NapalmLogsPublisherProxy._setup_ipc
def _setup_ipc(self): ''' Setup the IPC PUB and SUB sockets for the proxy. ''' log.debug('Setting up the internal IPC proxy') self.ctx = zmq.Context() # Frontend self.sub = self.ctx.socket(zmq.SUB) self.sub.bind(PUB_PX_IPC_URL) self.sub.setsockopt(zmq.SUBSCRIBE, b'') log.debug('Setting HWM for the proxy frontend: %d', self.hwm) try: self.sub.setsockopt(zmq.HWM, self.hwm) # zmq 2 except AttributeError: # zmq 3 self.sub.setsockopt(zmq.SNDHWM, self.hwm) # Backend self.pub = self.ctx.socket(zmq.PUB) self.pub.bind(PUB_IPC_URL) log.debug('Setting HWM for the proxy backend: %d', self.hwm) try: self.pub.setsockopt(zmq.HWM, self.hwm) # zmq 2 except AttributeError: # zmq 3 self.pub.setsockopt(zmq.SNDHWM, self.hwm)
python
def _setup_ipc(self): ''' Setup the IPC PUB and SUB sockets for the proxy. ''' log.debug('Setting up the internal IPC proxy') self.ctx = zmq.Context() # Frontend self.sub = self.ctx.socket(zmq.SUB) self.sub.bind(PUB_PX_IPC_URL) self.sub.setsockopt(zmq.SUBSCRIBE, b'') log.debug('Setting HWM for the proxy frontend: %d', self.hwm) try: self.sub.setsockopt(zmq.HWM, self.hwm) # zmq 2 except AttributeError: # zmq 3 self.sub.setsockopt(zmq.SNDHWM, self.hwm) # Backend self.pub = self.ctx.socket(zmq.PUB) self.pub.bind(PUB_IPC_URL) log.debug('Setting HWM for the proxy backend: %d', self.hwm) try: self.pub.setsockopt(zmq.HWM, self.hwm) # zmq 2 except AttributeError: # zmq 3 self.pub.setsockopt(zmq.SNDHWM, self.hwm)
[ "def", "_setup_ipc", "(", "self", ")", ":", "log", ".", "debug", "(", "'Setting up the internal IPC proxy'", ")", "self", ".", "ctx", "=", "zmq", ".", "Context", "(", ")", "# Frontend", "self", ".", "sub", "=", "self", ".", "ctx", ".", "socket", "(", "zmq", ".", "SUB", ")", "self", ".", "sub", ".", "bind", "(", "PUB_PX_IPC_URL", ")", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "SUBSCRIBE", ",", "b''", ")", "log", ".", "debug", "(", "'Setting HWM for the proxy frontend: %d'", ",", "self", ".", "hwm", ")", "try", ":", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "HWM", ",", "self", ".", "hwm", ")", "# zmq 2", "except", "AttributeError", ":", "# zmq 3", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "SNDHWM", ",", "self", ".", "hwm", ")", "# Backend", "self", ".", "pub", "=", "self", ".", "ctx", ".", "socket", "(", "zmq", ".", "PUB", ")", "self", ".", "pub", ".", "bind", "(", "PUB_IPC_URL", ")", "log", ".", "debug", "(", "'Setting HWM for the proxy backend: %d'", ",", "self", ".", "hwm", ")", "try", ":", "self", ".", "pub", ".", "setsockopt", "(", "zmq", ".", "HWM", ",", "self", ".", "hwm", ")", "# zmq 2", "except", "AttributeError", ":", "# zmq 3", "self", ".", "pub", ".", "setsockopt", "(", "zmq", ".", "SNDHWM", ",", "self", ".", "hwm", ")" ]
Setup the IPC PUB and SUB sockets for the proxy.
[ "Setup", "the", "IPC", "PUB", "and", "SUB", "sockets", "for", "the", "proxy", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/pub_proxy.py#L38-L64
train
233,529
napalm-automation/napalm-logs
napalm_logs/publisher.py
NapalmLogsPublisherProc._setup_ipc
def _setup_ipc(self): ''' Subscribe to the pub IPC and publish the messages on the right transport. ''' self.ctx = zmq.Context() log.debug('Setting up the %s publisher subscriber #%d', self._transport_type, self.pub_id) self.sub = self.ctx.socket(zmq.SUB) self.sub.connect(PUB_IPC_URL) self.sub.setsockopt(zmq.SUBSCRIBE, b'') try: self.sub.setsockopt(zmq.HWM, self.opts['hwm']) # zmq 2 except AttributeError: # zmq 3 self.sub.setsockopt(zmq.RCVHWM, self.opts['hwm'])
python
def _setup_ipc(self): ''' Subscribe to the pub IPC and publish the messages on the right transport. ''' self.ctx = zmq.Context() log.debug('Setting up the %s publisher subscriber #%d', self._transport_type, self.pub_id) self.sub = self.ctx.socket(zmq.SUB) self.sub.connect(PUB_IPC_URL) self.sub.setsockopt(zmq.SUBSCRIBE, b'') try: self.sub.setsockopt(zmq.HWM, self.opts['hwm']) # zmq 2 except AttributeError: # zmq 3 self.sub.setsockopt(zmq.RCVHWM, self.opts['hwm'])
[ "def", "_setup_ipc", "(", "self", ")", ":", "self", ".", "ctx", "=", "zmq", ".", "Context", "(", ")", "log", ".", "debug", "(", "'Setting up the %s publisher subscriber #%d'", ",", "self", ".", "_transport_type", ",", "self", ".", "pub_id", ")", "self", ".", "sub", "=", "self", ".", "ctx", ".", "socket", "(", "zmq", ".", "SUB", ")", "self", ".", "sub", ".", "connect", "(", "PUB_IPC_URL", ")", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "SUBSCRIBE", ",", "b''", ")", "try", ":", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "HWM", ",", "self", ".", "opts", "[", "'hwm'", "]", ")", "# zmq 2", "except", "AttributeError", ":", "# zmq 3", "self", ".", "sub", ".", "setsockopt", "(", "zmq", ".", "RCVHWM", ",", "self", ".", "opts", "[", "'hwm'", "]", ")" ]
Subscribe to the pub IPC and publish the messages on the right transport.
[ "Subscribe", "to", "the", "pub", "IPC", "and", "publish", "the", "messages", "on", "the", "right", "transport", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/publisher.py#L71-L87
train
233,530
napalm-automation/napalm-logs
napalm_logs/publisher.py
NapalmLogsPublisherProc._prepare
def _prepare(self, serialized_obj): ''' Prepare the object to be sent over the untrusted channel. ''' # generating a nonce nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) # encrypting using the nonce encrypted = self.__safe.encrypt(serialized_obj, nonce) # sign the message signed = self.__signing_key.sign(encrypted) return signed
python
def _prepare(self, serialized_obj): ''' Prepare the object to be sent over the untrusted channel. ''' # generating a nonce nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) # encrypting using the nonce encrypted = self.__safe.encrypt(serialized_obj, nonce) # sign the message signed = self.__signing_key.sign(encrypted) return signed
[ "def", "_prepare", "(", "self", ",", "serialized_obj", ")", ":", "# generating a nonce", "nonce", "=", "nacl", ".", "utils", ".", "random", "(", "nacl", ".", "secret", ".", "SecretBox", ".", "NONCE_SIZE", ")", "# encrypting using the nonce", "encrypted", "=", "self", ".", "__safe", ".", "encrypt", "(", "serialized_obj", ",", "nonce", ")", "# sign the message", "signed", "=", "self", ".", "__signing_key", ".", "sign", "(", "encrypted", ")", "return", "signed" ]
Prepare the object to be sent over the untrusted channel.
[ "Prepare", "the", "object", "to", "be", "sent", "over", "the", "untrusted", "channel", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/publisher.py#L110-L120
train
233,531
napalm-automation/napalm-logs
napalm_logs/listener/__init__.py
get_listener
def get_listener(name): ''' Return the listener class. ''' try: log.debug('Using %s as listener', name) return LISTENER_LOOKUP[name] except KeyError: msg = 'Listener {} is not available. Are the dependencies installed?'.format(name) log.error(msg, exc_info=True) raise InvalidListenerException(msg)
python
def get_listener(name): ''' Return the listener class. ''' try: log.debug('Using %s as listener', name) return LISTENER_LOOKUP[name] except KeyError: msg = 'Listener {} is not available. Are the dependencies installed?'.format(name) log.error(msg, exc_info=True) raise InvalidListenerException(msg)
[ "def", "get_listener", "(", "name", ")", ":", "try", ":", "log", ".", "debug", "(", "'Using %s as listener'", ",", "name", ")", "return", "LISTENER_LOOKUP", "[", "name", "]", "except", "KeyError", ":", "msg", "=", "'Listener {} is not available. Are the dependencies installed?'", ".", "format", "(", "name", ")", "log", ".", "error", "(", "msg", ",", "exc_info", "=", "True", ")", "raise", "InvalidListenerException", "(", "msg", ")" ]
Return the listener class.
[ "Return", "the", "listener", "class", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/__init__.py#L41-L51
train
233,532
napalm-automation/napalm-logs
napalm_logs/utils/__init__.py
ClientAuth._start_keep_alive
def _start_keep_alive(self): ''' Start the keep alive thread as a daemon ''' keep_alive_thread = threading.Thread(target=self.keep_alive) keep_alive_thread.daemon = True keep_alive_thread.start()
python
def _start_keep_alive(self): ''' Start the keep alive thread as a daemon ''' keep_alive_thread = threading.Thread(target=self.keep_alive) keep_alive_thread.daemon = True keep_alive_thread.start()
[ "def", "_start_keep_alive", "(", "self", ")", ":", "keep_alive_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "keep_alive", ")", "keep_alive_thread", ".", "daemon", "=", "True", "keep_alive_thread", ".", "start", "(", ")" ]
Start the keep alive thread as a daemon
[ "Start", "the", "keep", "alive", "thread", "as", "a", "daemon" ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/utils/__init__.py#L61-L67
train
233,533
napalm-automation/napalm-logs
napalm_logs/utils/__init__.py
ClientAuth.keep_alive
def keep_alive(self): ''' Send a keep alive request periodically to make sure that the server is still alive. If not then try to reconnect. ''' self.ssl_skt.settimeout(defaults.AUTH_KEEP_ALIVE_INTERVAL) while self.__up: try: log.debug('Sending keep-alive message to the server') self.ssl_skt.send(defaults.AUTH_KEEP_ALIVE) except socket.error: log.error('Unable to send keep-alive message to the server.') log.error('Re-init the SSL socket.') self.reconnect() log.debug('Trying to re-send the keep-alive message to the server.') self.ssl_skt.send(defaults.AUTH_KEEP_ALIVE) msg = self.ssl_skt.recv(len(defaults.AUTH_KEEP_ALIVE_ACK)) log.debug('Received %s from the keep-alive server', msg) if msg != defaults.AUTH_KEEP_ALIVE_ACK: log.error('Received %s instead of %s form the auth keep-alive server', msg, defaults.AUTH_KEEP_ALIVE_ACK) log.error('Re-init the SSL socket.') self.reconnect() time.sleep(defaults.AUTH_KEEP_ALIVE_INTERVAL)
python
def keep_alive(self): ''' Send a keep alive request periodically to make sure that the server is still alive. If not then try to reconnect. ''' self.ssl_skt.settimeout(defaults.AUTH_KEEP_ALIVE_INTERVAL) while self.__up: try: log.debug('Sending keep-alive message to the server') self.ssl_skt.send(defaults.AUTH_KEEP_ALIVE) except socket.error: log.error('Unable to send keep-alive message to the server.') log.error('Re-init the SSL socket.') self.reconnect() log.debug('Trying to re-send the keep-alive message to the server.') self.ssl_skt.send(defaults.AUTH_KEEP_ALIVE) msg = self.ssl_skt.recv(len(defaults.AUTH_KEEP_ALIVE_ACK)) log.debug('Received %s from the keep-alive server', msg) if msg != defaults.AUTH_KEEP_ALIVE_ACK: log.error('Received %s instead of %s form the auth keep-alive server', msg, defaults.AUTH_KEEP_ALIVE_ACK) log.error('Re-init the SSL socket.') self.reconnect() time.sleep(defaults.AUTH_KEEP_ALIVE_INTERVAL)
[ "def", "keep_alive", "(", "self", ")", ":", "self", ".", "ssl_skt", ".", "settimeout", "(", "defaults", ".", "AUTH_KEEP_ALIVE_INTERVAL", ")", "while", "self", ".", "__up", ":", "try", ":", "log", ".", "debug", "(", "'Sending keep-alive message to the server'", ")", "self", ".", "ssl_skt", ".", "send", "(", "defaults", ".", "AUTH_KEEP_ALIVE", ")", "except", "socket", ".", "error", ":", "log", ".", "error", "(", "'Unable to send keep-alive message to the server.'", ")", "log", ".", "error", "(", "'Re-init the SSL socket.'", ")", "self", ".", "reconnect", "(", ")", "log", ".", "debug", "(", "'Trying to re-send the keep-alive message to the server.'", ")", "self", ".", "ssl_skt", ".", "send", "(", "defaults", ".", "AUTH_KEEP_ALIVE", ")", "msg", "=", "self", ".", "ssl_skt", ".", "recv", "(", "len", "(", "defaults", ".", "AUTH_KEEP_ALIVE_ACK", ")", ")", "log", ".", "debug", "(", "'Received %s from the keep-alive server'", ",", "msg", ")", "if", "msg", "!=", "defaults", ".", "AUTH_KEEP_ALIVE_ACK", ":", "log", ".", "error", "(", "'Received %s instead of %s form the auth keep-alive server'", ",", "msg", ",", "defaults", ".", "AUTH_KEEP_ALIVE_ACK", ")", "log", ".", "error", "(", "'Re-init the SSL socket.'", ")", "self", ".", "reconnect", "(", ")", "time", ".", "sleep", "(", "defaults", ".", "AUTH_KEEP_ALIVE_INTERVAL", ")" ]
Send a keep alive request periodically to make sure that the server is still alive. If not then try to reconnect.
[ "Send", "a", "keep", "alive", "request", "periodically", "to", "make", "sure", "that", "the", "server", "is", "still", "alive", ".", "If", "not", "then", "try", "to", "reconnect", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/utils/__init__.py#L69-L92
train
233,534
napalm-automation/napalm-logs
napalm_logs/utils/__init__.py
ClientAuth.reconnect
def reconnect(self): ''' Try to reconnect and re-authenticate with the server. ''' log.debug('Closing the SSH socket.') try: self.ssl_skt.close() except socket.error: log.error('The socket seems to be closed already.') log.debug('Re-opening the SSL socket.') self.authenticate()
python
def reconnect(self): ''' Try to reconnect and re-authenticate with the server. ''' log.debug('Closing the SSH socket.') try: self.ssl_skt.close() except socket.error: log.error('The socket seems to be closed already.') log.debug('Re-opening the SSL socket.') self.authenticate()
[ "def", "reconnect", "(", "self", ")", ":", "log", ".", "debug", "(", "'Closing the SSH socket.'", ")", "try", ":", "self", ".", "ssl_skt", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "log", ".", "error", "(", "'The socket seems to be closed already.'", ")", "log", ".", "debug", "(", "'Re-opening the SSL socket.'", ")", "self", ".", "authenticate", "(", ")" ]
Try to reconnect and re-authenticate with the server.
[ "Try", "to", "reconnect", "and", "re", "-", "authenticate", "with", "the", "server", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/utils/__init__.py#L94-L104
train
233,535
napalm-automation/napalm-logs
napalm_logs/utils/__init__.py
ClientAuth.authenticate
def authenticate(self): ''' Authenticate the client and return the private and signature keys. Establish a connection through a secured socket, then do the handshake using the napalm-logs auth algorithm. ''' log.debug('Authenticate to %s:%d, using the certificate %s', self.address, self.port, self.certificate) if ':' in self.address: skt_ver = socket.AF_INET6 else: skt_ver = socket.AF_INET skt = socket.socket(skt_ver, socket.SOCK_STREAM) self.ssl_skt = ssl.wrap_socket(skt, ca_certs=self.certificate, cert_reqs=ssl.CERT_REQUIRED) try: self.ssl_skt.connect((self.address, self.port)) self.auth_try_id = 0 except socket.error as err: log.error('Unable to open the SSL socket.') self.auth_try_id += 1 if not self.max_try or self.auth_try_id < self.max_try: log.error('Trying to authenticate again in %d seconds', self.timeout) time.sleep(self.timeout) self.authenticate() log.critical('Giving up, unable to authenticate to %s:%d using the certificate %s', self.address, self.port, self.certificate) raise ClientConnectException(err) # Explicit INIT self.ssl_skt.write(defaults.MAGIC_REQ) # Receive the private key private_key = self.ssl_skt.recv(defaults.BUFFER_SIZE) # Send back explicit ACK self.ssl_skt.write(defaults.MAGIC_ACK) # Read the hex of the verification key verify_key_hex = self.ssl_skt.recv(defaults.BUFFER_SIZE) # Send back explicit ACK self.ssl_skt.write(defaults.MAGIC_ACK) self.priv_key = nacl.secret.SecretBox(private_key) self.verify_key = nacl.signing.VerifyKey(verify_key_hex, encoder=nacl.encoding.HexEncoder)
python
def authenticate(self): ''' Authenticate the client and return the private and signature keys. Establish a connection through a secured socket, then do the handshake using the napalm-logs auth algorithm. ''' log.debug('Authenticate to %s:%d, using the certificate %s', self.address, self.port, self.certificate) if ':' in self.address: skt_ver = socket.AF_INET6 else: skt_ver = socket.AF_INET skt = socket.socket(skt_ver, socket.SOCK_STREAM) self.ssl_skt = ssl.wrap_socket(skt, ca_certs=self.certificate, cert_reqs=ssl.CERT_REQUIRED) try: self.ssl_skt.connect((self.address, self.port)) self.auth_try_id = 0 except socket.error as err: log.error('Unable to open the SSL socket.') self.auth_try_id += 1 if not self.max_try or self.auth_try_id < self.max_try: log.error('Trying to authenticate again in %d seconds', self.timeout) time.sleep(self.timeout) self.authenticate() log.critical('Giving up, unable to authenticate to %s:%d using the certificate %s', self.address, self.port, self.certificate) raise ClientConnectException(err) # Explicit INIT self.ssl_skt.write(defaults.MAGIC_REQ) # Receive the private key private_key = self.ssl_skt.recv(defaults.BUFFER_SIZE) # Send back explicit ACK self.ssl_skt.write(defaults.MAGIC_ACK) # Read the hex of the verification key verify_key_hex = self.ssl_skt.recv(defaults.BUFFER_SIZE) # Send back explicit ACK self.ssl_skt.write(defaults.MAGIC_ACK) self.priv_key = nacl.secret.SecretBox(private_key) self.verify_key = nacl.signing.VerifyKey(verify_key_hex, encoder=nacl.encoding.HexEncoder)
[ "def", "authenticate", "(", "self", ")", ":", "log", ".", "debug", "(", "'Authenticate to %s:%d, using the certificate %s'", ",", "self", ".", "address", ",", "self", ".", "port", ",", "self", ".", "certificate", ")", "if", "':'", "in", "self", ".", "address", ":", "skt_ver", "=", "socket", ".", "AF_INET6", "else", ":", "skt_ver", "=", "socket", ".", "AF_INET", "skt", "=", "socket", ".", "socket", "(", "skt_ver", ",", "socket", ".", "SOCK_STREAM", ")", "self", ".", "ssl_skt", "=", "ssl", ".", "wrap_socket", "(", "skt", ",", "ca_certs", "=", "self", ".", "certificate", ",", "cert_reqs", "=", "ssl", ".", "CERT_REQUIRED", ")", "try", ":", "self", ".", "ssl_skt", ".", "connect", "(", "(", "self", ".", "address", ",", "self", ".", "port", ")", ")", "self", ".", "auth_try_id", "=", "0", "except", "socket", ".", "error", "as", "err", ":", "log", ".", "error", "(", "'Unable to open the SSL socket.'", ")", "self", ".", "auth_try_id", "+=", "1", "if", "not", "self", ".", "max_try", "or", "self", ".", "auth_try_id", "<", "self", ".", "max_try", ":", "log", ".", "error", "(", "'Trying to authenticate again in %d seconds'", ",", "self", ".", "timeout", ")", "time", ".", "sleep", "(", "self", ".", "timeout", ")", "self", ".", "authenticate", "(", ")", "log", ".", "critical", "(", "'Giving up, unable to authenticate to %s:%d using the certificate %s'", ",", "self", ".", "address", ",", "self", ".", "port", ",", "self", ".", "certificate", ")", "raise", "ClientConnectException", "(", "err", ")", "# Explicit INIT", "self", ".", "ssl_skt", ".", "write", "(", "defaults", ".", "MAGIC_REQ", ")", "# Receive the private key", "private_key", "=", "self", ".", "ssl_skt", ".", "recv", "(", "defaults", ".", "BUFFER_SIZE", ")", "# Send back explicit ACK", "self", ".", "ssl_skt", ".", "write", "(", "defaults", ".", "MAGIC_ACK", ")", "# Read the hex of the verification key", "verify_key_hex", "=", "self", ".", "ssl_skt", ".", "recv", "(", "defaults", ".", "BUFFER_SIZE", ")", "# Send back explicit ACK", "self", ".", "ssl_skt", ".", "write", "(", "defaults", ".", "MAGIC_ACK", ")", "self", ".", "priv_key", "=", "nacl", ".", "secret", ".", "SecretBox", "(", "private_key", ")", "self", ".", "verify_key", "=", "nacl", ".", "signing", ".", "VerifyKey", "(", "verify_key_hex", ",", "encoder", "=", "nacl", ".", "encoding", ".", "HexEncoder", ")" ]
Authenticate the client and return the private and signature keys. Establish a connection through a secured socket, then do the handshake using the napalm-logs auth algorithm.
[ "Authenticate", "the", "client", "and", "return", "the", "private", "and", "signature", "keys", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/utils/__init__.py#L106-L150
train
233,536
napalm-automation/napalm-logs
napalm_logs/utils/__init__.py
ClientAuth.decrypt
def decrypt(self, binary): ''' Decrypt and unpack the original OpenConfig object, serialized using MessagePack. Raise BadSignatureException when the signature was forged or corrupted. ''' try: encrypted = self.verify_key.verify(binary) except BadSignatureError: log.error('Signature was forged or corrupt', exc_info=True) raise BadSignatureException('Signature was forged or corrupt') try: packed = self.priv_key.decrypt(encrypted) except CryptoError: log.error('Unable to decrypt', exc_info=True) raise CryptoException('Unable to decrypt') return umsgpack.unpackb(packed)
python
def decrypt(self, binary): ''' Decrypt and unpack the original OpenConfig object, serialized using MessagePack. Raise BadSignatureException when the signature was forged or corrupted. ''' try: encrypted = self.verify_key.verify(binary) except BadSignatureError: log.error('Signature was forged or corrupt', exc_info=True) raise BadSignatureException('Signature was forged or corrupt') try: packed = self.priv_key.decrypt(encrypted) except CryptoError: log.error('Unable to decrypt', exc_info=True) raise CryptoException('Unable to decrypt') return umsgpack.unpackb(packed)
[ "def", "decrypt", "(", "self", ",", "binary", ")", ":", "try", ":", "encrypted", "=", "self", ".", "verify_key", ".", "verify", "(", "binary", ")", "except", "BadSignatureError", ":", "log", ".", "error", "(", "'Signature was forged or corrupt'", ",", "exc_info", "=", "True", ")", "raise", "BadSignatureException", "(", "'Signature was forged or corrupt'", ")", "try", ":", "packed", "=", "self", ".", "priv_key", ".", "decrypt", "(", "encrypted", ")", "except", "CryptoError", ":", "log", ".", "error", "(", "'Unable to decrypt'", ",", "exc_info", "=", "True", ")", "raise", "CryptoException", "(", "'Unable to decrypt'", ")", "return", "umsgpack", ".", "unpackb", "(", "packed", ")" ]
Decrypt and unpack the original OpenConfig object, serialized using MessagePack. Raise BadSignatureException when the signature was forged or corrupted.
[ "Decrypt", "and", "unpack", "the", "original", "OpenConfig", "object", "serialized", "using", "MessagePack", ".", "Raise", "BadSignatureException", "when", "the", "signature", "was", "forged", "or", "corrupted", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/utils/__init__.py#L152-L169
train
233,537
napalm-automation/napalm-logs
napalm_logs/listener/tcp.py
TCPListener._client_connection
def _client_connection(self, conn, addr): ''' Handle the connecition with one client. ''' log.debug('Established connection with %s:%d', addr[0], addr[1]) conn.settimeout(self.socket_timeout) try: while self.__up: msg = conn.recv(self.buffer_size) if not msg: # log.debug('Received empty message from %s', addr) # disabled ^ as it was too noisy continue log.debug('[%s] Received %s from %s. Adding in the queue', time.time(), msg, addr) self.buffer.put((msg, '{}:{}'.format(addr[0], addr[1]))) except socket.timeout: if not self.__up: return log.debug('Connection %s:%d timed out', addr[1], addr[0]) raise ListenerException('Connection %s:%d timed out' % addr) finally: log.debug('Closing connection with %s', addr) conn.close()
python
def _client_connection(self, conn, addr): ''' Handle the connecition with one client. ''' log.debug('Established connection with %s:%d', addr[0], addr[1]) conn.settimeout(self.socket_timeout) try: while self.__up: msg = conn.recv(self.buffer_size) if not msg: # log.debug('Received empty message from %s', addr) # disabled ^ as it was too noisy continue log.debug('[%s] Received %s from %s. Adding in the queue', time.time(), msg, addr) self.buffer.put((msg, '{}:{}'.format(addr[0], addr[1]))) except socket.timeout: if not self.__up: return log.debug('Connection %s:%d timed out', addr[1], addr[0]) raise ListenerException('Connection %s:%d timed out' % addr) finally: log.debug('Closing connection with %s', addr) conn.close()
[ "def", "_client_connection", "(", "self", ",", "conn", ",", "addr", ")", ":", "log", ".", "debug", "(", "'Established connection with %s:%d'", ",", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ")", "conn", ".", "settimeout", "(", "self", ".", "socket_timeout", ")", "try", ":", "while", "self", ".", "__up", ":", "msg", "=", "conn", ".", "recv", "(", "self", ".", "buffer_size", ")", "if", "not", "msg", ":", "# log.debug('Received empty message from %s', addr)", "# disabled ^ as it was too noisy", "continue", "log", ".", "debug", "(", "'[%s] Received %s from %s. Adding in the queue'", ",", "time", ".", "time", "(", ")", ",", "msg", ",", "addr", ")", "self", ".", "buffer", ".", "put", "(", "(", "msg", ",", "'{}:{}'", ".", "format", "(", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ")", ")", ")", "except", "socket", ".", "timeout", ":", "if", "not", "self", ".", "__up", ":", "return", "log", ".", "debug", "(", "'Connection %s:%d timed out'", ",", "addr", "[", "1", "]", ",", "addr", "[", "0", "]", ")", "raise", "ListenerException", "(", "'Connection %s:%d timed out'", "%", "addr", ")", "finally", ":", "log", ".", "debug", "(", "'Closing connection with %s'", ",", "addr", ")", "conn", ".", "close", "(", ")" ]
Handle the connecition with one client.
[ "Handle", "the", "connecition", "with", "one", "client", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/tcp.py#L53-L75
train
233,538
napalm-automation/napalm-logs
napalm_logs/listener/tcp.py
TCPListener._serve_clients
def _serve_clients(self): ''' Accept cients and serve, one separate thread per client. ''' self.__up = True while self.__up: log.debug('Waiting for a client to connect') try: conn, addr = self.skt.accept() log.debug('Received connection from %s:%d', addr[0], addr[1]) except socket.error as error: if not self.__up: return msg = 'Received listener socket error: {}'.format(error) log.error(msg, exc_info=True) raise ListenerException(msg) client_thread = threading.Thread(target=self._client_connection, args=(conn, addr,)) client_thread.start()
python
def _serve_clients(self): ''' Accept cients and serve, one separate thread per client. ''' self.__up = True while self.__up: log.debug('Waiting for a client to connect') try: conn, addr = self.skt.accept() log.debug('Received connection from %s:%d', addr[0], addr[1]) except socket.error as error: if not self.__up: return msg = 'Received listener socket error: {}'.format(error) log.error(msg, exc_info=True) raise ListenerException(msg) client_thread = threading.Thread(target=self._client_connection, args=(conn, addr,)) client_thread.start()
[ "def", "_serve_clients", "(", "self", ")", ":", "self", ".", "__up", "=", "True", "while", "self", ".", "__up", ":", "log", ".", "debug", "(", "'Waiting for a client to connect'", ")", "try", ":", "conn", ",", "addr", "=", "self", ".", "skt", ".", "accept", "(", ")", "log", ".", "debug", "(", "'Received connection from %s:%d'", ",", "addr", "[", "0", "]", ",", "addr", "[", "1", "]", ")", "except", "socket", ".", "error", "as", "error", ":", "if", "not", "self", ".", "__up", ":", "return", "msg", "=", "'Received listener socket error: {}'", ".", "format", "(", "error", ")", "log", ".", "error", "(", "msg", ",", "exc_info", "=", "True", ")", "raise", "ListenerException", "(", "msg", ")", "client_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_client_connection", ",", "args", "=", "(", "conn", ",", "addr", ",", ")", ")", "client_thread", ".", "start", "(", ")" ]
Accept cients and serve, one separate thread per client.
[ "Accept", "cients", "and", "serve", "one", "separate", "thread", "per", "client", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/tcp.py#L77-L94
train
233,539
napalm-automation/napalm-logs
napalm_logs/listener/tcp.py
TCPListener.start
def start(self): ''' Start listening for messages. ''' log.debug('Creating the TCP server') if ':' in self.address: self.skt = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.reuse_port: self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'SO_REUSEPORT'): self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) else: log.error('SO_REUSEPORT not supported') try: self.skt.bind((self.address, int(self.port))) except socket.error as msg: error_string = 'Unable to bind to port {} on {}: {}'.format(self.port, self.address, msg) log.error(error_string, exc_info=True) raise BindException(error_string) log.debug('Accepting max %d parallel connections', self.max_clients) self.skt.listen(self.max_clients) self.thread_serve = threading.Thread(target=self._serve_clients) self.thread_serve.start()
python
def start(self): ''' Start listening for messages. ''' log.debug('Creating the TCP server') if ':' in self.address: self.skt = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) else: self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.reuse_port: self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) if hasattr(socket, 'SO_REUSEPORT'): self.skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) else: log.error('SO_REUSEPORT not supported') try: self.skt.bind((self.address, int(self.port))) except socket.error as msg: error_string = 'Unable to bind to port {} on {}: {}'.format(self.port, self.address, msg) log.error(error_string, exc_info=True) raise BindException(error_string) log.debug('Accepting max %d parallel connections', self.max_clients) self.skt.listen(self.max_clients) self.thread_serve = threading.Thread(target=self._serve_clients) self.thread_serve.start()
[ "def", "start", "(", "self", ")", ":", "log", ".", "debug", "(", "'Creating the TCP server'", ")", "if", "':'", "in", "self", ".", "address", ":", "self", ".", "skt", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET6", ",", "socket", ".", "SOCK_STREAM", ")", "else", ":", "self", ".", "skt", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "if", "self", ".", "reuse_port", ":", "self", ".", "skt", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEADDR", ",", "1", ")", "if", "hasattr", "(", "socket", ",", "'SO_REUSEPORT'", ")", ":", "self", ".", "skt", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", "SO_REUSEPORT", ",", "1", ")", "else", ":", "log", ".", "error", "(", "'SO_REUSEPORT not supported'", ")", "try", ":", "self", ".", "skt", ".", "bind", "(", "(", "self", ".", "address", ",", "int", "(", "self", ".", "port", ")", ")", ")", "except", "socket", ".", "error", "as", "msg", ":", "error_string", "=", "'Unable to bind to port {} on {}: {}'", ".", "format", "(", "self", ".", "port", ",", "self", ".", "address", ",", "msg", ")", "log", ".", "error", "(", "error_string", ",", "exc_info", "=", "True", ")", "raise", "BindException", "(", "error_string", ")", "log", ".", "debug", "(", "'Accepting max %d parallel connections'", ",", "self", ".", "max_clients", ")", "self", ".", "skt", ".", "listen", "(", "self", ".", "max_clients", ")", "self", ".", "thread_serve", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_serve_clients", ")", "self", ".", "thread_serve", ".", "start", "(", ")" ]
Start listening for messages.
[ "Start", "listening", "for", "messages", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/tcp.py#L96-L120
train
233,540
napalm-automation/napalm-logs
napalm_logs/listener/tcp.py
TCPListener.receive
def receive(self): ''' Return one message dequeued from the listen buffer. ''' while self.buffer.empty() and self.__up: # This sequence is skipped when the buffer is not empty. sleep_ms = random.randint(0, 1000) # log.debug('The message queue is empty, waiting %d miliseconds', sleep_ms) # disabled ^ as it was too noisy time.sleep(sleep_ms / 1000.0) if not self.buffer.empty(): return self.buffer.get(block=False) return '', ''
python
def receive(self): ''' Return one message dequeued from the listen buffer. ''' while self.buffer.empty() and self.__up: # This sequence is skipped when the buffer is not empty. sleep_ms = random.randint(0, 1000) # log.debug('The message queue is empty, waiting %d miliseconds', sleep_ms) # disabled ^ as it was too noisy time.sleep(sleep_ms / 1000.0) if not self.buffer.empty(): return self.buffer.get(block=False) return '', ''
[ "def", "receive", "(", "self", ")", ":", "while", "self", ".", "buffer", ".", "empty", "(", ")", "and", "self", ".", "__up", ":", "# This sequence is skipped when the buffer is not empty.", "sleep_ms", "=", "random", ".", "randint", "(", "0", ",", "1000", ")", "# log.debug('The message queue is empty, waiting %d miliseconds', sleep_ms)", "# disabled ^ as it was too noisy", "time", ".", "sleep", "(", "sleep_ms", "/", "1000.0", ")", "if", "not", "self", ".", "buffer", ".", "empty", "(", ")", ":", "return", "self", ".", "buffer", ".", "get", "(", "block", "=", "False", ")", "return", "''", ",", "''" ]
Return one message dequeued from the listen buffer.
[ "Return", "one", "message", "dequeued", "from", "the", "listen", "buffer", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/tcp.py#L122-L134
train
233,541
napalm-automation/napalm-logs
napalm_logs/listener/tcp.py
TCPListener.stop
def stop(self): ''' Closing the socket. ''' log.info('Stopping the TCP listener') self.__up = False try: self.skt.shutdown(socket.SHUT_RDWR) except socket.error: log.error('The following error may not be critical:', exc_info=True) self.skt.close()
python
def stop(self): ''' Closing the socket. ''' log.info('Stopping the TCP listener') self.__up = False try: self.skt.shutdown(socket.SHUT_RDWR) except socket.error: log.error('The following error may not be critical:', exc_info=True) self.skt.close()
[ "def", "stop", "(", "self", ")", ":", "log", ".", "info", "(", "'Stopping the TCP listener'", ")", "self", ".", "__up", "=", "False", "try", ":", "self", ".", "skt", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "except", "socket", ".", "error", ":", "log", ".", "error", "(", "'The following error may not be critical:'", ",", "exc_info", "=", "True", ")", "self", ".", "skt", ".", "close", "(", ")" ]
Closing the socket.
[ "Closing", "the", "socket", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener/tcp.py#L136-L146
train
233,542
napalm-automation/napalm-logs
napalm_logs/listener_proc.py
NapalmLogsListenerProc._setup_ipc
def _setup_ipc(self): ''' Setup the listener ICP pusher. ''' log.debug('Setting up the listener IPC pusher') self.ctx = zmq.Context() self.pub = self.ctx.socket(zmq.PUSH) self.pub.connect(LST_IPC_URL) log.debug('Setting HWM for the listener: %d', self.opts['hwm']) try: self.pub.setsockopt(zmq.HWM, self.opts['hwm']) # zmq 2 except AttributeError: # zmq 3 self.pub.setsockopt(zmq.SNDHWM, self.opts['hwm'])
python
def _setup_ipc(self): ''' Setup the listener ICP pusher. ''' log.debug('Setting up the listener IPC pusher') self.ctx = zmq.Context() self.pub = self.ctx.socket(zmq.PUSH) self.pub.connect(LST_IPC_URL) log.debug('Setting HWM for the listener: %d', self.opts['hwm']) try: self.pub.setsockopt(zmq.HWM, self.opts['hwm']) # zmq 2 except AttributeError: # zmq 3 self.pub.setsockopt(zmq.SNDHWM, self.opts['hwm'])
[ "def", "_setup_ipc", "(", "self", ")", ":", "log", ".", "debug", "(", "'Setting up the listener IPC pusher'", ")", "self", ".", "ctx", "=", "zmq", ".", "Context", "(", ")", "self", ".", "pub", "=", "self", ".", "ctx", ".", "socket", "(", "zmq", ".", "PUSH", ")", "self", ".", "pub", ".", "connect", "(", "LST_IPC_URL", ")", "log", ".", "debug", "(", "'Setting HWM for the listener: %d'", ",", "self", ".", "opts", "[", "'hwm'", "]", ")", "try", ":", "self", ".", "pub", ".", "setsockopt", "(", "zmq", ".", "HWM", ",", "self", ".", "opts", "[", "'hwm'", "]", ")", "# zmq 2", "except", "AttributeError", ":", "# zmq 3", "self", ".", "pub", ".", "setsockopt", "(", "zmq", ".", "SNDHWM", ",", "self", ".", "opts", "[", "'hwm'", "]", ")" ]
Setup the listener ICP pusher.
[ "Setup", "the", "listener", "ICP", "pusher", "." ]
4b89100a6e4f994aa004f3ea42a06dc803a7ccb0
https://github.com/napalm-automation/napalm-logs/blob/4b89100a6e4f994aa004f3ea42a06dc803a7ccb0/napalm_logs/listener_proc.py#L62-L76
train
233,543
poppy-project/pypot
pypot/utils/stoppablethread.py
make_update_loop
def make_update_loop(thread, update_func): """ Makes a run loop which calls an update function at a predefined frequency. """ while not thread.should_stop(): if thread.should_pause(): thread.wait_to_resume() start = time.time() if hasattr(thread, '_updated'): thread._updated.clear() update_func() if hasattr(thread, '_updated'): thread._updated.set() end = time.time() dt = thread.period - (end - start) if dt > 0: time.sleep(dt)
python
def make_update_loop(thread, update_func): """ Makes a run loop which calls an update function at a predefined frequency. """ while not thread.should_stop(): if thread.should_pause(): thread.wait_to_resume() start = time.time() if hasattr(thread, '_updated'): thread._updated.clear() update_func() if hasattr(thread, '_updated'): thread._updated.set() end = time.time() dt = thread.period - (end - start) if dt > 0: time.sleep(dt)
[ "def", "make_update_loop", "(", "thread", ",", "update_func", ")", ":", "while", "not", "thread", ".", "should_stop", "(", ")", ":", "if", "thread", ".", "should_pause", "(", ")", ":", "thread", ".", "wait_to_resume", "(", ")", "start", "=", "time", ".", "time", "(", ")", "if", "hasattr", "(", "thread", ",", "'_updated'", ")", ":", "thread", ".", "_updated", ".", "clear", "(", ")", "update_func", "(", ")", "if", "hasattr", "(", "thread", ",", "'_updated'", ")", ":", "thread", ".", "_updated", ".", "set", "(", ")", "end", "=", "time", ".", "time", "(", ")", "dt", "=", "thread", ".", "period", "-", "(", "end", "-", "start", ")", "if", "dt", ">", "0", ":", "time", ".", "sleep", "(", "dt", ")" ]
Makes a run loop which calls an update function at a predefined frequency.
[ "Makes", "a", "run", "loop", "which", "calls", "an", "update", "function", "at", "a", "predefined", "frequency", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/utils/stoppablethread.py#L166-L183
train
233,544
poppy-project/pypot
pypot/utils/stoppablethread.py
StoppableThread.start
def start(self): """ Start the run method as a new thread. It will first stop the thread if it is already running. """ if self.running: self.stop() self._thread = threading.Thread(target=self._wrapped_target) self._thread.daemon = True self._thread.start()
python
def start(self): """ Start the run method as a new thread. It will first stop the thread if it is already running. """ if self.running: self.stop() self._thread = threading.Thread(target=self._wrapped_target) self._thread.daemon = True self._thread.start()
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "running", ":", "self", ".", "stop", "(", ")", "self", ".", "_thread", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_wrapped_target", ")", "self", ".", "_thread", ".", "daemon", "=", "True", "self", ".", "_thread", ".", "start", "(", ")" ]
Start the run method as a new thread. It will first stop the thread if it is already running.
[ "Start", "the", "run", "method", "as", "a", "new", "thread", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/utils/stoppablethread.py#L33-L44
train
233,545
poppy-project/pypot
pypot/utils/stoppablethread.py
StoppableThread.wait_to_start
def wait_to_start(self, allow_failure=False): """ Wait for the thread to actually starts. """ self._started.wait() if self._crashed and not allow_failure: self._thread.join() raise RuntimeError('Setup failed, see {} Traceback' 'for details.'.format(self._thread.name))
python
def wait_to_start(self, allow_failure=False): """ Wait for the thread to actually starts. """ self._started.wait() if self._crashed and not allow_failure: self._thread.join() raise RuntimeError('Setup failed, see {} Traceback' 'for details.'.format(self._thread.name))
[ "def", "wait_to_start", "(", "self", ",", "allow_failure", "=", "False", ")", ":", "self", ".", "_started", ".", "wait", "(", ")", "if", "self", ".", "_crashed", "and", "not", "allow_failure", ":", "self", ".", "_thread", ".", "join", "(", ")", "raise", "RuntimeError", "(", "'Setup failed, see {} Traceback'", "'for details.'", ".", "format", "(", "self", ".", "_thread", ".", "name", ")", ")" ]
Wait for the thread to actually starts.
[ "Wait", "for", "the", "thread", "to", "actually", "starts", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/utils/stoppablethread.py#L82-L89
train
233,546
poppy-project/pypot
pypot/vrep/__init__.py
from_vrep
def from_vrep(config, vrep_host='127.0.0.1', vrep_port=19997, scene=None, tracked_objects=[], tracked_collisions=[], id=None, shared_vrep_io=None): """ Create a robot from a V-REP instance. :param config: robot configuration (either the path to the json or directly the dictionary) :type config: str or dict :param str vrep_host: host of the V-REP server :param int vrep_port: port of the V-REP server :param str scene: path to the V-REP scene to load and start :param list tracked_objects: list of V-REP dummy object to track :param list tracked_collisions: list of V-REP collision to track :param int id: robot id in simulator (useful when using a scene with multiple robots) :param vrep_io: use an already connected VrepIO (useful when using a scene with multiple robots) :type vrep_io: :class:`~pypot.vrep.io.VrepIO` This function tries to connect to a V-REP instance and expects to find motors with names corresponding as the ones found in the config. .. note:: The :class:`~pypot.robot.robot.Robot` returned will also provide a convenience reset_simulation method which resets the simulation and the robot position to its intial stance. .. note:: Using the same configuration, you should be able to switch from a real to a simulated robot just by switching from :func:`~pypot.robot.config.from_config` to :func:`~pypot.vrep.from_vrep`. For instance:: import json with open('my_config.json') as f: config = json.load(f) from pypot.robot import from_config from pypot.vrep import from_vrep real_robot = from_config(config) simulated_robot = from_vrep(config, '127.0.0.1', 19997, 'poppy.ttt') """ if shared_vrep_io is None: vrep_io = VrepIO(vrep_host, vrep_port) else: vrep_io = shared_vrep_io vreptime = vrep_time(vrep_io) pypot_time.time = vreptime.get_time pypot_time.sleep = vreptime.sleep if isinstance(config, basestring): with open(config) as f: config = json.load(f, object_pairs_hook=OrderedDict) motors = [motor_from_confignode(config, name) for name in config['motors'].keys()] vc = VrepController(vrep_io, scene, motors, id=id) vc._init_vrep_streaming() sensor_controllers = [] if tracked_objects: sensors = [ObjectTracker(name) for name in tracked_objects] vot = VrepObjectTracker(vrep_io, sensors) sensor_controllers.append(vot) if tracked_collisions: sensors = [VrepCollisionDetector(name) for name in tracked_collisions] vct = VrepCollisionTracker(vrep_io, sensors) sensor_controllers.append(vct) robot = Robot(motor_controllers=[vc], sensor_controllers=sensor_controllers) for m in robot.motors: m.goto_behavior = 'minjerk' init_pos = {m: m.goal_position for m in robot.motors} make_alias(config, robot) def start_simu(): vrep_io.start_simulation() for m, p in init_pos.iteritems(): m.goal_position = p vc.start() if tracked_objects: vot.start() if tracked_collisions: vct.start() while vrep_io.get_simulation_current_time() < 1.: sys_time.sleep(0.1) def stop_simu(): if tracked_objects: vot.stop() if tracked_collisions: vct.stop() vc.stop() vrep_io.stop_simulation() def reset_simu(): stop_simu() sys_time.sleep(0.5) start_simu() robot.start_simulation = start_simu robot.stop_simulation = stop_simu robot.reset_simulation = reset_simu def current_simulation_time(robot): return robot._controllers[0].io.get_simulation_current_time() Robot.current_simulation_time = property(lambda robot: current_simulation_time(robot)) def get_object_position(robot, object, relative_to_object=None): return vrep_io.get_object_position(object, relative_to_object) Robot.get_object_position = partial(get_object_position, robot) def get_object_orientation(robot, object, relative_to_object=None): return vrep_io.get_object_orientation(object, relative_to_object) Robot.get_object_orientation = partial(get_object_orientation, robot) return robot
python
def from_vrep(config, vrep_host='127.0.0.1', vrep_port=19997, scene=None, tracked_objects=[], tracked_collisions=[], id=None, shared_vrep_io=None): """ Create a robot from a V-REP instance. :param config: robot configuration (either the path to the json or directly the dictionary) :type config: str or dict :param str vrep_host: host of the V-REP server :param int vrep_port: port of the V-REP server :param str scene: path to the V-REP scene to load and start :param list tracked_objects: list of V-REP dummy object to track :param list tracked_collisions: list of V-REP collision to track :param int id: robot id in simulator (useful when using a scene with multiple robots) :param vrep_io: use an already connected VrepIO (useful when using a scene with multiple robots) :type vrep_io: :class:`~pypot.vrep.io.VrepIO` This function tries to connect to a V-REP instance and expects to find motors with names corresponding as the ones found in the config. .. note:: The :class:`~pypot.robot.robot.Robot` returned will also provide a convenience reset_simulation method which resets the simulation and the robot position to its intial stance. .. note:: Using the same configuration, you should be able to switch from a real to a simulated robot just by switching from :func:`~pypot.robot.config.from_config` to :func:`~pypot.vrep.from_vrep`. For instance:: import json with open('my_config.json') as f: config = json.load(f) from pypot.robot import from_config from pypot.vrep import from_vrep real_robot = from_config(config) simulated_robot = from_vrep(config, '127.0.0.1', 19997, 'poppy.ttt') """ if shared_vrep_io is None: vrep_io = VrepIO(vrep_host, vrep_port) else: vrep_io = shared_vrep_io vreptime = vrep_time(vrep_io) pypot_time.time = vreptime.get_time pypot_time.sleep = vreptime.sleep if isinstance(config, basestring): with open(config) as f: config = json.load(f, object_pairs_hook=OrderedDict) motors = [motor_from_confignode(config, name) for name in config['motors'].keys()] vc = VrepController(vrep_io, scene, motors, id=id) vc._init_vrep_streaming() sensor_controllers = [] if tracked_objects: sensors = [ObjectTracker(name) for name in tracked_objects] vot = VrepObjectTracker(vrep_io, sensors) sensor_controllers.append(vot) if tracked_collisions: sensors = [VrepCollisionDetector(name) for name in tracked_collisions] vct = VrepCollisionTracker(vrep_io, sensors) sensor_controllers.append(vct) robot = Robot(motor_controllers=[vc], sensor_controllers=sensor_controllers) for m in robot.motors: m.goto_behavior = 'minjerk' init_pos = {m: m.goal_position for m in robot.motors} make_alias(config, robot) def start_simu(): vrep_io.start_simulation() for m, p in init_pos.iteritems(): m.goal_position = p vc.start() if tracked_objects: vot.start() if tracked_collisions: vct.start() while vrep_io.get_simulation_current_time() < 1.: sys_time.sleep(0.1) def stop_simu(): if tracked_objects: vot.stop() if tracked_collisions: vct.stop() vc.stop() vrep_io.stop_simulation() def reset_simu(): stop_simu() sys_time.sleep(0.5) start_simu() robot.start_simulation = start_simu robot.stop_simulation = stop_simu robot.reset_simulation = reset_simu def current_simulation_time(robot): return robot._controllers[0].io.get_simulation_current_time() Robot.current_simulation_time = property(lambda robot: current_simulation_time(robot)) def get_object_position(robot, object, relative_to_object=None): return vrep_io.get_object_position(object, relative_to_object) Robot.get_object_position = partial(get_object_position, robot) def get_object_orientation(robot, object, relative_to_object=None): return vrep_io.get_object_orientation(object, relative_to_object) Robot.get_object_orientation = partial(get_object_orientation, robot) return robot
[ "def", "from_vrep", "(", "config", ",", "vrep_host", "=", "'127.0.0.1'", ",", "vrep_port", "=", "19997", ",", "scene", "=", "None", ",", "tracked_objects", "=", "[", "]", ",", "tracked_collisions", "=", "[", "]", ",", "id", "=", "None", ",", "shared_vrep_io", "=", "None", ")", ":", "if", "shared_vrep_io", "is", "None", ":", "vrep_io", "=", "VrepIO", "(", "vrep_host", ",", "vrep_port", ")", "else", ":", "vrep_io", "=", "shared_vrep_io", "vreptime", "=", "vrep_time", "(", "vrep_io", ")", "pypot_time", ".", "time", "=", "vreptime", ".", "get_time", "pypot_time", ".", "sleep", "=", "vreptime", ".", "sleep", "if", "isinstance", "(", "config", ",", "basestring", ")", ":", "with", "open", "(", "config", ")", "as", "f", ":", "config", "=", "json", ".", "load", "(", "f", ",", "object_pairs_hook", "=", "OrderedDict", ")", "motors", "=", "[", "motor_from_confignode", "(", "config", ",", "name", ")", "for", "name", "in", "config", "[", "'motors'", "]", ".", "keys", "(", ")", "]", "vc", "=", "VrepController", "(", "vrep_io", ",", "scene", ",", "motors", ",", "id", "=", "id", ")", "vc", ".", "_init_vrep_streaming", "(", ")", "sensor_controllers", "=", "[", "]", "if", "tracked_objects", ":", "sensors", "=", "[", "ObjectTracker", "(", "name", ")", "for", "name", "in", "tracked_objects", "]", "vot", "=", "VrepObjectTracker", "(", "vrep_io", ",", "sensors", ")", "sensor_controllers", ".", "append", "(", "vot", ")", "if", "tracked_collisions", ":", "sensors", "=", "[", "VrepCollisionDetector", "(", "name", ")", "for", "name", "in", "tracked_collisions", "]", "vct", "=", "VrepCollisionTracker", "(", "vrep_io", ",", "sensors", ")", "sensor_controllers", ".", "append", "(", "vct", ")", "robot", "=", "Robot", "(", "motor_controllers", "=", "[", "vc", "]", ",", "sensor_controllers", "=", "sensor_controllers", ")", "for", "m", "in", "robot", ".", "motors", ":", "m", ".", "goto_behavior", "=", "'minjerk'", "init_pos", "=", "{", "m", ":", "m", ".", "goal_position", "for", "m", "in", "robot", ".", "motors", "}", "make_alias", "(", "config", ",", "robot", ")", "def", "start_simu", "(", ")", ":", "vrep_io", ".", "start_simulation", "(", ")", "for", "m", ",", "p", "in", "init_pos", ".", "iteritems", "(", ")", ":", "m", ".", "goal_position", "=", "p", "vc", ".", "start", "(", ")", "if", "tracked_objects", ":", "vot", ".", "start", "(", ")", "if", "tracked_collisions", ":", "vct", ".", "start", "(", ")", "while", "vrep_io", ".", "get_simulation_current_time", "(", ")", "<", "1.", ":", "sys_time", ".", "sleep", "(", "0.1", ")", "def", "stop_simu", "(", ")", ":", "if", "tracked_objects", ":", "vot", ".", "stop", "(", ")", "if", "tracked_collisions", ":", "vct", ".", "stop", "(", ")", "vc", ".", "stop", "(", ")", "vrep_io", ".", "stop_simulation", "(", ")", "def", "reset_simu", "(", ")", ":", "stop_simu", "(", ")", "sys_time", ".", "sleep", "(", "0.5", ")", "start_simu", "(", ")", "robot", ".", "start_simulation", "=", "start_simu", "robot", ".", "stop_simulation", "=", "stop_simu", "robot", ".", "reset_simulation", "=", "reset_simu", "def", "current_simulation_time", "(", "robot", ")", ":", "return", "robot", ".", "_controllers", "[", "0", "]", ".", "io", ".", "get_simulation_current_time", "(", ")", "Robot", ".", "current_simulation_time", "=", "property", "(", "lambda", "robot", ":", "current_simulation_time", "(", "robot", ")", ")", "def", "get_object_position", "(", "robot", ",", "object", ",", "relative_to_object", "=", "None", ")", ":", "return", "vrep_io", ".", "get_object_position", "(", "object", ",", "relative_to_object", ")", "Robot", ".", "get_object_position", "=", "partial", "(", "get_object_position", ",", "robot", ")", "def", "get_object_orientation", "(", "robot", ",", "object", ",", "relative_to_object", "=", "None", ")", ":", "return", "vrep_io", ".", "get_object_orientation", "(", "object", ",", "relative_to_object", ")", "Robot", ".", "get_object_orientation", "=", "partial", "(", "get_object_orientation", ",", "robot", ")", "return", "robot" ]
Create a robot from a V-REP instance. :param config: robot configuration (either the path to the json or directly the dictionary) :type config: str or dict :param str vrep_host: host of the V-REP server :param int vrep_port: port of the V-REP server :param str scene: path to the V-REP scene to load and start :param list tracked_objects: list of V-REP dummy object to track :param list tracked_collisions: list of V-REP collision to track :param int id: robot id in simulator (useful when using a scene with multiple robots) :param vrep_io: use an already connected VrepIO (useful when using a scene with multiple robots) :type vrep_io: :class:`~pypot.vrep.io.VrepIO` This function tries to connect to a V-REP instance and expects to find motors with names corresponding as the ones found in the config. .. note:: The :class:`~pypot.robot.robot.Robot` returned will also provide a convenience reset_simulation method which resets the simulation and the robot position to its intial stance. .. note:: Using the same configuration, you should be able to switch from a real to a simulated robot just by switching from :func:`~pypot.robot.config.from_config` to :func:`~pypot.vrep.from_vrep`. For instance:: import json with open('my_config.json') as f: config = json.load(f) from pypot.robot import from_config from pypot.vrep import from_vrep real_robot = from_config(config) simulated_robot = from_vrep(config, '127.0.0.1', 19997, 'poppy.ttt')
[ "Create", "a", "robot", "from", "a", "V", "-", "REP", "instance", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/__init__.py#L52-L176
train
233,547
poppy-project/pypot
pypot/dynamixel/io/io.py
DxlIO.set_wheel_mode
def set_wheel_mode(self, ids): """ Sets the specified motors to wheel mode. """ self.set_control_mode(dict(zip(ids, itertools.repeat('wheel'))))
python
def set_wheel_mode(self, ids): """ Sets the specified motors to wheel mode. """ self.set_control_mode(dict(zip(ids, itertools.repeat('wheel'))))
[ "def", "set_wheel_mode", "(", "self", ",", "ids", ")", ":", "self", ".", "set_control_mode", "(", "dict", "(", "zip", "(", "ids", ",", "itertools", ".", "repeat", "(", "'wheel'", ")", ")", ")", ")" ]
Sets the specified motors to wheel mode.
[ "Sets", "the", "specified", "motors", "to", "wheel", "mode", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/io.py#L30-L32
train
233,548
poppy-project/pypot
pypot/dynamixel/io/io.py
DxlIO.set_joint_mode
def set_joint_mode(self, ids): """ Sets the specified motors to joint mode. """ self.set_control_mode(dict(zip(ids, itertools.repeat('joint'))))
python
def set_joint_mode(self, ids): """ Sets the specified motors to joint mode. """ self.set_control_mode(dict(zip(ids, itertools.repeat('joint'))))
[ "def", "set_joint_mode", "(", "self", ",", "ids", ")", ":", "self", ".", "set_control_mode", "(", "dict", "(", "zip", "(", "ids", ",", "itertools", ".", "repeat", "(", "'joint'", ")", ")", ")", ")" ]
Sets the specified motors to joint mode.
[ "Sets", "the", "specified", "motors", "to", "joint", "mode", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/io.py#L34-L36
train
233,549
poppy-project/pypot
pypot/dynamixel/io/io.py
DxlIO.set_angle_limit
def set_angle_limit(self, limit_for_id, **kwargs): """ Sets the angle limit to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if 'wheel' in self.get_control_mode(limit_for_id.keys()): raise ValueError('can not change the angle limit of a motor in wheel mode') if (0, 0) in limit_for_id.values(): raise ValueError('can not set limit to (0, 0)') self._set_angle_limit(limit_for_id, convert=convert)
python
def set_angle_limit(self, limit_for_id, **kwargs): """ Sets the angle limit to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if 'wheel' in self.get_control_mode(limit_for_id.keys()): raise ValueError('can not change the angle limit of a motor in wheel mode') if (0, 0) in limit_for_id.values(): raise ValueError('can not set limit to (0, 0)') self._set_angle_limit(limit_for_id, convert=convert)
[ "def", "set_angle_limit", "(", "self", ",", "limit_for_id", ",", "*", "*", "kwargs", ")", ":", "convert", "=", "kwargs", "[", "'convert'", "]", "if", "'convert'", "in", "kwargs", "else", "self", ".", "_convert", "if", "'wheel'", "in", "self", ".", "get_control_mode", "(", "limit_for_id", ".", "keys", "(", ")", ")", ":", "raise", "ValueError", "(", "'can not change the angle limit of a motor in wheel mode'", ")", "if", "(", "0", ",", "0", ")", "in", "limit_for_id", ".", "values", "(", ")", ":", "raise", "ValueError", "(", "'can not set limit to (0, 0)'", ")", "self", ".", "_set_angle_limit", "(", "limit_for_id", ",", "convert", "=", "convert", ")" ]
Sets the angle limit to the specified motors.
[ "Sets", "the", "angle", "limit", "to", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/io.py#L55-L65
train
233,550
poppy-project/pypot
pypot/robot/robot.py
Robot.close
def close(self): """ Cleans the robot by stopping synchronization and all controllers.""" self.stop_sync() [c.io.close() for c in self._controllers if c.io is not None]
python
def close(self): """ Cleans the robot by stopping synchronization and all controllers.""" self.stop_sync() [c.io.close() for c in self._controllers if c.io is not None]
[ "def", "close", "(", "self", ")", ":", "self", ".", "stop_sync", "(", ")", "[", "c", ".", "io", ".", "close", "(", ")", "for", "c", "in", "self", ".", "_controllers", "if", "c", ".", "io", "is", "not", "None", "]" ]
Cleans the robot by stopping synchronization and all controllers.
[ "Cleans", "the", "robot", "by", "stopping", "synchronization", "and", "all", "controllers", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/robot/robot.py#L51-L54
train
233,551
poppy-project/pypot
pypot/robot/robot.py
Robot.goto_position
def goto_position(self, position_for_motors, duration, control=None, wait=False): """ Moves a subset of the motors to a position within a specific duration. :param dict position_for_motors: which motors you want to move {motor_name: pos, motor_name: pos,...} :param float duration: duration of the move :param str control: control type ('dummy', 'minjerk') :param bool wait: whether or not to wait for the end of the move .. note::In case of dynamixel motors, the speed is automatically adjusted so the goal position is reached after the chosen duration. """ for i, (motor_name, position) in enumerate(position_for_motors.iteritems()): w = False if i < len(position_for_motors) - 1 else wait m = getattr(self, motor_name) m.goto_position(position, duration, control, wait=w)
python
def goto_position(self, position_for_motors, duration, control=None, wait=False): """ Moves a subset of the motors to a position within a specific duration. :param dict position_for_motors: which motors you want to move {motor_name: pos, motor_name: pos,...} :param float duration: duration of the move :param str control: control type ('dummy', 'minjerk') :param bool wait: whether or not to wait for the end of the move .. note::In case of dynamixel motors, the speed is automatically adjusted so the goal position is reached after the chosen duration. """ for i, (motor_name, position) in enumerate(position_for_motors.iteritems()): w = False if i < len(position_for_motors) - 1 else wait m = getattr(self, motor_name) m.goto_position(position, duration, control, wait=w)
[ "def", "goto_position", "(", "self", ",", "position_for_motors", ",", "duration", ",", "control", "=", "None", ",", "wait", "=", "False", ")", ":", "for", "i", ",", "(", "motor_name", ",", "position", ")", "in", "enumerate", "(", "position_for_motors", ".", "iteritems", "(", ")", ")", ":", "w", "=", "False", "if", "i", "<", "len", "(", "position_for_motors", ")", "-", "1", "else", "wait", "m", "=", "getattr", "(", "self", ",", "motor_name", ")", "m", ".", "goto_position", "(", "position", ",", "duration", ",", "control", ",", "wait", "=", "w", ")" ]
Moves a subset of the motors to a position within a specific duration. :param dict position_for_motors: which motors you want to move {motor_name: pos, motor_name: pos,...} :param float duration: duration of the move :param str control: control type ('dummy', 'minjerk') :param bool wait: whether or not to wait for the end of the move .. note::In case of dynamixel motors, the speed is automatically adjusted so the goal position is reached after the chosen duration.
[ "Moves", "a", "subset", "of", "the", "motors", "to", "a", "position", "within", "a", "specific", "duration", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/robot/robot.py#L126-L141
train
233,552
poppy-project/pypot
pypot/robot/robot.py
Robot.power_up
def power_up(self): """ Changes all settings to guarantee the motors will be used at their maximum power. """ for m in self.motors: m.compliant = False m.moving_speed = 0 m.torque_limit = 100.0
python
def power_up(self): """ Changes all settings to guarantee the motors will be used at their maximum power. """ for m in self.motors: m.compliant = False m.moving_speed = 0 m.torque_limit = 100.0
[ "def", "power_up", "(", "self", ")", ":", "for", "m", "in", "self", ".", "motors", ":", "m", ".", "compliant", "=", "False", "m", ".", "moving_speed", "=", "0", "m", ".", "torque_limit", "=", "100.0" ]
Changes all settings to guarantee the motors will be used at their maximum power.
[ "Changes", "all", "settings", "to", "guarantee", "the", "motors", "will", "be", "used", "at", "their", "maximum", "power", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/robot/robot.py#L143-L148
train
233,553
poppy-project/pypot
pypot/robot/robot.py
Robot.to_config
def to_config(self): """ Generates the config for the current robot. .. note:: The generated config should be used as a basis and must probably be modified. """ from ..dynamixel.controller import DxlController dxl_controllers = [c for c in self._controllers if isinstance(c, DxlController)] config = {} config['controllers'] = {} for i, c in enumerate(dxl_controllers): name = 'dxl_controller_{}'.format(i) config['controllers'][name] = { 'port': c.io.port, 'sync_read': c.io._sync_read, 'attached_motors': [m.name for m in c.motors], } config['motors'] = {} for m in self.motors: config['motors'][m.name] = { 'id': m.id, 'type': m.model, 'offset': m.offset, 'orientation': 'direct' if m.direct else 'indirect', 'angle_limit': m.angle_limit, } if m.angle_limit == (0, 0): config['motors']['wheel_mode'] = True config['motorgroups'] = {} return config
python
def to_config(self): """ Generates the config for the current robot. .. note:: The generated config should be used as a basis and must probably be modified. """ from ..dynamixel.controller import DxlController dxl_controllers = [c for c in self._controllers if isinstance(c, DxlController)] config = {} config['controllers'] = {} for i, c in enumerate(dxl_controllers): name = 'dxl_controller_{}'.format(i) config['controllers'][name] = { 'port': c.io.port, 'sync_read': c.io._sync_read, 'attached_motors': [m.name for m in c.motors], } config['motors'] = {} for m in self.motors: config['motors'][m.name] = { 'id': m.id, 'type': m.model, 'offset': m.offset, 'orientation': 'direct' if m.direct else 'indirect', 'angle_limit': m.angle_limit, } if m.angle_limit == (0, 0): config['motors']['wheel_mode'] = True config['motorgroups'] = {} return config
[ "def", "to_config", "(", "self", ")", ":", "from", ".", ".", "dynamixel", ".", "controller", "import", "DxlController", "dxl_controllers", "=", "[", "c", "for", "c", "in", "self", ".", "_controllers", "if", "isinstance", "(", "c", ",", "DxlController", ")", "]", "config", "=", "{", "}", "config", "[", "'controllers'", "]", "=", "{", "}", "for", "i", ",", "c", "in", "enumerate", "(", "dxl_controllers", ")", ":", "name", "=", "'dxl_controller_{}'", ".", "format", "(", "i", ")", "config", "[", "'controllers'", "]", "[", "name", "]", "=", "{", "'port'", ":", "c", ".", "io", ".", "port", ",", "'sync_read'", ":", "c", ".", "io", ".", "_sync_read", ",", "'attached_motors'", ":", "[", "m", ".", "name", "for", "m", "in", "c", ".", "motors", "]", ",", "}", "config", "[", "'motors'", "]", "=", "{", "}", "for", "m", "in", "self", ".", "motors", ":", "config", "[", "'motors'", "]", "[", "m", ".", "name", "]", "=", "{", "'id'", ":", "m", ".", "id", ",", "'type'", ":", "m", ".", "model", ",", "'offset'", ":", "m", ".", "offset", ",", "'orientation'", ":", "'direct'", "if", "m", ".", "direct", "else", "'indirect'", ",", "'angle_limit'", ":", "m", ".", "angle_limit", ",", "}", "if", "m", ".", "angle_limit", "==", "(", "0", ",", "0", ")", ":", "config", "[", "'motors'", "]", "[", "'wheel_mode'", "]", "=", "True", "config", "[", "'motorgroups'", "]", "=", "{", "}", "return", "config" ]
Generates the config for the current robot. .. note:: The generated config should be used as a basis and must probably be modified.
[ "Generates", "the", "config", "for", "the", "current", "robot", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/robot/robot.py#L150-L187
train
233,554
poppy-project/pypot
pypot/vrep/controller.py
VrepController.update
def update(self): """ Synchronization update loop. At each update all motor position are read from vrep and set to the motors. The motors target position are also send to v-rep. """ # Read all the angle limits h, _, l, _ = self.io.call_remote_api('simxGetObjectGroupData', remote_api.sim_object_joint_type, 16, streaming=True) limits4handle = {hh: (ll, lr) for hh, ll, lr in zip(h, l[::2], l[1::2])} for m in self.motors: tmax = torque_max[m.model] # Read values from V-REP and set them to the Motor p = round( rad2deg(self.io.get_motor_position(motor_name=self._motor_name(m))), 1) m.__dict__['present_position'] = p l = 100. * self.io.get_motor_force(motor_name=self._motor_name(m)) / tmax m.__dict__['present_load'] = l m.__dict__['_load_fifo'].append(abs(l)) m.__dict__['present_temperature'] = 25 + \ round(2.5 * sum(m.__dict__['_load_fifo']) / len(m.__dict__['_load_fifo']), 1) ll, lr = limits4handle[self.io._object_handles[self._motor_name(m)]] m.__dict__['lower_limit'] = rad2deg(ll) m.__dict__['upper_limit'] = rad2deg(ll) + rad2deg(lr) # Send new values from Motor to V-REP p = deg2rad(round(m.__dict__['goal_position'], 1)) self.io.set_motor_position(motor_name=self._motor_name(m), position=p) t = m.__dict__['torque_limit'] * tmax / 100. if m.__dict__['compliant']: t = 0. self.io.set_motor_force(motor_name=self._motor_name(m), force=t)
python
def update(self): """ Synchronization update loop. At each update all motor position are read from vrep and set to the motors. The motors target position are also send to v-rep. """ # Read all the angle limits h, _, l, _ = self.io.call_remote_api('simxGetObjectGroupData', remote_api.sim_object_joint_type, 16, streaming=True) limits4handle = {hh: (ll, lr) for hh, ll, lr in zip(h, l[::2], l[1::2])} for m in self.motors: tmax = torque_max[m.model] # Read values from V-REP and set them to the Motor p = round( rad2deg(self.io.get_motor_position(motor_name=self._motor_name(m))), 1) m.__dict__['present_position'] = p l = 100. * self.io.get_motor_force(motor_name=self._motor_name(m)) / tmax m.__dict__['present_load'] = l m.__dict__['_load_fifo'].append(abs(l)) m.__dict__['present_temperature'] = 25 + \ round(2.5 * sum(m.__dict__['_load_fifo']) / len(m.__dict__['_load_fifo']), 1) ll, lr = limits4handle[self.io._object_handles[self._motor_name(m)]] m.__dict__['lower_limit'] = rad2deg(ll) m.__dict__['upper_limit'] = rad2deg(ll) + rad2deg(lr) # Send new values from Motor to V-REP p = deg2rad(round(m.__dict__['goal_position'], 1)) self.io.set_motor_position(motor_name=self._motor_name(m), position=p) t = m.__dict__['torque_limit'] * tmax / 100. if m.__dict__['compliant']: t = 0. self.io.set_motor_force(motor_name=self._motor_name(m), force=t)
[ "def", "update", "(", "self", ")", ":", "# Read all the angle limits", "h", ",", "_", ",", "l", ",", "_", "=", "self", ".", "io", ".", "call_remote_api", "(", "'simxGetObjectGroupData'", ",", "remote_api", ".", "sim_object_joint_type", ",", "16", ",", "streaming", "=", "True", ")", "limits4handle", "=", "{", "hh", ":", "(", "ll", ",", "lr", ")", "for", "hh", ",", "ll", ",", "lr", "in", "zip", "(", "h", ",", "l", "[", ":", ":", "2", "]", ",", "l", "[", "1", ":", ":", "2", "]", ")", "}", "for", "m", "in", "self", ".", "motors", ":", "tmax", "=", "torque_max", "[", "m", ".", "model", "]", "# Read values from V-REP and set them to the Motor", "p", "=", "round", "(", "rad2deg", "(", "self", ".", "io", ".", "get_motor_position", "(", "motor_name", "=", "self", ".", "_motor_name", "(", "m", ")", ")", ")", ",", "1", ")", "m", ".", "__dict__", "[", "'present_position'", "]", "=", "p", "l", "=", "100.", "*", "self", ".", "io", ".", "get_motor_force", "(", "motor_name", "=", "self", ".", "_motor_name", "(", "m", ")", ")", "/", "tmax", "m", ".", "__dict__", "[", "'present_load'", "]", "=", "l", "m", ".", "__dict__", "[", "'_load_fifo'", "]", ".", "append", "(", "abs", "(", "l", ")", ")", "m", ".", "__dict__", "[", "'present_temperature'", "]", "=", "25", "+", "round", "(", "2.5", "*", "sum", "(", "m", ".", "__dict__", "[", "'_load_fifo'", "]", ")", "/", "len", "(", "m", ".", "__dict__", "[", "'_load_fifo'", "]", ")", ",", "1", ")", "ll", ",", "lr", "=", "limits4handle", "[", "self", ".", "io", ".", "_object_handles", "[", "self", ".", "_motor_name", "(", "m", ")", "]", "]", "m", ".", "__dict__", "[", "'lower_limit'", "]", "=", "rad2deg", "(", "ll", ")", "m", ".", "__dict__", "[", "'upper_limit'", "]", "=", "rad2deg", "(", "ll", ")", "+", "rad2deg", "(", "lr", ")", "# Send new values from Motor to V-REP", "p", "=", "deg2rad", "(", "round", "(", "m", ".", "__dict__", "[", "'goal_position'", "]", ",", "1", ")", ")", "self", ".", "io", ".", "set_motor_position", "(", "motor_name", "=", "self", ".", "_motor_name", "(", "m", ")", ",", "position", "=", "p", ")", "t", "=", "m", ".", "__dict__", "[", "'torque_limit'", "]", "*", "tmax", "/", "100.", "if", "m", ".", "__dict__", "[", "'compliant'", "]", ":", "t", "=", "0.", "self", ".", "io", ".", "set_motor_force", "(", "motor_name", "=", "self", ".", "_motor_name", "(", "m", ")", ",", "force", "=", "t", ")" ]
Synchronization update loop. At each update all motor position are read from vrep and set to the motors. The motors target position are also send to v-rep.
[ "Synchronization", "update", "loop", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/controller.py#L41-L82
train
233,555
poppy-project/pypot
pypot/vrep/controller.py
VrepObjectTracker.update
def update(self): """ Updates the position and orientation of the tracked objects. """ for s in self.sensors: s.position = self.io.get_object_position(object_name=s.name) s.orientation = self.io.get_object_orientation(object_name=s.name)
python
def update(self): """ Updates the position and orientation of the tracked objects. """ for s in self.sensors: s.position = self.io.get_object_position(object_name=s.name) s.orientation = self.io.get_object_orientation(object_name=s.name)
[ "def", "update", "(", "self", ")", ":", "for", "s", "in", "self", ".", "sensors", ":", "s", ".", "position", "=", "self", ".", "io", ".", "get_object_position", "(", "object_name", "=", "s", ".", "name", ")", "s", ".", "orientation", "=", "self", ".", "io", ".", "get_object_orientation", "(", "object_name", "=", "s", ".", "name", ")" ]
Updates the position and orientation of the tracked objects.
[ "Updates", "the", "position", "and", "orientation", "of", "the", "tracked", "objects", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/controller.py#L149-L153
train
233,556
poppy-project/pypot
pypot/vrep/controller.py
VrepCollisionTracker.update
def update(self): """ Update the state of the collision detectors. """ for s in self.sensors: s.colliding = self.io.get_collision_state(collision_name=s.name)
python
def update(self): """ Update the state of the collision detectors. """ for s in self.sensors: s.colliding = self.io.get_collision_state(collision_name=s.name)
[ "def", "update", "(", "self", ")", ":", "for", "s", "in", "self", ".", "sensors", ":", "s", ".", "colliding", "=", "self", ".", "io", ".", "get_collision_state", "(", "collision_name", "=", "s", ".", "name", ")" ]
Update the state of the collision detectors.
[ "Update", "the", "state", "of", "the", "collision", "detectors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/controller.py#L180-L184
train
233,557
poppy-project/pypot
pypot/kinematics.py
Link.get_transformation_matrix
def get_transformation_matrix(self, theta): """ Computes the homogeneous transformation matrix for this link. """ ct = numpy.cos(theta + self.theta) st = numpy.sin(theta + self.theta) ca = numpy.cos(self.alpha) sa = numpy.sin(self.alpha) return numpy.matrix(((ct, -st * ca, st * sa, self.a * ct), (st, ct * ca, -ct * sa, self.a * st), (0, sa, ca, self.d), (0, 0, 0, 1)))
python
def get_transformation_matrix(self, theta): """ Computes the homogeneous transformation matrix for this link. """ ct = numpy.cos(theta + self.theta) st = numpy.sin(theta + self.theta) ca = numpy.cos(self.alpha) sa = numpy.sin(self.alpha) return numpy.matrix(((ct, -st * ca, st * sa, self.a * ct), (st, ct * ca, -ct * sa, self.a * st), (0, sa, ca, self.d), (0, 0, 0, 1)))
[ "def", "get_transformation_matrix", "(", "self", ",", "theta", ")", ":", "ct", "=", "numpy", ".", "cos", "(", "theta", "+", "self", ".", "theta", ")", "st", "=", "numpy", ".", "sin", "(", "theta", "+", "self", ".", "theta", ")", "ca", "=", "numpy", ".", "cos", "(", "self", ".", "alpha", ")", "sa", "=", "numpy", ".", "sin", "(", "self", ".", "alpha", ")", "return", "numpy", ".", "matrix", "(", "(", "(", "ct", ",", "-", "st", "*", "ca", ",", "st", "*", "sa", ",", "self", ".", "a", "*", "ct", ")", ",", "(", "st", ",", "ct", "*", "ca", ",", "-", "ct", "*", "sa", ",", "self", ".", "a", "*", "st", ")", ",", "(", "0", ",", "sa", ",", "ca", ",", "self", ".", "d", ")", ",", "(", "0", ",", "0", ",", "0", ",", "1", ")", ")", ")" ]
Computes the homogeneous transformation matrix for this link.
[ "Computes", "the", "homogeneous", "transformation", "matrix", "for", "this", "link", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/kinematics.py#L27-L37
train
233,558
poppy-project/pypot
pypot/kinematics.py
Chain.forward_kinematics
def forward_kinematics(self, q): """ Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n) """ q = numpy.array(q).flatten() if len(q) != len(self.links): raise ValueError('q must contain as element as the number of links') tr = self.base.copy() l = [] for link, theta in zip(self.links, q): tr = tr * link.get_transformation_matrix(theta) l.append(tr) tr = tr * self.tool l.append(tr) return tr, numpy.asarray(l)
python
def forward_kinematics(self, q): """ Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n) """ q = numpy.array(q).flatten() if len(q) != len(self.links): raise ValueError('q must contain as element as the number of links') tr = self.base.copy() l = [] for link, theta in zip(self.links, q): tr = tr * link.get_transformation_matrix(theta) l.append(tr) tr = tr * self.tool l.append(tr) return tr, numpy.asarray(l)
[ "def", "forward_kinematics", "(", "self", ",", "q", ")", ":", "q", "=", "numpy", ".", "array", "(", "q", ")", ".", "flatten", "(", ")", "if", "len", "(", "q", ")", "!=", "len", "(", "self", ".", "links", ")", ":", "raise", "ValueError", "(", "'q must contain as element as the number of links'", ")", "tr", "=", "self", ".", "base", ".", "copy", "(", ")", "l", "=", "[", "]", "for", "link", ",", "theta", "in", "zip", "(", "self", ".", "links", ",", "q", ")", ":", "tr", "=", "tr", "*", "link", ".", "get_transformation_matrix", "(", "theta", ")", "l", ".", "append", "(", "tr", ")", "tr", "=", "tr", "*", "self", ".", "tool", "l", ".", "append", "(", "tr", ")", "return", "tr", ",", "numpy", ".", "asarray", "(", "l", ")" ]
Computes the homogeneous transformation matrix of the end effector of the chain. :param vector q: vector of the joint angles (theta 1, theta 2, ..., theta n)
[ "Computes", "the", "homogeneous", "transformation", "matrix", "of", "the", "end", "effector", "of", "the", "chain", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/kinematics.py#L51-L73
train
233,559
poppy-project/pypot
pypot/kinematics.py
Chain.inverse_kinematics
def inverse_kinematics(self, end_effector_transformation, q=None, max_iter=1000, tolerance=0.05, mask=numpy.ones(6), use_pinv=False): """ Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float tolerance: tolerance before convergence :param mask: specify the cartesian DOF that will be ignore (in the case of a chain with less than 6 joints). :rtype: vector of the joint angles (theta 1, theta 2, ..., theta n) """ if q is None: q = numpy.zeros((len(self.links), 1)) q = numpy.matrix(q.reshape(-1, 1)) best_e = numpy.ones(6) * numpy.inf best_q = None alpha = 1.0 for _ in range(max_iter): e = numpy.multiply(transform_difference(self.forward_kinematics(q)[0], end_effector_transformation), mask) d = numpy.linalg.norm(e) if d < numpy.linalg.norm(best_e): best_e = e.copy() best_q = q.copy() alpha *= 2.0 ** (1.0 / 8.0) else: q = best_q.copy() e = best_e.copy() alpha *= 0.5 if use_pinv: dq = numpy.linalg.pinv(self._jacob0(q)) * e.reshape((-1, 1)) else: dq = self._jacob0(q).T * e.reshape((-1, 1)) q += alpha * dq # d = numpy.linalg.norm(dq) if d < tolerance: return q else: raise ValueError('could not converge d={}'.format(numpy.linalg.norm(best_e)))
python
def inverse_kinematics(self, end_effector_transformation, q=None, max_iter=1000, tolerance=0.05, mask=numpy.ones(6), use_pinv=False): """ Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float tolerance: tolerance before convergence :param mask: specify the cartesian DOF that will be ignore (in the case of a chain with less than 6 joints). :rtype: vector of the joint angles (theta 1, theta 2, ..., theta n) """ if q is None: q = numpy.zeros((len(self.links), 1)) q = numpy.matrix(q.reshape(-1, 1)) best_e = numpy.ones(6) * numpy.inf best_q = None alpha = 1.0 for _ in range(max_iter): e = numpy.multiply(transform_difference(self.forward_kinematics(q)[0], end_effector_transformation), mask) d = numpy.linalg.norm(e) if d < numpy.linalg.norm(best_e): best_e = e.copy() best_q = q.copy() alpha *= 2.0 ** (1.0 / 8.0) else: q = best_q.copy() e = best_e.copy() alpha *= 0.5 if use_pinv: dq = numpy.linalg.pinv(self._jacob0(q)) * e.reshape((-1, 1)) else: dq = self._jacob0(q).T * e.reshape((-1, 1)) q += alpha * dq # d = numpy.linalg.norm(dq) if d < tolerance: return q else: raise ValueError('could not converge d={}'.format(numpy.linalg.norm(best_e)))
[ "def", "inverse_kinematics", "(", "self", ",", "end_effector_transformation", ",", "q", "=", "None", ",", "max_iter", "=", "1000", ",", "tolerance", "=", "0.05", ",", "mask", "=", "numpy", ".", "ones", "(", "6", ")", ",", "use_pinv", "=", "False", ")", ":", "if", "q", "is", "None", ":", "q", "=", "numpy", ".", "zeros", "(", "(", "len", "(", "self", ".", "links", ")", ",", "1", ")", ")", "q", "=", "numpy", ".", "matrix", "(", "q", ".", "reshape", "(", "-", "1", ",", "1", ")", ")", "best_e", "=", "numpy", ".", "ones", "(", "6", ")", "*", "numpy", ".", "inf", "best_q", "=", "None", "alpha", "=", "1.0", "for", "_", "in", "range", "(", "max_iter", ")", ":", "e", "=", "numpy", ".", "multiply", "(", "transform_difference", "(", "self", ".", "forward_kinematics", "(", "q", ")", "[", "0", "]", ",", "end_effector_transformation", ")", ",", "mask", ")", "d", "=", "numpy", ".", "linalg", ".", "norm", "(", "e", ")", "if", "d", "<", "numpy", ".", "linalg", ".", "norm", "(", "best_e", ")", ":", "best_e", "=", "e", ".", "copy", "(", ")", "best_q", "=", "q", ".", "copy", "(", ")", "alpha", "*=", "2.0", "**", "(", "1.0", "/", "8.0", ")", "else", ":", "q", "=", "best_q", ".", "copy", "(", ")", "e", "=", "best_e", ".", "copy", "(", ")", "alpha", "*=", "0.5", "if", "use_pinv", ":", "dq", "=", "numpy", ".", "linalg", ".", "pinv", "(", "self", ".", "_jacob0", "(", "q", ")", ")", "*", "e", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "else", ":", "dq", "=", "self", ".", "_jacob0", "(", "q", ")", ".", "T", "*", "e", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "q", "+=", "alpha", "*", "dq", "# d = numpy.linalg.norm(dq)", "if", "d", "<", "tolerance", ":", "return", "q", "else", ":", "raise", "ValueError", "(", "'could not converge d={}'", ".", "format", "(", "numpy", ".", "linalg", ".", "norm", "(", "best_e", ")", ")", ")" ]
Computes the joint angles corresponding to the end effector transformation. :param end_effector_transformation: the end effector homogeneous transformation matrix :param vector q: initial estimate of the joint angles :param int max_iter: maximum number of iteration :param float tolerance: tolerance before convergence :param mask: specify the cartesian DOF that will be ignore (in the case of a chain with less than 6 joints). :rtype: vector of the joint angles (theta 1, theta 2, ..., theta n)
[ "Computes", "the", "joint", "angles", "corresponding", "to", "the", "end", "effector", "transformation", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/kinematics.py#L75-L122
train
233,560
poppy-project/pypot
pypot/dynamixel/__init__.py
_get_available_ports
def _get_available_ports(): """ Tries to find the available serial ports on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*') elif sys.platform.lower() == 'cygwin': return glob.glob('/dev/com*') elif platform.system() == 'Windows': import _winreg import itertools ports = [] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) for i in itertools.count(): try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports else: raise EnvironmentError('{} is an unsupported platform, cannot find serial ports !'.format(platform.system())) return []
python
def _get_available_ports(): """ Tries to find the available serial ports on your system. """ if platform.system() == 'Darwin': return glob.glob('/dev/tty.usb*') elif platform.system() == 'Linux': return glob.glob('/dev/ttyACM*') + glob.glob('/dev/ttyUSB*') + glob.glob('/dev/ttyAMA*') elif sys.platform.lower() == 'cygwin': return glob.glob('/dev/com*') elif platform.system() == 'Windows': import _winreg import itertools ports = [] path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' key = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, path) for i in itertools.count(): try: ports.append(str(_winreg.EnumValue(key, i)[1])) except WindowsError: return ports else: raise EnvironmentError('{} is an unsupported platform, cannot find serial ports !'.format(platform.system())) return []
[ "def", "_get_available_ports", "(", ")", ":", "if", "platform", ".", "system", "(", ")", "==", "'Darwin'", ":", "return", "glob", ".", "glob", "(", "'/dev/tty.usb*'", ")", "elif", "platform", ".", "system", "(", ")", "==", "'Linux'", ":", "return", "glob", ".", "glob", "(", "'/dev/ttyACM*'", ")", "+", "glob", ".", "glob", "(", "'/dev/ttyUSB*'", ")", "+", "glob", ".", "glob", "(", "'/dev/ttyAMA*'", ")", "elif", "sys", ".", "platform", ".", "lower", "(", ")", "==", "'cygwin'", ":", "return", "glob", ".", "glob", "(", "'/dev/com*'", ")", "elif", "platform", ".", "system", "(", ")", "==", "'Windows'", ":", "import", "_winreg", "import", "itertools", "ports", "=", "[", "]", "path", "=", "'HARDWARE\\\\DEVICEMAP\\\\SERIALCOMM'", "key", "=", "_winreg", ".", "OpenKey", "(", "_winreg", ".", "HKEY_LOCAL_MACHINE", ",", "path", ")", "for", "i", "in", "itertools", ".", "count", "(", ")", ":", "try", ":", "ports", ".", "append", "(", "str", "(", "_winreg", ".", "EnumValue", "(", "key", ",", "i", ")", "[", "1", "]", ")", ")", "except", "WindowsError", ":", "return", "ports", "else", ":", "raise", "EnvironmentError", "(", "'{} is an unsupported platform, cannot find serial ports !'", ".", "format", "(", "platform", ".", "system", "(", ")", ")", ")", "return", "[", "]" ]
Tries to find the available serial ports on your system.
[ "Tries", "to", "find", "the", "available", "serial", "ports", "on", "your", "system", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/__init__.py#L20-L46
train
233,561
poppy-project/pypot
pypot/dynamixel/__init__.py
find_port
def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned. """ ids_founds = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): try: with DxlIOCls(port) as dxl: _ids_founds = dxl.scan(ids) ids_founds += _ids_founds if strict and len(_ids_founds) == len(ids): return port if not strict and len(_ids_founds) >= len(ids) / 2: logger.warning('Missing ids: {}'.format(ids, list(set(ids) - set(_ids_founds)))) return port if len(ids_founds) > 0: logger.warning('Port:{} ids found:{}'.format(port, _ids_founds)) except DxlError: logger.warning('DxlError on port {}'.format(port)) continue raise IndexError('No suitable port found for ids {}. These ids are missing {} !'.format( ids, list(set(ids) - set(ids_founds))))
python
def find_port(ids, strict=True): """ Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned. """ ids_founds = [] for port in get_available_ports(): for DxlIOCls in (DxlIO, Dxl320IO): try: with DxlIOCls(port) as dxl: _ids_founds = dxl.scan(ids) ids_founds += _ids_founds if strict and len(_ids_founds) == len(ids): return port if not strict and len(_ids_founds) >= len(ids) / 2: logger.warning('Missing ids: {}'.format(ids, list(set(ids) - set(_ids_founds)))) return port if len(ids_founds) > 0: logger.warning('Port:{} ids found:{}'.format(port, _ids_founds)) except DxlError: logger.warning('DxlError on port {}'.format(port)) continue raise IndexError('No suitable port found for ids {}. These ids are missing {} !'.format( ids, list(set(ids) - set(ids_founds))))
[ "def", "find_port", "(", "ids", ",", "strict", "=", "True", ")", ":", "ids_founds", "=", "[", "]", "for", "port", "in", "get_available_ports", "(", ")", ":", "for", "DxlIOCls", "in", "(", "DxlIO", ",", "Dxl320IO", ")", ":", "try", ":", "with", "DxlIOCls", "(", "port", ")", "as", "dxl", ":", "_ids_founds", "=", "dxl", ".", "scan", "(", "ids", ")", "ids_founds", "+=", "_ids_founds", "if", "strict", "and", "len", "(", "_ids_founds", ")", "==", "len", "(", "ids", ")", ":", "return", "port", "if", "not", "strict", "and", "len", "(", "_ids_founds", ")", ">=", "len", "(", "ids", ")", "/", "2", ":", "logger", ".", "warning", "(", "'Missing ids: {}'", ".", "format", "(", "ids", ",", "list", "(", "set", "(", "ids", ")", "-", "set", "(", "_ids_founds", ")", ")", ")", ")", "return", "port", "if", "len", "(", "ids_founds", ")", ">", "0", ":", "logger", ".", "warning", "(", "'Port:{} ids found:{}'", ".", "format", "(", "port", ",", "_ids_founds", ")", ")", "except", "DxlError", ":", "logger", ".", "warning", "(", "'DxlError on port {}'", ".", "format", "(", "port", ")", ")", "continue", "raise", "IndexError", "(", "'No suitable port found for ids {}. These ids are missing {} !'", ".", "format", "(", "ids", ",", "list", "(", "set", "(", "ids", ")", "-", "set", "(", "ids_founds", ")", ")", ")", ")" ]
Find the port with the specified attached motor ids. :param list ids: list of motor ids to find :param bool strict: specify if all ids should be find (when set to False, only half motor must be found) .. warning:: If two (or more) ports are attached to the same list of motor ids the first match will be returned.
[ "Find", "the", "port", "with", "the", "specified", "attached", "motor", "ids", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/__init__.py#L74-L106
train
233,562
poppy-project/pypot
pypot/sensor/depth/sonar.py
Sonar._filter
def _filter(self, data): """ Apply a filter to reduce noisy data. Return the median value of a heap of data. """ filtered_data = [] for queue, data in zip(self._raw_data_queues, data): queue.append(data) filtered_data.append(numpy.median(queue)) return filtered_data
python
def _filter(self, data): """ Apply a filter to reduce noisy data. Return the median value of a heap of data. """ filtered_data = [] for queue, data in zip(self._raw_data_queues, data): queue.append(data) filtered_data.append(numpy.median(queue)) return filtered_data
[ "def", "_filter", "(", "self", ",", "data", ")", ":", "filtered_data", "=", "[", "]", "for", "queue", ",", "data", "in", "zip", "(", "self", ".", "_raw_data_queues", ",", "data", ")", ":", "queue", ".", "append", "(", "data", ")", "filtered_data", ".", "append", "(", "numpy", ".", "median", "(", "queue", ")", ")", "return", "filtered_data" ]
Apply a filter to reduce noisy data. Return the median value of a heap of data.
[ "Apply", "a", "filter", "to", "reduce", "noisy", "data", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/sensor/depth/sonar.py#L87-L98
train
233,563
poppy-project/pypot
pypot/dynamixel/syncloop.py
MetaDxlController.setup
def setup(self): """ Starts all the synchronization loops. """ [c.start() for c in self.controllers] [c.wait_to_start() for c in self.controllers]
python
def setup(self): """ Starts all the synchronization loops. """ [c.start() for c in self.controllers] [c.wait_to_start() for c in self.controllers]
[ "def", "setup", "(", "self", ")", ":", "[", "c", ".", "start", "(", ")", "for", "c", "in", "self", ".", "controllers", "]", "[", "c", ".", "wait_to_start", "(", ")", "for", "c", "in", "self", ".", "controllers", "]" ]
Starts all the synchronization loops.
[ "Starts", "all", "the", "synchronization", "loops", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/syncloop.py#L20-L23
train
233,564
poppy-project/pypot
pypot/creatures/ik.py
IKChain.from_poppy_creature
def from_poppy_creature(cls, poppy, motors, passiv, tip, reversed_motors=[]): """ Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x, y, z] translation of the tip of the chain (in meters) :param list reversed_motors: list of motors that should be manually reversed (due to a problem in the URDF?) """ chain_elements = get_chain_from_joints(poppy.urdf_file, [m.name for m in motors]) activ = [False] + [m not in passiv for m in motors] + [True] chain = cls.from_urdf_file(poppy.urdf_file, base_elements=chain_elements, last_link_vector=tip, active_links_mask=activ) chain.motors = [getattr(poppy, l.name) for l in chain.links[1:-1]] for m, l in zip(chain.motors, chain.links[1:-1]): # Force an access to angle limit to retrieve real values # This is quite an ugly fix and should be handled better m.angle_limit bounds = m.__dict__['lower_limit'], m.__dict__['upper_limit'] l.bounds = tuple(map(rad2deg, bounds)) chain._reversed = array([(-1 if m in reversed_motors else 1) for m in motors]) return chain
python
def from_poppy_creature(cls, poppy, motors, passiv, tip, reversed_motors=[]): """ Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x, y, z] translation of the tip of the chain (in meters) :param list reversed_motors: list of motors that should be manually reversed (due to a problem in the URDF?) """ chain_elements = get_chain_from_joints(poppy.urdf_file, [m.name for m in motors]) activ = [False] + [m not in passiv for m in motors] + [True] chain = cls.from_urdf_file(poppy.urdf_file, base_elements=chain_elements, last_link_vector=tip, active_links_mask=activ) chain.motors = [getattr(poppy, l.name) for l in chain.links[1:-1]] for m, l in zip(chain.motors, chain.links[1:-1]): # Force an access to angle limit to retrieve real values # This is quite an ugly fix and should be handled better m.angle_limit bounds = m.__dict__['lower_limit'], m.__dict__['upper_limit'] l.bounds = tuple(map(rad2deg, bounds)) chain._reversed = array([(-1 if m in reversed_motors else 1) for m in motors]) return chain
[ "def", "from_poppy_creature", "(", "cls", ",", "poppy", ",", "motors", ",", "passiv", ",", "tip", ",", "reversed_motors", "=", "[", "]", ")", ":", "chain_elements", "=", "get_chain_from_joints", "(", "poppy", ".", "urdf_file", ",", "[", "m", ".", "name", "for", "m", "in", "motors", "]", ")", "activ", "=", "[", "False", "]", "+", "[", "m", "not", "in", "passiv", "for", "m", "in", "motors", "]", "+", "[", "True", "]", "chain", "=", "cls", ".", "from_urdf_file", "(", "poppy", ".", "urdf_file", ",", "base_elements", "=", "chain_elements", ",", "last_link_vector", "=", "tip", ",", "active_links_mask", "=", "activ", ")", "chain", ".", "motors", "=", "[", "getattr", "(", "poppy", ",", "l", ".", "name", ")", "for", "l", "in", "chain", ".", "links", "[", "1", ":", "-", "1", "]", "]", "for", "m", ",", "l", "in", "zip", "(", "chain", ".", "motors", ",", "chain", ".", "links", "[", "1", ":", "-", "1", "]", ")", ":", "# Force an access to angle limit to retrieve real values", "# This is quite an ugly fix and should be handled better", "m", ".", "angle_limit", "bounds", "=", "m", ".", "__dict__", "[", "'lower_limit'", "]", ",", "m", ".", "__dict__", "[", "'upper_limit'", "]", "l", ".", "bounds", "=", "tuple", "(", "map", "(", "rad2deg", ",", "bounds", ")", ")", "chain", ".", "_reversed", "=", "array", "(", "[", "(", "-", "1", "if", "m", "in", "reversed_motors", "else", "1", ")", "for", "m", "in", "motors", "]", ")", "return", "chain" ]
Creates an kinematic chain from motors of a Poppy Creature. :param poppy: PoppyCreature used :param list motors: list of all motors that composed the kinematic chain :param list passiv: list of motors which are passiv in the chain (they will not move) :param list tip: [x, y, z] translation of the tip of the chain (in meters) :param list reversed_motors: list of motors that should be manually reversed (due to a problem in the URDF?)
[ "Creates", "an", "kinematic", "chain", "from", "motors", "of", "a", "Poppy", "Creature", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L14-L48
train
233,565
poppy-project/pypot
pypot/creatures/ik.py
IKChain.goto
def goto(self, position, duration, wait=False, accurate=False): """ Goes to a given cartesian position. :param list position: [x, y, z] representing the target position (in meters) :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ if len(position) != 3: raise ValueError('Position should be a list [x, y, z]!') M = eye(4) M[:3, 3] = position self._goto(M, duration, wait, accurate)
python
def goto(self, position, duration, wait=False, accurate=False): """ Goes to a given cartesian position. :param list position: [x, y, z] representing the target position (in meters) :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ if len(position) != 3: raise ValueError('Position should be a list [x, y, z]!') M = eye(4) M[:3, 3] = position self._goto(M, duration, wait, accurate)
[ "def", "goto", "(", "self", ",", "position", ",", "duration", ",", "wait", "=", "False", ",", "accurate", "=", "False", ")", ":", "if", "len", "(", "position", ")", "!=", "3", ":", "raise", "ValueError", "(", "'Position should be a list [x, y, z]!'", ")", "M", "=", "eye", "(", "4", ")", "M", "[", ":", "3", ",", "3", "]", "=", "position", "self", ".", "_goto", "(", "M", ",", "duration", ",", "wait", ",", "accurate", ")" ]
Goes to a given cartesian position. :param list position: [x, y, z] representing the target position (in meters) :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version.
[ "Goes", "to", "a", "given", "cartesian", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L61-L75
train
233,566
poppy-project/pypot
pypot/creatures/ik.py
IKChain._goto
def _goto(self, pose, duration, wait, accurate): """ Goes to a given cartesian pose. :param matrix pose: homogeneous matrix representing the target position :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ kwargs = {} if not accurate: kwargs['max_iter'] = 3 q0 = self.convert_to_ik_angles(self.joints_position) q = self.inverse_kinematics(pose, initial_position=q0, **kwargs) joints = self.convert_from_ik_angles(q) last = self.motors[-1] for m, pos in list(zip(self.motors, joints)): m.goto_position(pos, duration, wait=False if m != last else wait)
python
def _goto(self, pose, duration, wait, accurate): """ Goes to a given cartesian pose. :param matrix pose: homogeneous matrix representing the target position :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version. """ kwargs = {} if not accurate: kwargs['max_iter'] = 3 q0 = self.convert_to_ik_angles(self.joints_position) q = self.inverse_kinematics(pose, initial_position=q0, **kwargs) joints = self.convert_from_ik_angles(q) last = self.motors[-1] for m, pos in list(zip(self.motors, joints)): m.goto_position(pos, duration, wait=False if m != last else wait)
[ "def", "_goto", "(", "self", ",", "pose", ",", "duration", ",", "wait", ",", "accurate", ")", ":", "kwargs", "=", "{", "}", "if", "not", "accurate", ":", "kwargs", "[", "'max_iter'", "]", "=", "3", "q0", "=", "self", ".", "convert_to_ik_angles", "(", "self", ".", "joints_position", ")", "q", "=", "self", ".", "inverse_kinematics", "(", "pose", ",", "initial_position", "=", "q0", ",", "*", "*", "kwargs", ")", "joints", "=", "self", ".", "convert_from_ik_angles", "(", "q", ")", "last", "=", "self", ".", "motors", "[", "-", "1", "]", "for", "m", ",", "pos", "in", "list", "(", "zip", "(", "self", ".", "motors", ",", "joints", ")", ")", ":", "m", ".", "goto_position", "(", "pos", ",", "duration", ",", "wait", "=", "False", "if", "m", "!=", "last", "else", "wait", ")" ]
Goes to a given cartesian pose. :param matrix pose: homogeneous matrix representing the target position :param float duration: move duration :param bool wait: whether to wait for the end of the move :param bool accurate: trade-off between accurate solution and computation time. By default, use the not so accurate but fast version.
[ "Goes", "to", "a", "given", "cartesian", "pose", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L77-L99
train
233,567
poppy-project/pypot
pypot/creatures/ik.py
IKChain.convert_to_ik_angles
def convert_to_ik_angles(self, joints): """ Convert from poppy representation to IKPY internal representation. """ if len(joints) != len(self.motors): raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors))) raw_joints = [(j + m.offset) * (1 if m.direct else -1) for j, m in zip(joints, self.motors)] raw_joints *= self._reversed return [0] + [deg2rad(j) for j in raw_joints] + [0]
python
def convert_to_ik_angles(self, joints): """ Convert from poppy representation to IKPY internal representation. """ if len(joints) != len(self.motors): raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors))) raw_joints = [(j + m.offset) * (1 if m.direct else -1) for j, m in zip(joints, self.motors)] raw_joints *= self._reversed return [0] + [deg2rad(j) for j in raw_joints] + [0]
[ "def", "convert_to_ik_angles", "(", "self", ",", "joints", ")", ":", "if", "len", "(", "joints", ")", "!=", "len", "(", "self", ".", "motors", ")", ":", "raise", "ValueError", "(", "'Incompatible data, len(joints) should be {}!'", ".", "format", "(", "len", "(", "self", ".", "motors", ")", ")", ")", "raw_joints", "=", "[", "(", "j", "+", "m", ".", "offset", ")", "*", "(", "1", "if", "m", ".", "direct", "else", "-", "1", ")", "for", "j", ",", "m", "in", "zip", "(", "joints", ",", "self", ".", "motors", ")", "]", "raw_joints", "*=", "self", ".", "_reversed", "return", "[", "0", "]", "+", "[", "deg2rad", "(", "j", ")", "for", "j", "in", "raw_joints", "]", "+", "[", "0", "]" ]
Convert from poppy representation to IKPY internal representation.
[ "Convert", "from", "poppy", "representation", "to", "IKPY", "internal", "representation", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L101-L111
train
233,568
poppy-project/pypot
pypot/creatures/ik.py
IKChain.convert_from_ik_angles
def convert_from_ik_angles(self, joints): """ Convert from IKPY internal representation to poppy representation. """ if len(joints) != len(self.motors) + 2: raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors) + 2)) joints = [rad2deg(j) for j in joints[1:-1]] joints *= self._reversed return [(j * (1 if m.direct else -1)) - m.offset for j, m in zip(joints, self.motors)]
python
def convert_from_ik_angles(self, joints): """ Convert from IKPY internal representation to poppy representation. """ if len(joints) != len(self.motors) + 2: raise ValueError('Incompatible data, len(joints) should be {}!'.format(len(self.motors) + 2)) joints = [rad2deg(j) for j in joints[1:-1]] joints *= self._reversed return [(j * (1 if m.direct else -1)) - m.offset for j, m in zip(joints, self.motors)]
[ "def", "convert_from_ik_angles", "(", "self", ",", "joints", ")", ":", "if", "len", "(", "joints", ")", "!=", "len", "(", "self", ".", "motors", ")", "+", "2", ":", "raise", "ValueError", "(", "'Incompatible data, len(joints) should be {}!'", ".", "format", "(", "len", "(", "self", ".", "motors", ")", "+", "2", ")", ")", "joints", "=", "[", "rad2deg", "(", "j", ")", "for", "j", "in", "joints", "[", "1", ":", "-", "1", "]", "]", "joints", "*=", "self", ".", "_reversed", "return", "[", "(", "j", "*", "(", "1", "if", "m", ".", "direct", "else", "-", "1", ")", ")", "-", "m", ".", "offset", "for", "j", ",", "m", "in", "zip", "(", "joints", ",", "self", ".", "motors", ")", "]" ]
Convert from IKPY internal representation to poppy representation.
[ "Convert", "from", "IKPY", "internal", "representation", "to", "poppy", "representation", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/creatures/ik.py#L113-L122
train
233,569
poppy-project/pypot
pypot/dynamixel/io/io_320.py
Dxl320IO.factory_reset
def factory_reset(self, ids, except_ids=False, except_baudrate_and_ids=False): """ Reset all motors on the bus to their factory default settings. """ mode = (0x02 if except_baudrate_and_ids else 0x01 if except_ids else 0xFF) for id in ids: try: self._send_packet(self._protocol.DxlResetPacket(id, mode)) except (DxlTimeoutError, DxlCommunicationError): pass
python
def factory_reset(self, ids, except_ids=False, except_baudrate_and_ids=False): """ Reset all motors on the bus to their factory default settings. """ mode = (0x02 if except_baudrate_and_ids else 0x01 if except_ids else 0xFF) for id in ids: try: self._send_packet(self._protocol.DxlResetPacket(id, mode)) except (DxlTimeoutError, DxlCommunicationError): pass
[ "def", "factory_reset", "(", "self", ",", "ids", ",", "except_ids", "=", "False", ",", "except_baudrate_and_ids", "=", "False", ")", ":", "mode", "=", "(", "0x02", "if", "except_baudrate_and_ids", "else", "0x01", "if", "except_ids", "else", "0xFF", ")", "for", "id", "in", "ids", ":", "try", ":", "self", ".", "_send_packet", "(", "self", ".", "_protocol", ".", "DxlResetPacket", "(", "id", ",", "mode", ")", ")", "except", "(", "DxlTimeoutError", ",", "DxlCommunicationError", ")", ":", "pass" ]
Reset all motors on the bus to their factory default settings.
[ "Reset", "all", "motors", "on", "the", "bus", "to", "their", "factory", "default", "settings", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/io_320.py#L32-L43
train
233,570
poppy-project/pypot
pypot/primitive/primitive.py
Primitive.stop
def stop(self, wait=True): """ Requests the primitive to stop. """ logger.info("Primitive %s stopped.", self) StoppableThread.stop(self, wait)
python
def stop(self, wait=True): """ Requests the primitive to stop. """ logger.info("Primitive %s stopped.", self) StoppableThread.stop(self, wait)
[ "def", "stop", "(", "self", ",", "wait", "=", "True", ")", ":", "logger", ".", "info", "(", "\"Primitive %s stopped.\"", ",", "self", ")", "StoppableThread", ".", "stop", "(", "self", ",", "wait", ")" ]
Requests the primitive to stop.
[ "Requests", "the", "primitive", "to", "stop", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/primitive.py#L126-L129
train
233,571
poppy-project/pypot
pypot/primitive/primitive.py
LoopPrimitive.recent_update_frequencies
def recent_update_frequencies(self): """ Returns the 10 most recent update frequencies. The given frequencies are computed as short-term frequencies! The 0th element of the list corresponds to the most recent frequency. """ return list(reversed([(1.0 / p) for p in numpy.diff(self._recent_updates)]))
python
def recent_update_frequencies(self): """ Returns the 10 most recent update frequencies. The given frequencies are computed as short-term frequencies! The 0th element of the list corresponds to the most recent frequency. """ return list(reversed([(1.0 / p) for p in numpy.diff(self._recent_updates)]))
[ "def", "recent_update_frequencies", "(", "self", ")", ":", "return", "list", "(", "reversed", "(", "[", "(", "1.0", "/", "p", ")", "for", "p", "in", "numpy", ".", "diff", "(", "self", ".", "_recent_updates", ")", "]", ")", ")" ]
Returns the 10 most recent update frequencies. The given frequencies are computed as short-term frequencies! The 0th element of the list corresponds to the most recent frequency.
[ "Returns", "the", "10", "most", "recent", "update", "frequencies", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/primitive.py#L174-L180
train
233,572
poppy-project/pypot
pypot/primitive/primitive.py
MockupMotor.goto_position
def goto_position(self, position, duration, control=None, wait=False): """ Automatically sets the goal position and the moving speed to reach the desired position within the duration. """ if control is None: control = self.goto_behavior if control == 'minjerk': goto_min_jerk = GotoMinJerk(self, position, duration) goto_min_jerk.start() if wait: goto_min_jerk.wait_to_stop() elif control == 'dummy': dp = abs(self.present_position - position) speed = (dp / float(duration)) if duration > 0 else numpy.inf self.moving_speed = speed self.goal_position = position if wait: time.sleep(duration)
python
def goto_position(self, position, duration, control=None, wait=False): """ Automatically sets the goal position and the moving speed to reach the desired position within the duration. """ if control is None: control = self.goto_behavior if control == 'minjerk': goto_min_jerk = GotoMinJerk(self, position, duration) goto_min_jerk.start() if wait: goto_min_jerk.wait_to_stop() elif control == 'dummy': dp = abs(self.present_position - position) speed = (dp / float(duration)) if duration > 0 else numpy.inf self.moving_speed = speed self.goal_position = position if wait: time.sleep(duration)
[ "def", "goto_position", "(", "self", ",", "position", ",", "duration", ",", "control", "=", "None", ",", "wait", "=", "False", ")", ":", "if", "control", "is", "None", ":", "control", "=", "self", ".", "goto_behavior", "if", "control", "==", "'minjerk'", ":", "goto_min_jerk", "=", "GotoMinJerk", "(", "self", ",", "position", ",", "duration", ")", "goto_min_jerk", ".", "start", "(", ")", "if", "wait", ":", "goto_min_jerk", ".", "wait_to_stop", "(", ")", "elif", "control", "==", "'dummy'", ":", "dp", "=", "abs", "(", "self", ".", "present_position", "-", "position", ")", "speed", "=", "(", "dp", "/", "float", "(", "duration", ")", ")", "if", "duration", ">", "0", "else", "numpy", ".", "inf", "self", ".", "moving_speed", "=", "speed", "self", ".", "goal_position", "=", "position", "if", "wait", ":", "time", ".", "sleep", "(", "duration", ")" ]
Automatically sets the goal position and the moving speed to reach the desired position within the duration.
[ "Automatically", "sets", "the", "goal", "position", "and", "the", "moving", "speed", "to", "reach", "the", "desired", "position", "within", "the", "duration", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/primitive.py#L257-L277
train
233,573
poppy-project/pypot
pypot/primitive/move.py
MoveRecorder.add_tracked_motors
def add_tracked_motors(self, tracked_motors): """Add new motors to the recording""" new_mockup_motors = map(self.get_mockup_motor, tracked_motors) self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors))
python
def add_tracked_motors(self, tracked_motors): """Add new motors to the recording""" new_mockup_motors = map(self.get_mockup_motor, tracked_motors) self.tracked_motors = list(set(self.tracked_motors + new_mockup_motors))
[ "def", "add_tracked_motors", "(", "self", ",", "tracked_motors", ")", ":", "new_mockup_motors", "=", "map", "(", "self", ".", "get_mockup_motor", ",", "tracked_motors", ")", "self", ".", "tracked_motors", "=", "list", "(", "set", "(", "self", ".", "tracked_motors", "+", "new_mockup_motors", ")", ")" ]
Add new motors to the recording
[ "Add", "new", "motors", "to", "the", "recording" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/move.py#L137-L140
train
233,574
poppy-project/pypot
pypot/primitive/manager.py
PrimitiveManager.update
def update(self): """ Combined at a predefined frequency the request orders and affect them to the real motors. """ with self.syncing: for m in self._motors: to_set = defaultdict(list) for p in self._prim: for key, val in getattr(p.robot, m.name)._to_set.iteritems(): to_set[key].append(val) for key, val in to_set.iteritems(): if key == 'led': colors = set(val) if len(colors) > 1: colors -= {'off'} filtred_val = colors.pop() else: filtred_val = self._filter(val) logger.debug('Combined %s.%s from %s to %s', m.name, key, val, filtred_val) setattr(m, key, filtred_val) [p._synced.set() for p in self._prim]
python
def update(self): """ Combined at a predefined frequency the request orders and affect them to the real motors. """ with self.syncing: for m in self._motors: to_set = defaultdict(list) for p in self._prim: for key, val in getattr(p.robot, m.name)._to_set.iteritems(): to_set[key].append(val) for key, val in to_set.iteritems(): if key == 'led': colors = set(val) if len(colors) > 1: colors -= {'off'} filtred_val = colors.pop() else: filtred_val = self._filter(val) logger.debug('Combined %s.%s from %s to %s', m.name, key, val, filtred_val) setattr(m, key, filtred_val) [p._synced.set() for p in self._prim]
[ "def", "update", "(", "self", ")", ":", "with", "self", ".", "syncing", ":", "for", "m", "in", "self", ".", "_motors", ":", "to_set", "=", "defaultdict", "(", "list", ")", "for", "p", "in", "self", ".", "_prim", ":", "for", "key", ",", "val", "in", "getattr", "(", "p", ".", "robot", ",", "m", ".", "name", ")", ".", "_to_set", ".", "iteritems", "(", ")", ":", "to_set", "[", "key", "]", ".", "append", "(", "val", ")", "for", "key", ",", "val", "in", "to_set", ".", "iteritems", "(", ")", ":", "if", "key", "==", "'led'", ":", "colors", "=", "set", "(", "val", ")", "if", "len", "(", "colors", ")", ">", "1", ":", "colors", "-=", "{", "'off'", "}", "filtred_val", "=", "colors", ".", "pop", "(", ")", "else", ":", "filtred_val", "=", "self", ".", "_filter", "(", "val", ")", "logger", ".", "debug", "(", "'Combined %s.%s from %s to %s'", ",", "m", ".", "name", ",", "key", ",", "val", ",", "filtred_val", ")", "setattr", "(", "m", ",", "key", ",", "filtred_val", ")", "[", "p", ".", "_synced", ".", "set", "(", ")", "for", "p", "in", "self", ".", "_prim", "]" ]
Combined at a predefined frequency the request orders and affect them to the real motors.
[ "Combined", "at", "a", "predefined", "frequency", "the", "request", "orders", "and", "affect", "them", "to", "the", "real", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/manager.py#L51-L74
train
233,575
poppy-project/pypot
pypot/primitive/manager.py
PrimitiveManager.stop
def stop(self): """ Stop the primitive manager. """ for p in self.primitives[:]: p.stop() StoppableLoopThread.stop(self)
python
def stop(self): """ Stop the primitive manager. """ for p in self.primitives[:]: p.stop() StoppableLoopThread.stop(self)
[ "def", "stop", "(", "self", ")", ":", "for", "p", "in", "self", ".", "primitives", "[", ":", "]", ":", "p", ".", "stop", "(", ")", "StoppableLoopThread", ".", "stop", "(", "self", ")" ]
Stop the primitive manager.
[ "Stop", "the", "primitive", "manager", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/primitive/manager.py#L76-L81
train
233,576
poppy-project/pypot
pypot/vrep/io.py
VrepIO.load_scene
def load_scene(self, scene_path, start=False): """ Loads a scene on the V-REP server. :param str scene_path: path to a V-REP scene file :param bool start: whether to directly start the simulation after loading the scene .. note:: It is assumed that the scene file is always available on the server side. """ self.stop_simulation() if not os.path.exists(scene_path): raise IOError("No such file or directory: '{}'".format(scene_path)) self.call_remote_api('simxLoadScene', scene_path, True) if start: self.start_simulation()
python
def load_scene(self, scene_path, start=False): """ Loads a scene on the V-REP server. :param str scene_path: path to a V-REP scene file :param bool start: whether to directly start the simulation after loading the scene .. note:: It is assumed that the scene file is always available on the server side. """ self.stop_simulation() if not os.path.exists(scene_path): raise IOError("No such file or directory: '{}'".format(scene_path)) self.call_remote_api('simxLoadScene', scene_path, True) if start: self.start_simulation()
[ "def", "load_scene", "(", "self", ",", "scene_path", ",", "start", "=", "False", ")", ":", "self", ".", "stop_simulation", "(", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "scene_path", ")", ":", "raise", "IOError", "(", "\"No such file or directory: '{}'\"", ".", "format", "(", "scene_path", ")", ")", "self", ".", "call_remote_api", "(", "'simxLoadScene'", ",", "scene_path", ",", "True", ")", "if", "start", ":", "self", ".", "start_simulation", "(", ")" ]
Loads a scene on the V-REP server. :param str scene_path: path to a V-REP scene file :param bool start: whether to directly start the simulation after loading the scene .. note:: It is assumed that the scene file is always available on the server side.
[ "Loads", "a", "scene", "on", "the", "V", "-", "REP", "server", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L91-L108
train
233,577
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_motor_position
def get_motor_position(self, motor_name): """ Gets the motor current position. """ return self.call_remote_api('simxGetJointPosition', self.get_object_handle(motor_name), streaming=True)
python
def get_motor_position(self, motor_name): """ Gets the motor current position. """ return self.call_remote_api('simxGetJointPosition', self.get_object_handle(motor_name), streaming=True)
[ "def", "get_motor_position", "(", "self", ",", "motor_name", ")", ":", "return", "self", ".", "call_remote_api", "(", "'simxGetJointPosition'", ",", "self", ".", "get_object_handle", "(", "motor_name", ")", ",", "streaming", "=", "True", ")" ]
Gets the motor current position.
[ "Gets", "the", "motor", "current", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L143-L147
train
233,578
poppy-project/pypot
pypot/vrep/io.py
VrepIO.set_motor_position
def set_motor_position(self, motor_name, position): """ Sets the motor target position. """ self.call_remote_api('simxSetJointTargetPosition', self.get_object_handle(motor_name), position, sending=True)
python
def set_motor_position(self, motor_name, position): """ Sets the motor target position. """ self.call_remote_api('simxSetJointTargetPosition', self.get_object_handle(motor_name), position, sending=True)
[ "def", "set_motor_position", "(", "self", ",", "motor_name", ",", "position", ")", ":", "self", ".", "call_remote_api", "(", "'simxSetJointTargetPosition'", ",", "self", ".", "get_object_handle", "(", "motor_name", ")", ",", "position", ",", "sending", "=", "True", ")" ]
Sets the motor target position.
[ "Sets", "the", "motor", "target", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L149-L154
train
233,579
poppy-project/pypot
pypot/vrep/io.py
VrepIO.set_motor_force
def set_motor_force(self, motor_name, force): """ Sets the maximum force or torque that a joint can exert. """ self.call_remote_api('simxSetJointForce', self.get_object_handle(motor_name), force, sending=True)
python
def set_motor_force(self, motor_name, force): """ Sets the maximum force or torque that a joint can exert. """ self.call_remote_api('simxSetJointForce', self.get_object_handle(motor_name), force, sending=True)
[ "def", "set_motor_force", "(", "self", ",", "motor_name", ",", "force", ")", ":", "self", ".", "call_remote_api", "(", "'simxSetJointForce'", ",", "self", ".", "get_object_handle", "(", "motor_name", ")", ",", "force", ",", "sending", "=", "True", ")" ]
Sets the maximum force or torque that a joint can exert.
[ "Sets", "the", "maximum", "force", "or", "torque", "that", "a", "joint", "can", "exert", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L162-L167
train
233,580
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_object_position
def get_object_position(self, object_name, relative_to_object=None): """ Gets the object position. """ h = self.get_object_handle(object_name) relative_handle = (-1 if relative_to_object is None else self.get_object_handle(relative_to_object)) return self.call_remote_api('simxGetObjectPosition', h, relative_handle, streaming=True)
python
def get_object_position(self, object_name, relative_to_object=None): """ Gets the object position. """ h = self.get_object_handle(object_name) relative_handle = (-1 if relative_to_object is None else self.get_object_handle(relative_to_object)) return self.call_remote_api('simxGetObjectPosition', h, relative_handle, streaming=True)
[ "def", "get_object_position", "(", "self", ",", "object_name", ",", "relative_to_object", "=", "None", ")", ":", "h", "=", "self", ".", "get_object_handle", "(", "object_name", ")", "relative_handle", "=", "(", "-", "1", "if", "relative_to_object", "is", "None", "else", "self", ".", "get_object_handle", "(", "relative_to_object", ")", ")", "return", "self", ".", "call_remote_api", "(", "'simxGetObjectPosition'", ",", "h", ",", "relative_handle", ",", "streaming", "=", "True", ")" ]
Gets the object position.
[ "Gets", "the", "object", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L169-L177
train
233,581
poppy-project/pypot
pypot/vrep/io.py
VrepIO.set_object_position
def set_object_position(self, object_name, position=[0, 0, 0]): """ Sets the object position. """ h = self.get_object_handle(object_name) return self.call_remote_api('simxSetObjectPosition', h, -1, position, sending=True)
python
def set_object_position(self, object_name, position=[0, 0, 0]): """ Sets the object position. """ h = self.get_object_handle(object_name) return self.call_remote_api('simxSetObjectPosition', h, -1, position, sending=True)
[ "def", "set_object_position", "(", "self", ",", "object_name", ",", "position", "=", "[", "0", ",", "0", ",", "0", "]", ")", ":", "h", "=", "self", ".", "get_object_handle", "(", "object_name", ")", "return", "self", ".", "call_remote_api", "(", "'simxSetObjectPosition'", ",", "h", ",", "-", "1", ",", "position", ",", "sending", "=", "True", ")" ]
Sets the object position.
[ "Sets", "the", "object", "position", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L179-L185
train
233,582
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_object_handle
def get_object_handle(self, obj): """ Gets the vrep object handle. """ if obj not in self._object_handles: self._object_handles[obj] = self._get_object_handle(obj=obj) return self._object_handles[obj]
python
def get_object_handle(self, obj): """ Gets the vrep object handle. """ if obj not in self._object_handles: self._object_handles[obj] = self._get_object_handle(obj=obj) return self._object_handles[obj]
[ "def", "get_object_handle", "(", "self", ",", "obj", ")", ":", "if", "obj", "not", "in", "self", ".", "_object_handles", ":", "self", ".", "_object_handles", "[", "obj", "]", "=", "self", ".", "_get_object_handle", "(", "obj", "=", "obj", ")", "return", "self", ".", "_object_handles", "[", "obj", "]" ]
Gets the vrep object handle.
[ "Gets", "the", "vrep", "object", "handle", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L200-L205
train
233,583
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_collision_state
def get_collision_state(self, collision_name): """ Gets the collision state. """ return self.call_remote_api('simxReadCollision', self.get_collision_handle(collision_name), streaming=True)
python
def get_collision_state(self, collision_name): """ Gets the collision state. """ return self.call_remote_api('simxReadCollision', self.get_collision_handle(collision_name), streaming=True)
[ "def", "get_collision_state", "(", "self", ",", "collision_name", ")", ":", "return", "self", ".", "call_remote_api", "(", "'simxReadCollision'", ",", "self", ".", "get_collision_handle", "(", "collision_name", ")", ",", "streaming", "=", "True", ")" ]
Gets the collision state.
[ "Gets", "the", "collision", "state", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L207-L211
train
233,584
poppy-project/pypot
pypot/vrep/io.py
VrepIO.get_collision_handle
def get_collision_handle(self, collision): """ Gets a vrep collisions handle. """ if collision not in self._object_handles: h = self._get_collision_handle(collision) self._object_handles[collision] = h return self._object_handles[collision]
python
def get_collision_handle(self, collision): """ Gets a vrep collisions handle. """ if collision not in self._object_handles: h = self._get_collision_handle(collision) self._object_handles[collision] = h return self._object_handles[collision]
[ "def", "get_collision_handle", "(", "self", ",", "collision", ")", ":", "if", "collision", "not", "in", "self", ".", "_object_handles", ":", "h", "=", "self", ".", "_get_collision_handle", "(", "collision", ")", "self", ".", "_object_handles", "[", "collision", "]", "=", "h", "return", "self", ".", "_object_handles", "[", "collision", "]" ]
Gets a vrep collisions handle.
[ "Gets", "a", "vrep", "collisions", "handle", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L216-L222
train
233,585
poppy-project/pypot
pypot/vrep/io.py
VrepIO.change_object_name
def change_object_name(self, old_name, new_name): """ Change object name """ h = self._get_object_handle(old_name) if old_name in self._object_handles: self._object_handles.pop(old_name) lua_code = "simSetObjectName({}, '{}')".format(h, new_name) self._inject_lua_code(lua_code)
python
def change_object_name(self, old_name, new_name): """ Change object name """ h = self._get_object_handle(old_name) if old_name in self._object_handles: self._object_handles.pop(old_name) lua_code = "simSetObjectName({}, '{}')".format(h, new_name) self._inject_lua_code(lua_code)
[ "def", "change_object_name", "(", "self", ",", "old_name", ",", "new_name", ")", ":", "h", "=", "self", ".", "_get_object_handle", "(", "old_name", ")", "if", "old_name", "in", "self", ".", "_object_handles", ":", "self", ".", "_object_handles", ".", "pop", "(", "old_name", ")", "lua_code", "=", "\"simSetObjectName({}, '{}')\"", ".", "format", "(", "h", ",", "new_name", ")", "self", ".", "_inject_lua_code", "(", "lua_code", ")" ]
Change object name
[ "Change", "object", "name" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L255-L261
train
233,586
poppy-project/pypot
pypot/vrep/io.py
VrepIO._create_pure_shape
def _create_pure_shape(self, primitive_type, options, sizes, mass, precision): """ Create Pure Shape """ lua_code = "simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})".format( primitive_type, options, sizes[0], sizes[1], sizes[2], mass, precision[0], precision[1]) self._inject_lua_code(lua_code)
python
def _create_pure_shape(self, primitive_type, options, sizes, mass, precision): """ Create Pure Shape """ lua_code = "simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})".format( primitive_type, options, sizes[0], sizes[1], sizes[2], mass, precision[0], precision[1]) self._inject_lua_code(lua_code)
[ "def", "_create_pure_shape", "(", "self", ",", "primitive_type", ",", "options", ",", "sizes", ",", "mass", ",", "precision", ")", ":", "lua_code", "=", "\"simCreatePureShape({}, {}, {{{}, {}, {}}}, {}, {{{}, {}}})\"", ".", "format", "(", "primitive_type", ",", "options", ",", "sizes", "[", "0", "]", ",", "sizes", "[", "1", "]", ",", "sizes", "[", "2", "]", ",", "mass", ",", "precision", "[", "0", "]", ",", "precision", "[", "1", "]", ")", "self", ".", "_inject_lua_code", "(", "lua_code", ")" ]
Create Pure Shape
[ "Create", "Pure", "Shape" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L263-L267
train
233,587
poppy-project/pypot
pypot/vrep/io.py
VrepIO._inject_lua_code
def _inject_lua_code(self, lua_code): """ Sends raw lua code and evaluate it wihtout any checking! """ msg = (ctypes.c_ubyte * len(lua_code)).from_buffer_copy(lua_code.encode()) self.call_remote_api('simxWriteStringStream', 'my_lua_code', msg)
python
def _inject_lua_code(self, lua_code): """ Sends raw lua code and evaluate it wihtout any checking! """ msg = (ctypes.c_ubyte * len(lua_code)).from_buffer_copy(lua_code.encode()) self.call_remote_api('simxWriteStringStream', 'my_lua_code', msg)
[ "def", "_inject_lua_code", "(", "self", ",", "lua_code", ")", ":", "msg", "=", "(", "ctypes", ".", "c_ubyte", "*", "len", "(", "lua_code", ")", ")", ".", "from_buffer_copy", "(", "lua_code", ".", "encode", "(", ")", ")", "self", ".", "call_remote_api", "(", "'simxWriteStringStream'", ",", "'my_lua_code'", ",", "msg", ")" ]
Sends raw lua code and evaluate it wihtout any checking!
[ "Sends", "raw", "lua", "code", "and", "evaluate", "it", "wihtout", "any", "checking!" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L269-L272
train
233,588
poppy-project/pypot
pypot/vrep/io.py
VrepIO.call_remote_api
def call_remote_api(self, func_name, *args, **kwargs): """ Calls any remote API func in a thread_safe way. :param str func_name: name of the remote API func to call :param args: args to pass to the remote API call :param kwargs: args to pass to the remote API call .. note:: You can add an extra keyword to specify if you want to use the streaming or sending mode. The oneshot_wait mode is used by default (see `here <http://www.coppeliarobotics.com/helpFiles/en/remoteApiConstants.htm#operationModes>`_ for details about possible modes). .. warning:: You should not pass the clientId and the operationMode as arguments. They will be automatically added. As an example you can retrieve all joints name using the following call:: vrep_io.remote_api_call('simxGetObjectGroupData', vrep_io.remote_api.sim_object_joint_type, 0, streaming=True) """ f = getattr(remote_api, func_name) mode = self._extract_mode(kwargs) kwargs['operationMode'] = vrep_mode[mode] # hard_retry = True if '_force' in kwargs: del kwargs['_force'] _force = True else: _force = False for _ in range(VrepIO.MAX_ITER): with self._lock: ret = f(self.client_id, *args, **kwargs) if _force: return if mode == 'sending' or isinstance(ret, int): err, res = ret, None else: err, res = ret[0], ret[1:] res = res[0] if len(res) == 1 else res err = [bool((err >> i) & 1) for i in range(len(vrep_error))] if remote_api.simx_return_novalue_flag not in err: break time.sleep(VrepIO.TIMEOUT) # if any(err) and hard_retry: # print "HARD RETRY" # self.stop_simulation() #nope # # notconnected = True # while notconnected: # self.close() # close_all_connections() # time.sleep(0.5) # try: # self.open_io() # notconnected = False # except: # print 'CONNECTION ERROR' # pass # # self.start_simulation() # # with self._lock: # ret = f(self.client_id, *args, **kwargs) # # if mode == 'sending' or isinstance(ret, int): # err, res = ret, None # else: # err, res = ret[0], ret[1:] # res = res[0] if len(res) == 1 else res # # err = [bool((err >> i) & 1) for i in range(len(vrep_error))] # # return res if any(err): msg = ' '.join([vrep_error[2 ** i] for i, e in enumerate(err) if e]) raise VrepIOErrors(msg) return res
python
def call_remote_api(self, func_name, *args, **kwargs): """ Calls any remote API func in a thread_safe way. :param str func_name: name of the remote API func to call :param args: args to pass to the remote API call :param kwargs: args to pass to the remote API call .. note:: You can add an extra keyword to specify if you want to use the streaming or sending mode. The oneshot_wait mode is used by default (see `here <http://www.coppeliarobotics.com/helpFiles/en/remoteApiConstants.htm#operationModes>`_ for details about possible modes). .. warning:: You should not pass the clientId and the operationMode as arguments. They will be automatically added. As an example you can retrieve all joints name using the following call:: vrep_io.remote_api_call('simxGetObjectGroupData', vrep_io.remote_api.sim_object_joint_type, 0, streaming=True) """ f = getattr(remote_api, func_name) mode = self._extract_mode(kwargs) kwargs['operationMode'] = vrep_mode[mode] # hard_retry = True if '_force' in kwargs: del kwargs['_force'] _force = True else: _force = False for _ in range(VrepIO.MAX_ITER): with self._lock: ret = f(self.client_id, *args, **kwargs) if _force: return if mode == 'sending' or isinstance(ret, int): err, res = ret, None else: err, res = ret[0], ret[1:] res = res[0] if len(res) == 1 else res err = [bool((err >> i) & 1) for i in range(len(vrep_error))] if remote_api.simx_return_novalue_flag not in err: break time.sleep(VrepIO.TIMEOUT) # if any(err) and hard_retry: # print "HARD RETRY" # self.stop_simulation() #nope # # notconnected = True # while notconnected: # self.close() # close_all_connections() # time.sleep(0.5) # try: # self.open_io() # notconnected = False # except: # print 'CONNECTION ERROR' # pass # # self.start_simulation() # # with self._lock: # ret = f(self.client_id, *args, **kwargs) # # if mode == 'sending' or isinstance(ret, int): # err, res = ret, None # else: # err, res = ret[0], ret[1:] # res = res[0] if len(res) == 1 else res # # err = [bool((err >> i) & 1) for i in range(len(vrep_error))] # # return res if any(err): msg = ' '.join([vrep_error[2 ** i] for i, e in enumerate(err) if e]) raise VrepIOErrors(msg) return res
[ "def", "call_remote_api", "(", "self", ",", "func_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "f", "=", "getattr", "(", "remote_api", ",", "func_name", ")", "mode", "=", "self", ".", "_extract_mode", "(", "kwargs", ")", "kwargs", "[", "'operationMode'", "]", "=", "vrep_mode", "[", "mode", "]", "# hard_retry = True", "if", "'_force'", "in", "kwargs", ":", "del", "kwargs", "[", "'_force'", "]", "_force", "=", "True", "else", ":", "_force", "=", "False", "for", "_", "in", "range", "(", "VrepIO", ".", "MAX_ITER", ")", ":", "with", "self", ".", "_lock", ":", "ret", "=", "f", "(", "self", ".", "client_id", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "_force", ":", "return", "if", "mode", "==", "'sending'", "or", "isinstance", "(", "ret", ",", "int", ")", ":", "err", ",", "res", "=", "ret", ",", "None", "else", ":", "err", ",", "res", "=", "ret", "[", "0", "]", ",", "ret", "[", "1", ":", "]", "res", "=", "res", "[", "0", "]", "if", "len", "(", "res", ")", "==", "1", "else", "res", "err", "=", "[", "bool", "(", "(", "err", ">>", "i", ")", "&", "1", ")", "for", "i", "in", "range", "(", "len", "(", "vrep_error", ")", ")", "]", "if", "remote_api", ".", "simx_return_novalue_flag", "not", "in", "err", ":", "break", "time", ".", "sleep", "(", "VrepIO", ".", "TIMEOUT", ")", "# if any(err) and hard_retry:", "# print \"HARD RETRY\"", "# self.stop_simulation() #nope", "#", "# notconnected = True", "# while notconnected:", "# self.close()", "# close_all_connections()", "# time.sleep(0.5)", "# try:", "# self.open_io()", "# notconnected = False", "# except:", "# print 'CONNECTION ERROR'", "# pass", "#", "# self.start_simulation()", "#", "# with self._lock:", "# ret = f(self.client_id, *args, **kwargs)", "#", "# if mode == 'sending' or isinstance(ret, int):", "# err, res = ret, None", "# else:", "# err, res = ret[0], ret[1:]", "# res = res[0] if len(res) == 1 else res", "#", "# err = [bool((err >> i) & 1) for i in range(len(vrep_error))]", "#", "# return res", "if", "any", "(", "err", ")", ":", "msg", "=", "' '", ".", "join", "(", "[", "vrep_error", "[", "2", "**", "i", "]", "for", "i", ",", "e", "in", "enumerate", "(", "err", ")", "if", "e", "]", ")", "raise", "VrepIOErrors", "(", "msg", ")", "return", "res" ]
Calls any remote API func in a thread_safe way. :param str func_name: name of the remote API func to call :param args: args to pass to the remote API call :param kwargs: args to pass to the remote API call .. note:: You can add an extra keyword to specify if you want to use the streaming or sending mode. The oneshot_wait mode is used by default (see `here <http://www.coppeliarobotics.com/helpFiles/en/remoteApiConstants.htm#operationModes>`_ for details about possible modes). .. warning:: You should not pass the clientId and the operationMode as arguments. They will be automatically added. As an example you can retrieve all joints name using the following call:: vrep_io.remote_api_call('simxGetObjectGroupData', vrep_io.remote_api.sim_object_joint_type, 0, streaming=True)
[ "Calls", "any", "remote", "API", "func", "in", "a", "thread_safe", "way", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/vrep/io.py#L274-L361
train
233,589
poppy-project/pypot
pypot/server/httpserver.py
HTTPRobotServer.run
def run(self, **kwargs): """ Start the tornado server, run forever""" try: loop = IOLoop() app = self.make_app() app.listen(self.port) loop.start() except socket.error as serr: # Re raise the socket error if not "[Errno 98] Address already in use" if serr.errno != errno.EADDRINUSE: raise serr else: logger.warning('The webserver port {} is already used. May be the HttpRobotServer is already running or another software is using this port.'.format(self.port))
python
def run(self, **kwargs): """ Start the tornado server, run forever""" try: loop = IOLoop() app = self.make_app() app.listen(self.port) loop.start() except socket.error as serr: # Re raise the socket error if not "[Errno 98] Address already in use" if serr.errno != errno.EADDRINUSE: raise serr else: logger.warning('The webserver port {} is already used. May be the HttpRobotServer is already running or another software is using this port.'.format(self.port))
[ "def", "run", "(", "self", ",", "*", "*", "kwargs", ")", ":", "try", ":", "loop", "=", "IOLoop", "(", ")", "app", "=", "self", ".", "make_app", "(", ")", "app", ".", "listen", "(", "self", ".", "port", ")", "loop", ".", "start", "(", ")", "except", "socket", ".", "error", "as", "serr", ":", "# Re raise the socket error if not \"[Errno 98] Address already in use\"", "if", "serr", ".", "errno", "!=", "errno", ".", "EADDRINUSE", ":", "raise", "serr", "else", ":", "logger", ".", "warning", "(", "'The webserver port {} is already used. May be the HttpRobotServer is already running or another software is using this port.'", ".", "format", "(", "self", ".", "port", ")", ")" ]
Start the tornado server, run forever
[ "Start", "the", "tornado", "server", "run", "forever" ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/server/httpserver.py#L253-L267
train
233,590
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.close
def close(self, _force_lock=False): """ Closes the serial communication if opened. """ if not self.closed: with self.__force_lock(_force_lock) or self._serial_lock: self._serial.close() self.__used_ports.remove(self.port) logger.info("Closing port '%s'", self.port, extra={'port': self.port, 'baudrate': self.baudrate, 'timeout': self.timeout})
python
def close(self, _force_lock=False): """ Closes the serial communication if opened. """ if not self.closed: with self.__force_lock(_force_lock) or self._serial_lock: self._serial.close() self.__used_ports.remove(self.port) logger.info("Closing port '%s'", self.port, extra={'port': self.port, 'baudrate': self.baudrate, 'timeout': self.timeout})
[ "def", "close", "(", "self", ",", "_force_lock", "=", "False", ")", ":", "if", "not", "self", ".", "closed", ":", "with", "self", ".", "__force_lock", "(", "_force_lock", ")", "or", "self", ".", "_serial_lock", ":", "self", ".", "_serial", ".", "close", "(", ")", "self", ".", "__used_ports", ".", "remove", "(", "self", ".", "port", ")", "logger", ".", "info", "(", "\"Closing port '%s'\"", ",", "self", ".", "port", ",", "extra", "=", "{", "'port'", ":", "self", ".", "port", ",", "'baudrate'", ":", "self", ".", "baudrate", ",", "'timeout'", ":", "self", ".", "timeout", "}", ")" ]
Closes the serial communication if opened.
[ "Closes", "the", "serial", "communication", "if", "opened", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L145-L155
train
233,591
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.ping
def ping(self, id): """ Pings the motor with the specified id. .. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast. """ pp = self._protocol.DxlPingPacket(id) try: self._send_packet(pp, error_handler=None) return True except DxlTimeoutError: return False
python
def ping(self, id): """ Pings the motor with the specified id. .. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast. """ pp = self._protocol.DxlPingPacket(id) try: self._send_packet(pp, error_handler=None) return True except DxlTimeoutError: return False
[ "def", "ping", "(", "self", ",", "id", ")", ":", "pp", "=", "self", ".", "_protocol", ".", "DxlPingPacket", "(", "id", ")", "try", ":", "self", ".", "_send_packet", "(", "pp", ",", "error_handler", "=", "None", ")", "return", "True", "except", "DxlTimeoutError", ":", "return", "False" ]
Pings the motor with the specified id. .. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast.
[ "Pings", "the", "motor", "with", "the", "specified", "id", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L205-L217
train
233,592
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.scan
def scan(self, ids=range(254)): """ Pings all ids within the specified list, by default it finds all the motors connected to the bus. """ return [id for id in ids if self.ping(id)]
python
def scan(self, ids=range(254)): """ Pings all ids within the specified list, by default it finds all the motors connected to the bus. """ return [id for id in ids if self.ping(id)]
[ "def", "scan", "(", "self", ",", "ids", "=", "range", "(", "254", ")", ")", ":", "return", "[", "id", "for", "id", "in", "ids", "if", "self", ".", "ping", "(", "id", ")", "]" ]
Pings all ids within the specified list, by default it finds all the motors connected to the bus.
[ "Pings", "all", "ids", "within", "the", "specified", "list", "by", "default", "it", "finds", "all", "the", "motors", "connected", "to", "the", "bus", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L219-L221
train
233,593
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.get_model
def get_model(self, ids): """ Gets the model for the specified motors. """ to_get_ids = [i for i in ids if i not in self._known_models] models = [dxl_to_model(m) for m in self._get_model(to_get_ids, convert=False)] self._known_models.update(zip(to_get_ids, models)) return tuple(self._known_models[id] for id in ids)
python
def get_model(self, ids): """ Gets the model for the specified motors. """ to_get_ids = [i for i in ids if i not in self._known_models] models = [dxl_to_model(m) for m in self._get_model(to_get_ids, convert=False)] self._known_models.update(zip(to_get_ids, models)) return tuple(self._known_models[id] for id in ids)
[ "def", "get_model", "(", "self", ",", "ids", ")", ":", "to_get_ids", "=", "[", "i", "for", "i", "in", "ids", "if", "i", "not", "in", "self", ".", "_known_models", "]", "models", "=", "[", "dxl_to_model", "(", "m", ")", "for", "m", "in", "self", ".", "_get_model", "(", "to_get_ids", ",", "convert", "=", "False", ")", "]", "self", ".", "_known_models", ".", "update", "(", "zip", "(", "to_get_ids", ",", "models", ")", ")", "return", "tuple", "(", "self", ".", "_known_models", "[", "id", "]", "for", "id", "in", "ids", ")" ]
Gets the model for the specified motors.
[ "Gets", "the", "model", "for", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L225-L231
train
233,594
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.change_baudrate
def change_baudrate(self, baudrate_for_ids): """ Changes the baudrate of the specified motors. """ self._change_baudrate(baudrate_for_ids) for motor_id in baudrate_for_ids: if motor_id in self._known_models: del self._known_models[motor_id] if motor_id in self._known_mode: del self._known_mode[motor_id]
python
def change_baudrate(self, baudrate_for_ids): """ Changes the baudrate of the specified motors. """ self._change_baudrate(baudrate_for_ids) for motor_id in baudrate_for_ids: if motor_id in self._known_models: del self._known_models[motor_id] if motor_id in self._known_mode: del self._known_mode[motor_id]
[ "def", "change_baudrate", "(", "self", ",", "baudrate_for_ids", ")", ":", "self", ".", "_change_baudrate", "(", "baudrate_for_ids", ")", "for", "motor_id", "in", "baudrate_for_ids", ":", "if", "motor_id", "in", "self", ".", "_known_models", ":", "del", "self", ".", "_known_models", "[", "motor_id", "]", "if", "motor_id", "in", "self", ".", "_known_mode", ":", "del", "self", ".", "_known_mode", "[", "motor_id", "]" ]
Changes the baudrate of the specified motors.
[ "Changes", "the", "baudrate", "of", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L252-L260
train
233,595
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.get_status_return_level
def get_status_return_level(self, ids, **kwargs): """ Gets the status level for the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert srl = [] for id in ids: try: srl.extend(self._get_status_return_level((id, ), error_handler=None, convert=convert)) except DxlTimeoutError as e: if self.ping(id): srl.append('never' if convert else 0) else: if self._error_handler: self._error_handler.handle_timeout(e) return () else: raise e return tuple(srl)
python
def get_status_return_level(self, ids, **kwargs): """ Gets the status level for the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert srl = [] for id in ids: try: srl.extend(self._get_status_return_level((id, ), error_handler=None, convert=convert)) except DxlTimeoutError as e: if self.ping(id): srl.append('never' if convert else 0) else: if self._error_handler: self._error_handler.handle_timeout(e) return () else: raise e return tuple(srl)
[ "def", "get_status_return_level", "(", "self", ",", "ids", ",", "*", "*", "kwargs", ")", ":", "convert", "=", "kwargs", "[", "'convert'", "]", "if", "'convert'", "in", "kwargs", "else", "self", ".", "_convert", "srl", "=", "[", "]", "for", "id", "in", "ids", ":", "try", ":", "srl", ".", "extend", "(", "self", ".", "_get_status_return_level", "(", "(", "id", ",", ")", ",", "error_handler", "=", "None", ",", "convert", "=", "convert", ")", ")", "except", "DxlTimeoutError", "as", "e", ":", "if", "self", ".", "ping", "(", "id", ")", ":", "srl", ".", "append", "(", "'never'", "if", "convert", "else", "0", ")", "else", ":", "if", "self", ".", "_error_handler", ":", "self", ".", "_error_handler", ".", "handle_timeout", "(", "e", ")", "return", "(", ")", "else", ":", "raise", "e", "return", "tuple", "(", "srl", ")" ]
Gets the status level for the specified motors.
[ "Gets", "the", "status", "level", "for", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L262-L280
train
233,596
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.set_status_return_level
def set_status_return_level(self, srl_for_id, **kwargs): """ Sets status return level to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if convert: srl_for_id = dict(zip(srl_for_id.keys(), [('never', 'read', 'always').index(s) for s in srl_for_id.values()])) self._set_status_return_level(srl_for_id, convert=False)
python
def set_status_return_level(self, srl_for_id, **kwargs): """ Sets status return level to the specified motors. """ convert = kwargs['convert'] if 'convert' in kwargs else self._convert if convert: srl_for_id = dict(zip(srl_for_id.keys(), [('never', 'read', 'always').index(s) for s in srl_for_id.values()])) self._set_status_return_level(srl_for_id, convert=False)
[ "def", "set_status_return_level", "(", "self", ",", "srl_for_id", ",", "*", "*", "kwargs", ")", ":", "convert", "=", "kwargs", "[", "'convert'", "]", "if", "'convert'", "in", "kwargs", "else", "self", ".", "_convert", "if", "convert", ":", "srl_for_id", "=", "dict", "(", "zip", "(", "srl_for_id", ".", "keys", "(", ")", ",", "[", "(", "'never'", ",", "'read'", ",", "'always'", ")", ".", "index", "(", "s", ")", "for", "s", "in", "srl_for_id", ".", "values", "(", ")", "]", ")", ")", "self", ".", "_set_status_return_level", "(", "srl_for_id", ",", "convert", "=", "False", ")" ]
Sets status return level to the specified motors.
[ "Sets", "status", "return", "level", "to", "the", "specified", "motors", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L282-L288
train
233,597
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.switch_led_on
def switch_led_on(self, ids): """ Switches on the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(True))))
python
def switch_led_on(self, ids): """ Switches on the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(True))))
[ "def", "switch_led_on", "(", "self", ",", "ids", ")", ":", "self", ".", "_set_LED", "(", "dict", "(", "zip", "(", "ids", ",", "itertools", ".", "repeat", "(", "True", ")", ")", ")", ")" ]
Switches on the LED of the motors with the specified ids.
[ "Switches", "on", "the", "LED", "of", "the", "motors", "with", "the", "specified", "ids", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L290-L292
train
233,598
poppy-project/pypot
pypot/dynamixel/io/abstract_io.py
AbstractDxlIO.switch_led_off
def switch_led_off(self, ids): """ Switches off the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(False))))
python
def switch_led_off(self, ids): """ Switches off the LED of the motors with the specified ids. """ self._set_LED(dict(zip(ids, itertools.repeat(False))))
[ "def", "switch_led_off", "(", "self", ",", "ids", ")", ":", "self", ".", "_set_LED", "(", "dict", "(", "zip", "(", "ids", ",", "itertools", ".", "repeat", "(", "False", ")", ")", ")", ")" ]
Switches off the LED of the motors with the specified ids.
[ "Switches", "off", "the", "LED", "of", "the", "motors", "with", "the", "specified", "ids", "." ]
d9c6551bbc87d45d9d1f0bc15e35b616d0002afd
https://github.com/poppy-project/pypot/blob/d9c6551bbc87d45d9d1f0bc15e35b616d0002afd/pypot/dynamixel/io/abstract_io.py#L294-L296
train
233,599