partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
OAuthAuthentication.validate_token
Check the token and raise an `oauth.Error` exception if invalid.
rest_framework_oauth/authentication.py
def validate_token(self, request, consumer, token): """ Check the token and raise an `oauth.Error` exception if invalid. """ oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request) oauth_server.verify_request(oauth_request, consumer, token)
def validate_token(self, request, consumer, token): """ Check the token and raise an `oauth.Error` exception if invalid. """ oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request) oauth_server.verify_request(oauth_request, consumer, token)
[ "Check", "the", "token", "and", "raise", "an", "oauth", ".", "Error", "exception", "if", "invalid", "." ]
jpadilla/django-rest-framework-oauth
python
https://github.com/jpadilla/django-rest-framework-oauth/blob/e319b318c41edf93e121c58856bc4c744cdc6867/rest_framework_oauth/authentication.py#L106-L111
[ "def", "validate_token", "(", "self", ",", "request", ",", "consumer", ",", "token", ")", ":", "oauth_server", ",", "oauth_request", "=", "oauth_provider", ".", "utils", ".", "initialize_server_request", "(", "request", ")", "oauth_server", ".", "verify_request", "(", "oauth_request", ",", "consumer", ",", "token", ")" ]
e319b318c41edf93e121c58856bc4c744cdc6867
valid
OAuthAuthentication.check_nonce
Checks nonce of request, and return True if valid.
rest_framework_oauth/authentication.py
def check_nonce(self, request, oauth_request): """ Checks nonce of request, and return True if valid. """ oauth_nonce = oauth_request['oauth_nonce'] oauth_timestamp = oauth_request['oauth_timestamp'] return check_nonce(request, oauth_request, oauth_nonce, oauth_timestamp)
def check_nonce(self, request, oauth_request): """ Checks nonce of request, and return True if valid. """ oauth_nonce = oauth_request['oauth_nonce'] oauth_timestamp = oauth_request['oauth_timestamp'] return check_nonce(request, oauth_request, oauth_nonce, oauth_timestamp)
[ "Checks", "nonce", "of", "request", "and", "return", "True", "if", "valid", "." ]
jpadilla/django-rest-framework-oauth
python
https://github.com/jpadilla/django-rest-framework-oauth/blob/e319b318c41edf93e121c58856bc4c744cdc6867/rest_framework_oauth/authentication.py#L113-L119
[ "def", "check_nonce", "(", "self", ",", "request", ",", "oauth_request", ")", ":", "oauth_nonce", "=", "oauth_request", "[", "'oauth_nonce'", "]", "oauth_timestamp", "=", "oauth_request", "[", "'oauth_timestamp'", "]", "return", "check_nonce", "(", "request", ",", "oauth_request", ",", "oauth_nonce", ",", "oauth_timestamp", ")" ]
e319b318c41edf93e121c58856bc4c744cdc6867
valid
OAuth2Authentication.authenticate
Returns two-tuple of (user, token) if authentication succeeds, or None otherwise.
rest_framework_oauth/authentication.py
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ auth = get_authorization_header(request).split() if len(auth) == 1: msg = 'Invalid bearer header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid bearer header. Token string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) if auth and auth[0].lower() == b'bearer': access_token = auth[1] elif 'access_token' in request.POST: access_token = request.POST['access_token'] elif 'access_token' in request.GET and self.allow_query_params_token: access_token = request.GET['access_token'] else: return None return self.authenticate_credentials(request, access_token)
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ auth = get_authorization_header(request).split() if len(auth) == 1: msg = 'Invalid bearer header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid bearer header. Token string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) if auth and auth[0].lower() == b'bearer': access_token = auth[1] elif 'access_token' in request.POST: access_token = request.POST['access_token'] elif 'access_token' in request.GET and self.allow_query_params_token: access_token = request.GET['access_token'] else: return None return self.authenticate_credentials(request, access_token)
[ "Returns", "two", "-", "tuple", "of", "(", "user", "token", ")", "if", "authentication", "succeeds", "or", "None", "otherwise", "." ]
jpadilla/django-rest-framework-oauth
python
https://github.com/jpadilla/django-rest-framework-oauth/blob/e319b318c41edf93e121c58856bc4c744cdc6867/rest_framework_oauth/authentication.py#L137-L161
[ "def", "authenticate", "(", "self", ",", "request", ")", ":", "auth", "=", "get_authorization_header", "(", "request", ")", ".", "split", "(", ")", "if", "len", "(", "auth", ")", "==", "1", ":", "msg", "=", "'Invalid bearer header. No credentials provided.'", "raise", "exceptions", ".", "AuthenticationFailed", "(", "msg", ")", "elif", "len", "(", "auth", ")", ">", "2", ":", "msg", "=", "'Invalid bearer header. Token string should not contain spaces.'", "raise", "exceptions", ".", "AuthenticationFailed", "(", "msg", ")", "if", "auth", "and", "auth", "[", "0", "]", ".", "lower", "(", ")", "==", "b'bearer'", ":", "access_token", "=", "auth", "[", "1", "]", "elif", "'access_token'", "in", "request", ".", "POST", ":", "access_token", "=", "request", ".", "POST", "[", "'access_token'", "]", "elif", "'access_token'", "in", "request", ".", "GET", "and", "self", ".", "allow_query_params_token", ":", "access_token", "=", "request", ".", "GET", "[", "'access_token'", "]", "else", ":", "return", "None", "return", "self", ".", "authenticate_credentials", "(", "request", ",", "access_token", ")" ]
e319b318c41edf93e121c58856bc4c744cdc6867
valid
SHA1.getSHA1
用SHA1算法生成安全签名 @param token: 票据 @param timestamp: 时间戳 @param encrypt: 密文 @param nonce: 随机字符串 @return: 安全签名
wechat/crypt.py
def getSHA1(self, token, timestamp, nonce, encrypt): """用SHA1算法生成安全签名 @param token: 票据 @param timestamp: 时间戳 @param encrypt: 密文 @param nonce: 随机字符串 @return: 安全签名 """ try: sortlist = [token, timestamp, nonce, encrypt] sortlist.sort() sha = hashlib.sha1() sha.update("".join(sortlist)) return WXBizMsgCrypt_OK, sha.hexdigest() except Exception: return WXBizMsgCrypt_ComputeSignature_Error, None
def getSHA1(self, token, timestamp, nonce, encrypt): """用SHA1算法生成安全签名 @param token: 票据 @param timestamp: 时间戳 @param encrypt: 密文 @param nonce: 随机字符串 @return: 安全签名 """ try: sortlist = [token, timestamp, nonce, encrypt] sortlist.sort() sha = hashlib.sha1() sha.update("".join(sortlist)) return WXBizMsgCrypt_OK, sha.hexdigest() except Exception: return WXBizMsgCrypt_ComputeSignature_Error, None
[ "用SHA1算法生成安全签名" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L49-L64
[ "def", "getSHA1", "(", "self", ",", "token", ",", "timestamp", ",", "nonce", ",", "encrypt", ")", ":", "try", ":", "sortlist", "=", "[", "token", ",", "timestamp", ",", "nonce", ",", "encrypt", "]", "sortlist", ".", "sort", "(", ")", "sha", "=", "hashlib", ".", "sha1", "(", ")", "sha", ".", "update", "(", "\"\"", ".", "join", "(", "sortlist", ")", ")", "return", "WXBizMsgCrypt_OK", ",", "sha", ".", "hexdigest", "(", ")", "except", "Exception", ":", "return", "WXBizMsgCrypt_ComputeSignature_Error", ",", "None" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
XMLParse.extract
提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 提取出的加密消息字符串
wechat/crypt.py
def extract(self, xmltext): """提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 提取出的加密消息字符串 """ try: xml_tree = ET.fromstring(xmltext) encrypt = xml_tree.find("Encrypt") touser_name = xml_tree.find("ToUserName") if touser_name != None: touser_name = touser_name.text return WXBizMsgCrypt_OK, encrypt.text, touser_name except Exception: return WXBizMsgCrypt_ParseXml_Error, None, None
def extract(self, xmltext): """提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 提取出的加密消息字符串 """ try: xml_tree = ET.fromstring(xmltext) encrypt = xml_tree.find("Encrypt") touser_name = xml_tree.find("ToUserName") if touser_name != None: touser_name = touser_name.text return WXBizMsgCrypt_OK, encrypt.text, touser_name except Exception: return WXBizMsgCrypt_ParseXml_Error, None, None
[ "提取出xml数据包中的加密消息" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L76-L89
[ "def", "extract", "(", "self", ",", "xmltext", ")", ":", "try", ":", "xml_tree", "=", "ET", ".", "fromstring", "(", "xmltext", ")", "encrypt", "=", "xml_tree", ".", "find", "(", "\"Encrypt\"", ")", "touser_name", "=", "xml_tree", ".", "find", "(", "\"ToUserName\"", ")", "if", "touser_name", "!=", "None", ":", "touser_name", "=", "touser_name", ".", "text", "return", "WXBizMsgCrypt_OK", ",", "encrypt", ".", "text", ",", "touser_name", "except", "Exception", ":", "return", "WXBizMsgCrypt_ParseXml_Error", ",", "None", ",", "None" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
XMLParse.generate
生成xml消息 @param encrypt: 加密后的消息密文 @param signature: 安全签名 @param timestamp: 时间戳 @param nonce: 随机字符串 @return: 生成的xml字符串
wechat/crypt.py
def generate(self, encrypt, signature, timestamp, nonce): """生成xml消息 @param encrypt: 加密后的消息密文 @param signature: 安全签名 @param timestamp: 时间戳 @param nonce: 随机字符串 @return: 生成的xml字符串 """ resp_dict = { 'msg_encrypt': encrypt, 'msg_signaturet': signature, 'timestamp': timestamp, 'nonce': nonce, } resp_xml = self.AES_TEXT_RESPONSE_TEMPLATE % resp_dict return resp_xml
def generate(self, encrypt, signature, timestamp, nonce): """生成xml消息 @param encrypt: 加密后的消息密文 @param signature: 安全签名 @param timestamp: 时间戳 @param nonce: 随机字符串 @return: 生成的xml字符串 """ resp_dict = { 'msg_encrypt': encrypt, 'msg_signaturet': signature, 'timestamp': timestamp, 'nonce': nonce, } resp_xml = self.AES_TEXT_RESPONSE_TEMPLATE % resp_dict return resp_xml
[ "生成xml消息" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L91-L106
[ "def", "generate", "(", "self", ",", "encrypt", ",", "signature", ",", "timestamp", ",", "nonce", ")", ":", "resp_dict", "=", "{", "'msg_encrypt'", ":", "encrypt", ",", "'msg_signaturet'", ":", "signature", ",", "'timestamp'", ":", "timestamp", ",", "'nonce'", ":", "nonce", ",", "}", "resp_xml", "=", "self", ".", "AES_TEXT_RESPONSE_TEMPLATE", "%", "resp_dict", "return", "resp_xml" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
PKCS7Encoder.encode
对需要加密的明文进行填充补位 @param text: 需要进行填充补位操作的明文 @return: 补齐明文字符串
wechat/crypt.py
def encode(self, text): """ 对需要加密的明文进行填充补位 @param text: 需要进行填充补位操作的明文 @return: 补齐明文字符串 """ text_length = len(text) # 计算需要填充的位数 amount_to_pad = self.block_size - (text_length % self.block_size) if amount_to_pad == 0: amount_to_pad = self.block_size # 获得补位所用的字符 pad = chr(amount_to_pad) return text + pad * amount_to_pad
def encode(self, text): """ 对需要加密的明文进行填充补位 @param text: 需要进行填充补位操作的明文 @return: 补齐明文字符串 """ text_length = len(text) # 计算需要填充的位数 amount_to_pad = self.block_size - (text_length % self.block_size) if amount_to_pad == 0: amount_to_pad = self.block_size # 获得补位所用的字符 pad = chr(amount_to_pad) return text + pad * amount_to_pad
[ "对需要加密的明文进行填充补位" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L113-L125
[ "def", "encode", "(", "self", ",", "text", ")", ":", "text_length", "=", "len", "(", "text", ")", "# 计算需要填充的位数", "amount_to_pad", "=", "self", ".", "block_size", "-", "(", "text_length", "%", "self", ".", "block_size", ")", "if", "amount_to_pad", "==", "0", ":", "amount_to_pad", "=", "self", ".", "block_size", "# 获得补位所用的字符", "pad", "=", "chr", "(", "amount_to_pad", ")", "return", "text", "+", "pad", "*", "amount_to_pad" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
PKCS7Encoder.decode
删除解密后明文的补位字符 @param decrypted: 解密后的明文 @return: 删除补位字符后的明文
wechat/crypt.py
def decode(self, decrypted): """删除解密后明文的补位字符 @param decrypted: 解密后的明文 @return: 删除补位字符后的明文 """ pad = ord(decrypted[-1]) if pad < 1 or pad > 32: pad = 0 return decrypted[:-pad]
def decode(self, decrypted): """删除解密后明文的补位字符 @param decrypted: 解密后的明文 @return: 删除补位字符后的明文 """ pad = ord(decrypted[-1]) if pad < 1 or pad > 32: pad = 0 return decrypted[:-pad]
[ "删除解密后明文的补位字符" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L127-L135
[ "def", "decode", "(", "self", ",", "decrypted", ")", ":", "pad", "=", "ord", "(", "decrypted", "[", "-", "1", "]", ")", "if", "pad", "<", "1", "or", "pad", ">", "32", ":", "pad", "=", "0", "return", "decrypted", "[", ":", "-", "pad", "]" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
Prpcrypt.encrypt
对明文进行加密 @param text: 需要加密的明文 @return: 加密得到的字符串
wechat/crypt.py
def encrypt(self, text, appid): """对明文进行加密 @param text: 需要加密的明文 @return: 加密得到的字符串 """ # 16位随机字符串添加到明文开头 text = self.get_random_str() + struct.pack( "I", socket.htonl(len(text))) + text + appid # 使用自定义的填充方式对明文进行补位填充 pkcs7 = PKCS7Encoder() text = pkcs7.encode(text) # 加密 cryptor = AES.new(self.key, self.mode, self.key[:16]) try: ciphertext = cryptor.encrypt(text) # 使用BASE64对加密后的字符串进行编码 return WXBizMsgCrypt_OK, base64.b64encode(ciphertext) except Exception: return WXBizMsgCrypt_EncryptAES_Error, None
def encrypt(self, text, appid): """对明文进行加密 @param text: 需要加密的明文 @return: 加密得到的字符串 """ # 16位随机字符串添加到明文开头 text = self.get_random_str() + struct.pack( "I", socket.htonl(len(text))) + text + appid # 使用自定义的填充方式对明文进行补位填充 pkcs7 = PKCS7Encoder() text = pkcs7.encode(text) # 加密 cryptor = AES.new(self.key, self.mode, self.key[:16]) try: ciphertext = cryptor.encrypt(text) # 使用BASE64对加密后的字符串进行编码 return WXBizMsgCrypt_OK, base64.b64encode(ciphertext) except Exception: return WXBizMsgCrypt_EncryptAES_Error, None
[ "对明文进行加密" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L147-L165
[ "def", "encrypt", "(", "self", ",", "text", ",", "appid", ")", ":", "# 16位随机字符串添加到明文开头", "text", "=", "self", ".", "get_random_str", "(", ")", "+", "struct", ".", "pack", "(", "\"I\"", ",", "socket", ".", "htonl", "(", "len", "(", "text", ")", ")", ")", "+", "text", "+", "appid", "# 使用自定义的填充方式对明文进行补位填充", "pkcs7", "=", "PKCS7Encoder", "(", ")", "text", "=", "pkcs7", ".", "encode", "(", "text", ")", "# 加密", "cryptor", "=", "AES", ".", "new", "(", "self", ".", "key", ",", "self", ".", "mode", ",", "self", ".", "key", "[", ":", "16", "]", ")", "try", ":", "ciphertext", "=", "cryptor", ".", "encrypt", "(", "text", ")", "# 使用BASE64对加密后的字符串进行编码", "return", "WXBizMsgCrypt_OK", ",", "base64", ".", "b64encode", "(", "ciphertext", ")", "except", "Exception", ":", "return", "WXBizMsgCrypt_EncryptAES_Error", ",", "None" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
Prpcrypt.decrypt
对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文
wechat/crypt.py
def decrypt(self, text, appid): """对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文 """ try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception: return WXBizMsgCrypt_DecryptAES_Error, None try: pad = ord(plain_text[-1]) # 去掉补位字符串 #pkcs7 = PKCS7Encoder() #plain_text = pkcs7.encode(plain_text) # 去除16位随机字符串 content = plain_text[16:-pad] xml_len = socket.ntohl(struct.unpack("I", content[:4])[0]) xml_content = content[4:xml_len+4] from_appid = content[xml_len+4:] except Exception: return WXBizMsgCrypt_IllegalBuffer, None if from_appid != appid: return WXBizMsgCrypt_ValidateAppidOrCorpid_Error, None return 0, xml_content
def decrypt(self, text, appid): """对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文 """ try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception: return WXBizMsgCrypt_DecryptAES_Error, None try: pad = ord(plain_text[-1]) # 去掉补位字符串 #pkcs7 = PKCS7Encoder() #plain_text = pkcs7.encode(plain_text) # 去除16位随机字符串 content = plain_text[16:-pad] xml_len = socket.ntohl(struct.unpack("I", content[:4])[0]) xml_content = content[4:xml_len+4] from_appid = content[xml_len+4:] except Exception: return WXBizMsgCrypt_IllegalBuffer, None if from_appid != appid: return WXBizMsgCrypt_ValidateAppidOrCorpid_Error, None return 0, xml_content
[ "对解密后的明文进行补位删除" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L167-L192
[ "def", "decrypt", "(", "self", ",", "text", ",", "appid", ")", ":", "try", ":", "cryptor", "=", "AES", ".", "new", "(", "self", ".", "key", ",", "self", ".", "mode", ",", "self", ".", "key", "[", ":", "16", "]", ")", "# 使用BASE64对密文进行解码,然后AES-CBC解密", "plain_text", "=", "cryptor", ".", "decrypt", "(", "base64", ".", "b64decode", "(", "text", ")", ")", "except", "Exception", ":", "return", "WXBizMsgCrypt_DecryptAES_Error", ",", "None", "try", ":", "pad", "=", "ord", "(", "plain_text", "[", "-", "1", "]", ")", "# 去掉补位字符串", "#pkcs7 = PKCS7Encoder()", "#plain_text = pkcs7.encode(plain_text)", "# 去除16位随机字符串", "content", "=", "plain_text", "[", "16", ":", "-", "pad", "]", "xml_len", "=", "socket", ".", "ntohl", "(", "struct", ".", "unpack", "(", "\"I\"", ",", "content", "[", ":", "4", "]", ")", "[", "0", "]", ")", "xml_content", "=", "content", "[", "4", ":", "xml_len", "+", "4", "]", "from_appid", "=", "content", "[", "xml_len", "+", "4", ":", "]", "except", "Exception", ":", "return", "WXBizMsgCrypt_IllegalBuffer", ",", "None", "if", "from_appid", "!=", "appid", ":", "return", "WXBizMsgCrypt_ValidateAppidOrCorpid_Error", ",", "None", "return", "0", ",", "xml_content" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
Prpcrypt.get_random_str
随机生成16位字符串 @return: 16位字符串
wechat/crypt.py
def get_random_str(self): """ 随机生成16位字符串 @return: 16位字符串 """ rule = string.letters + string.digits str = random.sample(rule, 16) return "".join(str)
def get_random_str(self): """ 随机生成16位字符串 @return: 16位字符串 """ rule = string.letters + string.digits str = random.sample(rule, 16) return "".join(str)
[ "随机生成16位字符串" ]
jeffkit/wechat
python
https://github.com/jeffkit/wechat/blob/95510106605e3870e81d7b2ea08ef7868b01d3bf/wechat/crypt.py#L194-L200
[ "def", "get_random_str", "(", "self", ")", ":", "rule", "=", "string", ".", "letters", "+", "string", ".", "digits", "str", "=", "random", ".", "sample", "(", "rule", ",", "16", ")", "return", "\"\"", ".", "join", "(", "str", ")" ]
95510106605e3870e81d7b2ea08ef7868b01d3bf
valid
WebhookTargetRedisDetailView.deliveries
Get delivery log from Redis
djwebhooks/views.py
def deliveries(self): """ Get delivery log from Redis""" key = make_key( event=self.object.event, owner_name=self.object.owner.username, identifier=self.object.identifier ) return redis.lrange(key, 0, 20)
def deliveries(self): """ Get delivery log from Redis""" key = make_key( event=self.object.event, owner_name=self.object.owner.username, identifier=self.object.identifier ) return redis.lrange(key, 0, 20)
[ "Get", "delivery", "log", "from", "Redis" ]
pydanny/dj-webhooks
python
https://github.com/pydanny/dj-webhooks/blob/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/views.py#L78-L85
[ "def", "deliveries", "(", "self", ")", ":", "key", "=", "make_key", "(", "event", "=", "self", ".", "object", ".", "event", ",", "owner_name", "=", "self", ".", "object", ".", "owner", ".", "username", ",", "identifier", "=", "self", ".", "object", ".", "identifier", ")", "return", "redis", ".", "lrange", "(", "key", ",", "0", ",", "20", ")" ]
88e245bfe2020e96279af261d88bf8469ba469e5
valid
event_choices
Get the possible events from settings
djwebhooks/models.py
def event_choices(events): """ Get the possible events from settings """ if events is None: msg = "Please add some events in settings.WEBHOOK_EVENTS." raise ImproperlyConfigured(msg) try: choices = [(x, x) for x in events] except TypeError: """ Not a valid iterator, so we raise an exception """ msg = "settings.WEBHOOK_EVENTS must be an iterable object." raise ImproperlyConfigured(msg) return choices
def event_choices(events): """ Get the possible events from settings """ if events is None: msg = "Please add some events in settings.WEBHOOK_EVENTS." raise ImproperlyConfigured(msg) try: choices = [(x, x) for x in events] except TypeError: """ Not a valid iterator, so we raise an exception """ msg = "settings.WEBHOOK_EVENTS must be an iterable object." raise ImproperlyConfigured(msg) return choices
[ "Get", "the", "possible", "events", "from", "settings" ]
pydanny/dj-webhooks
python
https://github.com/pydanny/dj-webhooks/blob/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/models.py#L16-L27
[ "def", "event_choices", "(", "events", ")", ":", "if", "events", "is", "None", ":", "msg", "=", "\"Please add some events in settings.WEBHOOK_EVENTS.\"", "raise", "ImproperlyConfigured", "(", "msg", ")", "try", ":", "choices", "=", "[", "(", "x", ",", "x", ")", "for", "x", "in", "events", "]", "except", "TypeError", ":", "\"\"\" Not a valid iterator, so we raise an exception \"\"\"", "msg", "=", "\"settings.WEBHOOK_EVENTS must be an iterable object.\"", "raise", "ImproperlyConfigured", "(", "msg", ")", "return", "choices" ]
88e245bfe2020e96279af261d88bf8469ba469e5
valid
worker
This is an asynchronous sender callable that uses the Django ORM to store webhooks. Redis is used to handle the message queue. dkwargs argument requires the following key/values: :event: A string representing an event. kwargs argument requires the following key/values :owner: The user who created/owns the event
djwebhooks/senders/redisq.py
def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs): """ This is an asynchronous sender callable that uses the Django ORM to store webhooks. Redis is used to handle the message queue. dkwargs argument requires the following key/values: :event: A string representing an event. kwargs argument requires the following key/values :owner: The user who created/owns the event """ if "event" not in dkwargs: msg = "djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator." raise TypeError(msg) event = dkwargs['event'] if "owner" not in kwargs: msg = "djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function." raise TypeError(msg) owner = kwargs['owner'] if "identifier" not in kwargs: msg = "djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function." raise TypeError(msg) identifier = kwargs['identifier'] senderobj = DjangoRQSenderable( wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs ) # Add the webhook object just so it's around # TODO - error handling if this can't be found senderobj.webhook_target = WebhookTarget.objects.get( event=event, owner=owner, identifier=identifier ) # Get the target url and add it senderobj.url = senderobj.webhook_target.target_url # Get the payload. This overides the senderobj.payload property. senderobj.payload = senderobj.get_payload() # Get the creator and add it to the payload. senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD) # get the event and add it to the payload senderobj.payload['event'] = dkwargs['event'] return senderobj.send()
def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs): """ This is an asynchronous sender callable that uses the Django ORM to store webhooks. Redis is used to handle the message queue. dkwargs argument requires the following key/values: :event: A string representing an event. kwargs argument requires the following key/values :owner: The user who created/owns the event """ if "event" not in dkwargs: msg = "djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator." raise TypeError(msg) event = dkwargs['event'] if "owner" not in kwargs: msg = "djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function." raise TypeError(msg) owner = kwargs['owner'] if "identifier" not in kwargs: msg = "djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function." raise TypeError(msg) identifier = kwargs['identifier'] senderobj = DjangoRQSenderable( wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs ) # Add the webhook object just so it's around # TODO - error handling if this can't be found senderobj.webhook_target = WebhookTarget.objects.get( event=event, owner=owner, identifier=identifier ) # Get the target url and add it senderobj.url = senderobj.webhook_target.target_url # Get the payload. This overides the senderobj.payload property. senderobj.payload = senderobj.get_payload() # Get the creator and add it to the payload. senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD) # get the event and add it to the payload senderobj.payload['event'] = dkwargs['event'] return senderobj.send()
[ "This", "is", "an", "asynchronous", "sender", "callable", "that", "uses", "the", "Django", "ORM", "to", "store", "webhooks", ".", "Redis", "is", "used", "to", "handle", "the", "message", "queue", "." ]
pydanny/dj-webhooks
python
https://github.com/pydanny/dj-webhooks/blob/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/senders/redisq.py#L29-L82
[ "def", "worker", "(", "wrapped", ",", "dkwargs", ",", "hash_value", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "\"event\"", "not", "in", "dkwargs", ":", "msg", "=", "\"djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator.\"", "raise", "TypeError", "(", "msg", ")", "event", "=", "dkwargs", "[", "'event'", "]", "if", "\"owner\"", "not", "in", "kwargs", ":", "msg", "=", "\"djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function.\"", "raise", "TypeError", "(", "msg", ")", "owner", "=", "kwargs", "[", "'owner'", "]", "if", "\"identifier\"", "not", "in", "kwargs", ":", "msg", "=", "\"djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function.\"", "raise", "TypeError", "(", "msg", ")", "identifier", "=", "kwargs", "[", "'identifier'", "]", "senderobj", "=", "DjangoRQSenderable", "(", "wrapped", ",", "dkwargs", ",", "hash_value", ",", "WEBHOOK_ATTEMPTS", ",", "*", "args", ",", "*", "*", "kwargs", ")", "# Add the webhook object just so it's around", "# TODO - error handling if this can't be found", "senderobj", ".", "webhook_target", "=", "WebhookTarget", ".", "objects", ".", "get", "(", "event", "=", "event", ",", "owner", "=", "owner", ",", "identifier", "=", "identifier", ")", "# Get the target url and add it", "senderobj", ".", "url", "=", "senderobj", ".", "webhook_target", ".", "target_url", "# Get the payload. This overides the senderobj.payload property.", "senderobj", ".", "payload", "=", "senderobj", ".", "get_payload", "(", ")", "# Get the creator and add it to the payload.", "senderobj", ".", "payload", "[", "'owner'", "]", "=", "getattr", "(", "kwargs", "[", "'owner'", "]", ",", "WEBHOOK_OWNER_FIELD", ")", "# get the event and add it to the payload", "senderobj", ".", "payload", "[", "'event'", "]", "=", "dkwargs", "[", "'event'", "]", "return", "senderobj", ".", "send", "(", ")" ]
88e245bfe2020e96279af261d88bf8469ba469e5
valid
RedisLogSenderable.notify
TODO: Add code to lpush to redis stack rpop when stack hits size 'X'
djwebhooks/senders/redislog.py
def notify(self, message): """ TODO: Add code to lpush to redis stack rpop when stack hits size 'X' """ data = dict( payload=self.payload, attempt=self.attempt, success=self.success, response_message=self.response_content, hash_value=self.hash_value, response_status=self.response.status_code, notification=message, created=timezone.now() ) value = json.dumps(data, cls=StandardJSONEncoder) key = make_key(self.event, self.owner.username, self.identifier) redis.lpush(key, value)
def notify(self, message): """ TODO: Add code to lpush to redis stack rpop when stack hits size 'X' """ data = dict( payload=self.payload, attempt=self.attempt, success=self.success, response_message=self.response_content, hash_value=self.hash_value, response_status=self.response.status_code, notification=message, created=timezone.now() ) value = json.dumps(data, cls=StandardJSONEncoder) key = make_key(self.event, self.owner.username, self.identifier) redis.lpush(key, value)
[ "TODO", ":", "Add", "code", "to", "lpush", "to", "redis", "stack", "rpop", "when", "stack", "hits", "size", "X" ]
pydanny/dj-webhooks
python
https://github.com/pydanny/dj-webhooks/blob/88e245bfe2020e96279af261d88bf8469ba469e5/djwebhooks/senders/redislog.py#L50-L67
[ "def", "notify", "(", "self", ",", "message", ")", ":", "data", "=", "dict", "(", "payload", "=", "self", ".", "payload", ",", "attempt", "=", "self", ".", "attempt", ",", "success", "=", "self", ".", "success", ",", "response_message", "=", "self", ".", "response_content", ",", "hash_value", "=", "self", ".", "hash_value", ",", "response_status", "=", "self", ".", "response", ".", "status_code", ",", "notification", "=", "message", ",", "created", "=", "timezone", ".", "now", "(", ")", ")", "value", "=", "json", ".", "dumps", "(", "data", ",", "cls", "=", "StandardJSONEncoder", ")", "key", "=", "make_key", "(", "self", ".", "event", ",", "self", ".", "owner", ".", "username", ",", "self", ".", "identifier", ")", "redis", ".", "lpush", "(", "key", ",", "value", ")" ]
88e245bfe2020e96279af261d88bf8469ba469e5
valid
Faraday.send
Encodes data to slip protocol and then sends over serial port Uses the SlipLib module to convert the message data into SLIP format. The message is then sent over the serial port opened with the instance of the Faraday class used when invoking send(). Args: msg (bytes): Bytes format message to send over serial port. Returns: int: Number of bytes transmitted over the serial port.
faradayio/faraday.py
def send(self, msg): """Encodes data to slip protocol and then sends over serial port Uses the SlipLib module to convert the message data into SLIP format. The message is then sent over the serial port opened with the instance of the Faraday class used when invoking send(). Args: msg (bytes): Bytes format message to send over serial port. Returns: int: Number of bytes transmitted over the serial port. """ # Create a sliplib Driver slipDriver = sliplib.Driver() # Package data in slip format slipData = slipDriver.send(msg) # Send data over serial port res = self._serialPort.write(slipData) # Return number of bytes transmitted over serial port return res
def send(self, msg): """Encodes data to slip protocol and then sends over serial port Uses the SlipLib module to convert the message data into SLIP format. The message is then sent over the serial port opened with the instance of the Faraday class used when invoking send(). Args: msg (bytes): Bytes format message to send over serial port. Returns: int: Number of bytes transmitted over the serial port. """ # Create a sliplib Driver slipDriver = sliplib.Driver() # Package data in slip format slipData = slipDriver.send(msg) # Send data over serial port res = self._serialPort.write(slipData) # Return number of bytes transmitted over serial port return res
[ "Encodes", "data", "to", "slip", "protocol", "and", "then", "sends", "over", "serial", "port" ]
FaradayRF/faradayio
python
https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L32-L56
[ "def", "send", "(", "self", ",", "msg", ")", ":", "# Create a sliplib Driver", "slipDriver", "=", "sliplib", ".", "Driver", "(", ")", "# Package data in slip format", "slipData", "=", "slipDriver", ".", "send", "(", "msg", ")", "# Send data over serial port", "res", "=", "self", ".", "_serialPort", ".", "write", "(", "slipData", ")", "# Return number of bytes transmitted over serial port", "return", "res" ]
6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb
valid
Faraday.receive
Reads in data from a serial port (length bytes), decodes SLIP packets A function which reads from the serial port and then uses the SlipLib module to decode the SLIP protocol packets. Each message received is added to a receive buffer in SlipLib which is then returned. Args: length (int): Length to receive with serialPort.read(length) Returns: bytes: An iterator of the receive buffer
faradayio/faraday.py
def receive(self, length): """Reads in data from a serial port (length bytes), decodes SLIP packets A function which reads from the serial port and then uses the SlipLib module to decode the SLIP protocol packets. Each message received is added to a receive buffer in SlipLib which is then returned. Args: length (int): Length to receive with serialPort.read(length) Returns: bytes: An iterator of the receive buffer """ # Create a sliplib Driver slipDriver = sliplib.Driver() # Receive data from serial port ret = self._serialPort.read(length) # Decode data from slip format, stores msgs in sliplib.Driver.messages temp = slipDriver.receive(ret) return iter(temp)
def receive(self, length): """Reads in data from a serial port (length bytes), decodes SLIP packets A function which reads from the serial port and then uses the SlipLib module to decode the SLIP protocol packets. Each message received is added to a receive buffer in SlipLib which is then returned. Args: length (int): Length to receive with serialPort.read(length) Returns: bytes: An iterator of the receive buffer """ # Create a sliplib Driver slipDriver = sliplib.Driver() # Receive data from serial port ret = self._serialPort.read(length) # Decode data from slip format, stores msgs in sliplib.Driver.messages temp = slipDriver.receive(ret) return iter(temp)
[ "Reads", "in", "data", "from", "a", "serial", "port", "(", "length", "bytes", ")", "decodes", "SLIP", "packets" ]
FaradayRF/faradayio
python
https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L58-L81
[ "def", "receive", "(", "self", ",", "length", ")", ":", "# Create a sliplib Driver", "slipDriver", "=", "sliplib", ".", "Driver", "(", ")", "# Receive data from serial port", "ret", "=", "self", ".", "_serialPort", ".", "read", "(", "length", ")", "# Decode data from slip format, stores msgs in sliplib.Driver.messages", "temp", "=", "slipDriver", ".", "receive", "(", "ret", ")", "return", "iter", "(", "temp", ")" ]
6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb
valid
Monitor.checkTUN
Checks the TUN adapter for data and returns any that is found. Returns: packet: Data read from the TUN adapter
faradayio/faraday.py
def checkTUN(self): """ Checks the TUN adapter for data and returns any that is found. Returns: packet: Data read from the TUN adapter """ packet = self._TUN._tun.read(self._TUN._tun.mtu) return(packet)
def checkTUN(self): """ Checks the TUN adapter for data and returns any that is found. Returns: packet: Data read from the TUN adapter """ packet = self._TUN._tun.read(self._TUN._tun.mtu) return(packet)
[ "Checks", "the", "TUN", "adapter", "for", "data", "and", "returns", "any", "that", "is", "found", "." ]
FaradayRF/faradayio
python
https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L154-L162
[ "def", "checkTUN", "(", "self", ")", ":", "packet", "=", "self", ".", "_TUN", ".", "_tun", ".", "read", "(", "self", ".", "_TUN", ".", "_tun", ".", "mtu", ")", "return", "(", "packet", ")" ]
6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb
valid
Monitor.monitorTUN
Monitors the TUN adapter and sends data over serial port. Returns: ret: Number of bytes sent over serial port
faradayio/faraday.py
def monitorTUN(self): """ Monitors the TUN adapter and sends data over serial port. Returns: ret: Number of bytes sent over serial port """ packet = self.checkTUN() if packet: try: # TODO Do I need to strip off [4:] before sending? ret = self._faraday.send(packet) return ret except AttributeError as error: # AttributeError was encounteredthreading.Event() print("AttributeError")
def monitorTUN(self): """ Monitors the TUN adapter and sends data over serial port. Returns: ret: Number of bytes sent over serial port """ packet = self.checkTUN() if packet: try: # TODO Do I need to strip off [4:] before sending? ret = self._faraday.send(packet) return ret except AttributeError as error: # AttributeError was encounteredthreading.Event() print("AttributeError")
[ "Monitors", "the", "TUN", "adapter", "and", "sends", "data", "over", "serial", "port", "." ]
FaradayRF/faradayio
python
https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L164-L181
[ "def", "monitorTUN", "(", "self", ")", ":", "packet", "=", "self", ".", "checkTUN", "(", ")", "if", "packet", ":", "try", ":", "# TODO Do I need to strip off [4:] before sending?", "ret", "=", "self", ".", "_faraday", ".", "send", "(", "packet", ")", "return", "ret", "except", "AttributeError", "as", "error", ":", "# AttributeError was encounteredthreading.Event()", "print", "(", "\"AttributeError\"", ")" ]
6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb
valid
Monitor.checkSerial
Check the serial port for data to write to the TUN adapter.
faradayio/faraday.py
def checkSerial(self): """ Check the serial port for data to write to the TUN adapter. """ for item in self.rxSerial(self._TUN._tun.mtu): # print("about to send: {0}".format(item)) try: self._TUN._tun.write(item) except pytun.Error as error: print("pytun error writing: {0}".format(item)) print(error)
def checkSerial(self): """ Check the serial port for data to write to the TUN adapter. """ for item in self.rxSerial(self._TUN._tun.mtu): # print("about to send: {0}".format(item)) try: self._TUN._tun.write(item) except pytun.Error as error: print("pytun error writing: {0}".format(item)) print(error)
[ "Check", "the", "serial", "port", "for", "data", "to", "write", "to", "the", "TUN", "adapter", "." ]
FaradayRF/faradayio
python
https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L207-L217
[ "def", "checkSerial", "(", "self", ")", ":", "for", "item", "in", "self", ".", "rxSerial", "(", "self", ".", "_TUN", ".", "_tun", ".", "mtu", ")", ":", "# print(\"about to send: {0}\".format(item))", "try", ":", "self", ".", "_TUN", ".", "_tun", ".", "write", "(", "item", ")", "except", "pytun", ".", "Error", "as", "error", ":", "print", "(", "\"pytun error writing: {0}\"", ".", "format", "(", "item", ")", ")", "print", "(", "error", ")" ]
6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb
valid
Monitor.run
Wrapper function for TUN and serial port monitoring Wraps the necessary functions to loop over until self._isRunning threading.Event() is set(). This checks for data on the TUN/serial interfaces and then sends data over the appropriate interface. This function is automatically run when Threading.start() is called on the Monitor class.
faradayio/faraday.py
def run(self): """ Wrapper function for TUN and serial port monitoring Wraps the necessary functions to loop over until self._isRunning threading.Event() is set(). This checks for data on the TUN/serial interfaces and then sends data over the appropriate interface. This function is automatically run when Threading.start() is called on the Monitor class. """ while self.isRunning.is_set(): try: try: # self.checkTUN() self.monitorTUN() except timeout_decorator.TimeoutError as error: # No data received so just move on pass self.checkSerial() except KeyboardInterrupt: break
def run(self): """ Wrapper function for TUN and serial port monitoring Wraps the necessary functions to loop over until self._isRunning threading.Event() is set(). This checks for data on the TUN/serial interfaces and then sends data over the appropriate interface. This function is automatically run when Threading.start() is called on the Monitor class. """ while self.isRunning.is_set(): try: try: # self.checkTUN() self.monitorTUN() except timeout_decorator.TimeoutError as error: # No data received so just move on pass self.checkSerial() except KeyboardInterrupt: break
[ "Wrapper", "function", "for", "TUN", "and", "serial", "port", "monitoring" ]
FaradayRF/faradayio
python
https://github.com/FaradayRF/faradayio/blob/6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb/faradayio/faraday.py#L219-L240
[ "def", "run", "(", "self", ")", ":", "while", "self", ".", "isRunning", ".", "is_set", "(", ")", ":", "try", ":", "try", ":", "# self.checkTUN()", "self", ".", "monitorTUN", "(", ")", "except", "timeout_decorator", ".", "TimeoutError", "as", "error", ":", "# No data received so just move on", "pass", "self", ".", "checkSerial", "(", ")", "except", "KeyboardInterrupt", ":", "break" ]
6cf3af88bb4a83e5d2036e5cbdfaf8f0f01500bb
valid
SuperInlineModelAdmin._create_formsets
Helper function to generate formsets for add/change_view.
super_inlines/admin.py
def _create_formsets(self, request, obj, change, index, is_template): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = defaultdict(int) get_formsets_args = [request] if change: get_formsets_args.append(obj) base_prefix = self.get_formset(request).get_default_prefix() for FormSet, inline in self.get_formsets_with_inlines( *get_formsets_args): prefix = base_prefix + '-' + FormSet.get_default_prefix() if not is_template: prefix += '-%s' % index prefixes[prefix] += 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = { 'instance': obj, 'prefix': prefix, 'queryset': inline.get_queryset(request), } if request.method == 'POST': formset_params.update({ 'data': request.POST, 'files': request.FILES, 'save_as_new': '_saveasnew' in request.POST }) formset = FormSet(**formset_params) formset.has_parent = True formsets.append(formset) inline_instances.append(inline) return formsets, inline_instances
def _create_formsets(self, request, obj, change, index, is_template): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = defaultdict(int) get_formsets_args = [request] if change: get_formsets_args.append(obj) base_prefix = self.get_formset(request).get_default_prefix() for FormSet, inline in self.get_formsets_with_inlines( *get_formsets_args): prefix = base_prefix + '-' + FormSet.get_default_prefix() if not is_template: prefix += '-%s' % index prefixes[prefix] += 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = { 'instance': obj, 'prefix': prefix, 'queryset': inline.get_queryset(request), } if request.method == 'POST': formset_params.update({ 'data': request.POST, 'files': request.FILES, 'save_as_new': '_saveasnew' in request.POST }) formset = FormSet(**formset_params) formset.has_parent = True formsets.append(formset) inline_instances.append(inline) return formsets, inline_instances
[ "Helper", "function", "to", "generate", "formsets", "for", "add", "/", "change_view", "." ]
BertrandBordage/django-super-inlines
python
https://github.com/BertrandBordage/django-super-inlines/blob/75f1d110fc7aad4b31f73e54ce77337ffcb5c31a/super_inlines/admin.py#L35-L67
[ "def", "_create_formsets", "(", "self", ",", "request", ",", "obj", ",", "change", ",", "index", ",", "is_template", ")", ":", "formsets", "=", "[", "]", "inline_instances", "=", "[", "]", "prefixes", "=", "defaultdict", "(", "int", ")", "get_formsets_args", "=", "[", "request", "]", "if", "change", ":", "get_formsets_args", ".", "append", "(", "obj", ")", "base_prefix", "=", "self", ".", "get_formset", "(", "request", ")", ".", "get_default_prefix", "(", ")", "for", "FormSet", ",", "inline", "in", "self", ".", "get_formsets_with_inlines", "(", "*", "get_formsets_args", ")", ":", "prefix", "=", "base_prefix", "+", "'-'", "+", "FormSet", ".", "get_default_prefix", "(", ")", "if", "not", "is_template", ":", "prefix", "+=", "'-%s'", "%", "index", "prefixes", "[", "prefix", "]", "+=", "1", "if", "prefixes", "[", "prefix", "]", "!=", "1", "or", "not", "prefix", ":", "prefix", "=", "\"%s-%s\"", "%", "(", "prefix", ",", "prefixes", "[", "prefix", "]", ")", "formset_params", "=", "{", "'instance'", ":", "obj", ",", "'prefix'", ":", "prefix", ",", "'queryset'", ":", "inline", ".", "get_queryset", "(", "request", ")", ",", "}", "if", "request", ".", "method", "==", "'POST'", ":", "formset_params", ".", "update", "(", "{", "'data'", ":", "request", ".", "POST", ",", "'files'", ":", "request", ".", "FILES", ",", "'save_as_new'", ":", "'_saveasnew'", "in", "request", ".", "POST", "}", ")", "formset", "=", "FormSet", "(", "*", "*", "formset_params", ")", "formset", ".", "has_parent", "=", "True", "formsets", ".", "append", "(", "formset", ")", "inline_instances", ".", "append", "(", "inline", ")", "return", "formsets", ",", "inline_instances" ]
75f1d110fc7aad4b31f73e54ce77337ffcb5c31a
valid
RichTextWidget.get_field_settings
Get the field settings, if the configured setting is a string try to get a 'profile' from the global config.
djrichtextfield/widgets.py
def get_field_settings(self): """ Get the field settings, if the configured setting is a string try to get a 'profile' from the global config. """ field_settings = None if self.field_settings: if isinstance(self.field_settings, six.string_types): profiles = settings.CONFIG.get(self.PROFILE_KEY, {}) field_settings = profiles.get(self.field_settings) else: field_settings = self.field_settings return field_settings
def get_field_settings(self): """ Get the field settings, if the configured setting is a string try to get a 'profile' from the global config. """ field_settings = None if self.field_settings: if isinstance(self.field_settings, six.string_types): profiles = settings.CONFIG.get(self.PROFILE_KEY, {}) field_settings = profiles.get(self.field_settings) else: field_settings = self.field_settings return field_settings
[ "Get", "the", "field", "settings", "if", "the", "configured", "setting", "is", "a", "string", "try", "to", "get", "a", "profile", "from", "the", "global", "config", "." ]
jaap3/django-richtextfield
python
https://github.com/jaap3/django-richtextfield/blob/45890e33a4cab47bf0c067ce77d12f53219d6cf7/djrichtextfield/widgets.py#L45-L57
[ "def", "get_field_settings", "(", "self", ")", ":", "field_settings", "=", "None", "if", "self", ".", "field_settings", ":", "if", "isinstance", "(", "self", ".", "field_settings", ",", "six", ".", "string_types", ")", ":", "profiles", "=", "settings", ".", "CONFIG", ".", "get", "(", "self", ".", "PROFILE_KEY", ",", "{", "}", ")", "field_settings", "=", "profiles", ".", "get", "(", "self", ".", "field_settings", ")", "else", ":", "field_settings", "=", "self", ".", "field_settings", "return", "field_settings" ]
45890e33a4cab47bf0c067ce77d12f53219d6cf7
valid
RichTextWidget.value_from_datadict
Pass the submitted value through the sanitizer before returning it.
djrichtextfield/widgets.py
def value_from_datadict(self, *args, **kwargs): """ Pass the submitted value through the sanitizer before returning it. """ value = super(RichTextWidget, self).value_from_datadict( *args, **kwargs) if value is not None: value = self.get_sanitizer()(value) return value
def value_from_datadict(self, *args, **kwargs): """ Pass the submitted value through the sanitizer before returning it. """ value = super(RichTextWidget, self).value_from_datadict( *args, **kwargs) if value is not None: value = self.get_sanitizer()(value) return value
[ "Pass", "the", "submitted", "value", "through", "the", "sanitizer", "before", "returning", "it", "." ]
jaap3/django-richtextfield
python
https://github.com/jaap3/django-richtextfield/blob/45890e33a4cab47bf0c067ce77d12f53219d6cf7/djrichtextfield/widgets.py#L70-L78
[ "def", "value_from_datadict", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "value", "=", "super", "(", "RichTextWidget", ",", "self", ")", ".", "value_from_datadict", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "value", "is", "not", "None", ":", "value", "=", "self", ".", "get_sanitizer", "(", ")", "(", "value", ")", "return", "value" ]
45890e33a4cab47bf0c067ce77d12f53219d6cf7
valid
SanitizerMixin.get_sanitizer
Get the field sanitizer. The priority is the first defined in the following order: - A sanitizer provided to the widget. - Profile (field settings) specific sanitizer, if defined in settings. - Global sanitizer defined in settings. - Simple no-op sanitizer which just returns the provided value.
djrichtextfield/sanitizer.py
def get_sanitizer(self): """ Get the field sanitizer. The priority is the first defined in the following order: - A sanitizer provided to the widget. - Profile (field settings) specific sanitizer, if defined in settings. - Global sanitizer defined in settings. - Simple no-op sanitizer which just returns the provided value. """ sanitizer = self.sanitizer if not sanitizer: default_sanitizer = settings.CONFIG.get(self.SANITIZER_KEY) field_settings = getattr(self, 'field_settings', None) if isinstance(field_settings, six.string_types): profiles = settings.CONFIG.get(self.SANITIZER_PROFILES_KEY, {}) sanitizer = profiles.get(field_settings, default_sanitizer) else: sanitizer = default_sanitizer if isinstance(sanitizer, six.string_types): sanitizer = import_string(sanitizer) return sanitizer or noop
def get_sanitizer(self): """ Get the field sanitizer. The priority is the first defined in the following order: - A sanitizer provided to the widget. - Profile (field settings) specific sanitizer, if defined in settings. - Global sanitizer defined in settings. - Simple no-op sanitizer which just returns the provided value. """ sanitizer = self.sanitizer if not sanitizer: default_sanitizer = settings.CONFIG.get(self.SANITIZER_KEY) field_settings = getattr(self, 'field_settings', None) if isinstance(field_settings, six.string_types): profiles = settings.CONFIG.get(self.SANITIZER_PROFILES_KEY, {}) sanitizer = profiles.get(field_settings, default_sanitizer) else: sanitizer = default_sanitizer if isinstance(sanitizer, six.string_types): sanitizer = import_string(sanitizer) return sanitizer or noop
[ "Get", "the", "field", "sanitizer", "." ]
jaap3/django-richtextfield
python
https://github.com/jaap3/django-richtextfield/blob/45890e33a4cab47bf0c067ce77d12f53219d6cf7/djrichtextfield/sanitizer.py#L27-L52
[ "def", "get_sanitizer", "(", "self", ")", ":", "sanitizer", "=", "self", ".", "sanitizer", "if", "not", "sanitizer", ":", "default_sanitizer", "=", "settings", ".", "CONFIG", ".", "get", "(", "self", ".", "SANITIZER_KEY", ")", "field_settings", "=", "getattr", "(", "self", ",", "'field_settings'", ",", "None", ")", "if", "isinstance", "(", "field_settings", ",", "six", ".", "string_types", ")", ":", "profiles", "=", "settings", ".", "CONFIG", ".", "get", "(", "self", ".", "SANITIZER_PROFILES_KEY", ",", "{", "}", ")", "sanitizer", "=", "profiles", ".", "get", "(", "field_settings", ",", "default_sanitizer", ")", "else", ":", "sanitizer", "=", "default_sanitizer", "if", "isinstance", "(", "sanitizer", ",", "six", ".", "string_types", ")", ":", "sanitizer", "=", "import_string", "(", "sanitizer", ")", "return", "sanitizer", "or", "noop" ]
45890e33a4cab47bf0c067ce77d12f53219d6cf7
valid
heappop_max
Maxheap version of a heappop.
heapq_max/heapq_max.py
def heappop_max(heap): """Maxheap version of a heappop.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup_max(heap, 0) return returnitem return lastelt
def heappop_max(heap): """Maxheap version of a heappop.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup_max(heap, 0) return returnitem return lastelt
[ "Maxheap", "version", "of", "a", "heappop", "." ]
he-zhe/heapq_max
python
https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L28-L36
[ "def", "heappop_max", "(", "heap", ")", ":", "lastelt", "=", "heap", ".", "pop", "(", ")", "# raises appropriate IndexError if heap is empty", "if", "heap", ":", "returnitem", "=", "heap", "[", "0", "]", "heap", "[", "0", "]", "=", "lastelt", "_siftup_max", "(", "heap", ",", "0", ")", "return", "returnitem", "return", "lastelt" ]
2861f32319ab1981e3531101eea5d20434a99c53
valid
heapreplace_max
Maxheap version of a heappop followed by a heappush.
heapq_max/heapq_max.py
def heapreplace_max(heap, item): """Maxheap version of a heappop followed by a heappush.""" returnitem = heap[0] # raises appropriate IndexError if heap is empty heap[0] = item _siftup_max(heap, 0) return returnitem
def heapreplace_max(heap, item): """Maxheap version of a heappop followed by a heappush.""" returnitem = heap[0] # raises appropriate IndexError if heap is empty heap[0] = item _siftup_max(heap, 0) return returnitem
[ "Maxheap", "version", "of", "a", "heappop", "followed", "by", "a", "heappush", "." ]
he-zhe/heapq_max
python
https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L39-L44
[ "def", "heapreplace_max", "(", "heap", ",", "item", ")", ":", "returnitem", "=", "heap", "[", "0", "]", "# raises appropriate IndexError if heap is empty", "heap", "[", "0", "]", "=", "item", "_siftup_max", "(", "heap", ",", "0", ")", "return", "returnitem" ]
2861f32319ab1981e3531101eea5d20434a99c53
valid
heappush_max
Push item onto heap, maintaining the heap invariant.
heapq_max/heapq_max.py
def heappush_max(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown_max(heap, 0, len(heap) - 1)
def heappush_max(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown_max(heap, 0, len(heap) - 1)
[ "Push", "item", "onto", "heap", "maintaining", "the", "heap", "invariant", "." ]
he-zhe/heapq_max
python
https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L47-L50
[ "def", "heappush_max", "(", "heap", ",", "item", ")", ":", "heap", ".", "append", "(", "item", ")", "_siftdown_max", "(", "heap", ",", "0", ",", "len", "(", "heap", ")", "-", "1", ")" ]
2861f32319ab1981e3531101eea5d20434a99c53
valid
heappushpop_max
Fast version of a heappush followed by a heappop.
heapq_max/heapq_max.py
def heappushpop_max(heap, item): """Fast version of a heappush followed by a heappop.""" if heap and heap[0] > item: # if item >= heap[0], it will be popped immediately after pushed item, heap[0] = heap[0], item _siftup_max(heap, 0) return item
def heappushpop_max(heap, item): """Fast version of a heappush followed by a heappop.""" if heap and heap[0] > item: # if item >= heap[0], it will be popped immediately after pushed item, heap[0] = heap[0], item _siftup_max(heap, 0) return item
[ "Fast", "version", "of", "a", "heappush", "followed", "by", "a", "heappop", "." ]
he-zhe/heapq_max
python
https://github.com/he-zhe/heapq_max/blob/2861f32319ab1981e3531101eea5d20434a99c53/heapq_max/heapq_max.py#L53-L59
[ "def", "heappushpop_max", "(", "heap", ",", "item", ")", ":", "if", "heap", "and", "heap", "[", "0", "]", ">", "item", ":", "# if item >= heap[0], it will be popped immediately after pushed", "item", ",", "heap", "[", "0", "]", "=", "heap", "[", "0", "]", ",", "item", "_siftup_max", "(", "heap", ",", "0", ")", "return", "item" ]
2861f32319ab1981e3531101eea5d20434a99c53
valid
validate_response
Decorator to validate responses from QTM
qtm/qrt.py
def validate_response(expected_responses): """ Decorator to validate responses from QTM """ def internal_decorator(function): @wraps(function) async def wrapper(*args, **kwargs): response = await function(*args, **kwargs) for expected_response in expected_responses: if response.startswith(expected_response): return response raise QRTCommandException( "Expected %s but got %s" % (expected_responses, response) ) return wrapper return internal_decorator
def validate_response(expected_responses): """ Decorator to validate responses from QTM """ def internal_decorator(function): @wraps(function) async def wrapper(*args, **kwargs): response = await function(*args, **kwargs) for expected_response in expected_responses: if response.startswith(expected_response): return response raise QRTCommandException( "Expected %s but got %s" % (expected_responses, response) ) return wrapper return internal_decorator
[ "Decorator", "to", "validate", "responses", "from", "QTM" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L15-L34
[ "def", "validate_response", "(", "expected_responses", ")", ":", "def", "internal_decorator", "(", "function", ")", ":", "@", "wraps", "(", "function", ")", "async", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "await", "function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "for", "expected_response", "in", "expected_responses", ":", "if", "response", ".", "startswith", "(", "expected_response", ")", ":", "return", "response", "raise", "QRTCommandException", "(", "\"Expected %s but got %s\"", "%", "(", "expected_responses", ",", "response", ")", ")", "return", "wrapper", "return", "internal_decorator" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
connect
Async function to connect to QTM :param host: Address of the computer running QTM. :param port: Port number to connect to, should be the port configured for little endian. :param version: What version of the protocol to use, tested for 1.17 and above but could work with lower versions as well. :param on_disconnect: Function to be called when a disconnect from QTM occurs. :param on_event: Function to be called when there's an event from QTM. :param timeout: The default timeout time for calls to QTM. :param loop: Alternative event loop, will use asyncio default if None. :rtype: A :class:`.QRTConnection`
qtm/qrt.py
async def connect( host, port=22223, version="1.19", on_event=None, on_disconnect=None, timeout=5, loop=None, ) -> QRTConnection: """Async function to connect to QTM :param host: Address of the computer running QTM. :param port: Port number to connect to, should be the port configured for little endian. :param version: What version of the protocol to use, tested for 1.17 and above but could work with lower versions as well. :param on_disconnect: Function to be called when a disconnect from QTM occurs. :param on_event: Function to be called when there's an event from QTM. :param timeout: The default timeout time for calls to QTM. :param loop: Alternative event loop, will use asyncio default if None. :rtype: A :class:`.QRTConnection` """ loop = loop or asyncio.get_event_loop() try: _, protocol = await loop.create_connection( lambda: QTMProtocol( loop=loop, on_event=on_event, on_disconnect=on_disconnect ), host, port, ) except (ConnectionRefusedError, TimeoutError, OSError) as exception: LOG.error(exception) return None try: await protocol.set_version(version) except QRTCommandException as exception: LOG.error(Exception) return None except TypeError as exception: # TODO: fix test requiring this (test_connect_set_version) LOG.error(exception) return None return QRTConnection(protocol, timeout=timeout)
async def connect( host, port=22223, version="1.19", on_event=None, on_disconnect=None, timeout=5, loop=None, ) -> QRTConnection: """Async function to connect to QTM :param host: Address of the computer running QTM. :param port: Port number to connect to, should be the port configured for little endian. :param version: What version of the protocol to use, tested for 1.17 and above but could work with lower versions as well. :param on_disconnect: Function to be called when a disconnect from QTM occurs. :param on_event: Function to be called when there's an event from QTM. :param timeout: The default timeout time for calls to QTM. :param loop: Alternative event loop, will use asyncio default if None. :rtype: A :class:`.QRTConnection` """ loop = loop or asyncio.get_event_loop() try: _, protocol = await loop.create_connection( lambda: QTMProtocol( loop=loop, on_event=on_event, on_disconnect=on_disconnect ), host, port, ) except (ConnectionRefusedError, TimeoutError, OSError) as exception: LOG.error(exception) return None try: await protocol.set_version(version) except QRTCommandException as exception: LOG.error(Exception) return None except TypeError as exception: # TODO: fix test requiring this (test_connect_set_version) LOG.error(exception) return None return QRTConnection(protocol, timeout=timeout)
[ "Async", "function", "to", "connect", "to", "QTM" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L310-L355
[ "async", "def", "connect", "(", "host", ",", "port", "=", "22223", ",", "version", "=", "\"1.19\"", ",", "on_event", "=", "None", ",", "on_disconnect", "=", "None", ",", "timeout", "=", "5", ",", "loop", "=", "None", ",", ")", "->", "QRTConnection", ":", "loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "try", ":", "_", ",", "protocol", "=", "await", "loop", ".", "create_connection", "(", "lambda", ":", "QTMProtocol", "(", "loop", "=", "loop", ",", "on_event", "=", "on_event", ",", "on_disconnect", "=", "on_disconnect", ")", ",", "host", ",", "port", ",", ")", "except", "(", "ConnectionRefusedError", ",", "TimeoutError", ",", "OSError", ")", "as", "exception", ":", "LOG", ".", "error", "(", "exception", ")", "return", "None", "try", ":", "await", "protocol", ".", "set_version", "(", "version", ")", "except", "QRTCommandException", "as", "exception", ":", "LOG", ".", "error", "(", "Exception", ")", "return", "None", "except", "TypeError", "as", "exception", ":", "# TODO: fix test requiring this (test_connect_set_version)", "LOG", ".", "error", "(", "exception", ")", "return", "None", "return", "QRTConnection", "(", "protocol", ",", "timeout", "=", "timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.qtm_version
Get the QTM version.
qtm/qrt.py
async def qtm_version(self): """Get the QTM version. """ return await asyncio.wait_for( self._protocol.send_command("qtmversion"), timeout=self._timeout )
async def qtm_version(self): """Get the QTM version. """ return await asyncio.wait_for( self._protocol.send_command("qtmversion"), timeout=self._timeout )
[ "Get", "the", "QTM", "version", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L56-L61
[ "async", "def", "qtm_version", "(", "self", ")", ":", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "\"qtmversion\"", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.byte_order
Get the byte order used when communicating (should only ever be little endian using this library).
qtm/qrt.py
async def byte_order(self): """Get the byte order used when communicating (should only ever be little endian using this library). """ return await asyncio.wait_for( self._protocol.send_command("byteorder"), timeout=self._timeout )
async def byte_order(self): """Get the byte order used when communicating (should only ever be little endian using this library). """ return await asyncio.wait_for( self._protocol.send_command("byteorder"), timeout=self._timeout )
[ "Get", "the", "byte", "order", "used", "when", "communicating", "(", "should", "only", "ever", "be", "little", "endian", "using", "this", "library", ")", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L63-L69
[ "async", "def", "byte_order", "(", "self", ")", ":", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "\"byteorder\"", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.get_state
Get the latest state change of QTM. If the :func:`~qtm.connect` on_event callback was set the callback will be called as well. :rtype: A :class:`qtm.QRTEvent`
qtm/qrt.py
async def get_state(self): """Get the latest state change of QTM. If the :func:`~qtm.connect` on_event callback was set the callback will be called as well. :rtype: A :class:`qtm.QRTEvent` """ await self._protocol.send_command("getstate", callback=False) return await self._protocol.await_event()
async def get_state(self): """Get the latest state change of QTM. If the :func:`~qtm.connect` on_event callback was set the callback will be called as well. :rtype: A :class:`qtm.QRTEvent` """ await self._protocol.send_command("getstate", callback=False) return await self._protocol.await_event()
[ "Get", "the", "latest", "state", "change", "of", "QTM", ".", "If", "the", ":", "func", ":", "~qtm", ".", "connect", "on_event", "callback", "was", "set", "the", "callback", "will", "be", "called", "as", "well", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L71-L78
[ "async", "def", "get_state", "(", "self", ")", ":", "await", "self", ".", "_protocol", ".", "send_command", "(", "\"getstate\"", ",", "callback", "=", "False", ")", "return", "await", "self", ".", "_protocol", ".", "await_event", "(", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.await_event
Wait for an event from QTM. :param event: A :class:`qtm.QRTEvent` to wait for a specific event. Otherwise wait for any event. :param timeout: Max time to wait for event. :rtype: A :class:`qtm.QRTEvent`
qtm/qrt.py
async def await_event(self, event=None, timeout=30): """Wait for an event from QTM. :param event: A :class:`qtm.QRTEvent` to wait for a specific event. Otherwise wait for any event. :param timeout: Max time to wait for event. :rtype: A :class:`qtm.QRTEvent` """ return await self._protocol.await_event(event, timeout=timeout)
async def await_event(self, event=None, timeout=30): """Wait for an event from QTM. :param event: A :class:`qtm.QRTEvent` to wait for a specific event. Otherwise wait for any event. :param timeout: Max time to wait for event. :rtype: A :class:`qtm.QRTEvent` """ return await self._protocol.await_event(event, timeout=timeout)
[ "Wait", "for", "an", "event", "from", "QTM", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L80-L90
[ "async", "def", "await_event", "(", "self", ",", "event", "=", "None", ",", "timeout", "=", "30", ")", ":", "return", "await", "self", ".", "_protocol", ".", "await_event", "(", "event", ",", "timeout", "=", "timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.get_parameters
Get the settings for the requested component(s) of QTM in XML format. :param parameters: A list of parameters to request. Could be 'all' or any combination of 'general', '3d', '6d', 'analog', 'force', 'gazevector', 'image'. :rtype: An XML string containing the requested settings. See QTM RT Documentation for details.
qtm/qrt.py
async def get_parameters(self, parameters=None): """Get the settings for the requested component(s) of QTM in XML format. :param parameters: A list of parameters to request. Could be 'all' or any combination of 'general', '3d', '6d', 'analog', 'force', 'gazevector', 'image'. :rtype: An XML string containing the requested settings. See QTM RT Documentation for details. """ if parameters is None: parameters = ["all"] else: for parameter in parameters: if not parameter in [ "all", "general", "3d", "6d", "analog", "force", "gazevector", "image", "skeleton", "skeleton:global", ]: raise QRTCommandException("%s is not a valid parameter" % parameter) cmd = "getparameters %s" % " ".join(parameters) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def get_parameters(self, parameters=None): """Get the settings for the requested component(s) of QTM in XML format. :param parameters: A list of parameters to request. Could be 'all' or any combination of 'general', '3d', '6d', 'analog', 'force', 'gazevector', 'image'. :rtype: An XML string containing the requested settings. See QTM RT Documentation for details. """ if parameters is None: parameters = ["all"] else: for parameter in parameters: if not parameter in [ "all", "general", "3d", "6d", "analog", "force", "gazevector", "image", "skeleton", "skeleton:global", ]: raise QRTCommandException("%s is not a valid parameter" % parameter) cmd = "getparameters %s" % " ".join(parameters) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Get", "the", "settings", "for", "the", "requested", "component", "(", "s", ")", "of", "QTM", "in", "XML", "format", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L92-L123
[ "async", "def", "get_parameters", "(", "self", ",", "parameters", "=", "None", ")", ":", "if", "parameters", "is", "None", ":", "parameters", "=", "[", "\"all\"", "]", "else", ":", "for", "parameter", "in", "parameters", ":", "if", "not", "parameter", "in", "[", "\"all\"", ",", "\"general\"", ",", "\"3d\"", ",", "\"6d\"", ",", "\"analog\"", ",", "\"force\"", ",", "\"gazevector\"", ",", "\"image\"", ",", "\"skeleton\"", ",", "\"skeleton:global\"", ",", "]", ":", "raise", "QRTCommandException", "(", "\"%s is not a valid parameter\"", "%", "parameter", ")", "cmd", "=", "\"getparameters %s\"", "%", "\" \"", ".", "join", "(", "parameters", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.get_current_frame
Get measured values from QTM for a single frame. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: A :class:`qtm.QRTPacket` containing requested components
qtm/qrt.py
async def get_current_frame(self, components=None) -> QRTPacket: """Get measured values from QTM for a single frame. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: A :class:`qtm.QRTPacket` containing requested components """ if components is None: components = ["all"] else: _validate_components(components) cmd = "getcurrentframe %s" % " ".join(components) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def get_current_frame(self, components=None) -> QRTPacket: """Get measured values from QTM for a single frame. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: A :class:`qtm.QRTPacket` containing requested components """ if components is None: components = ["all"] else: _validate_components(components) cmd = "getcurrentframe %s" % " ".join(components) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Get", "measured", "values", "from", "QTM", "for", "a", "single", "frame", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L125-L145
[ "async", "def", "get_current_frame", "(", "self", ",", "components", "=", "None", ")", "->", "QRTPacket", ":", "if", "components", "is", "None", ":", "components", "=", "[", "\"all\"", "]", "else", ":", "_validate_components", "(", "components", ")", "cmd", "=", "\"getcurrentframe %s\"", "%", "\" \"", ".", "join", "(", "components", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.stream_frames
Stream measured frames from QTM until :func:`~qtm.QRTConnection.stream_frames_stop` is called. :param frames: Which frames to receive, possible values are 'allframes', 'frequency:n' or 'frequencydivisor:n' where n should be desired value. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: The string 'Ok' if successful
qtm/qrt.py
async def stream_frames(self, frames="allframes", components=None, on_packet=None): """Stream measured frames from QTM until :func:`~qtm.QRTConnection.stream_frames_stop` is called. :param frames: Which frames to receive, possible values are 'allframes', 'frequency:n' or 'frequencydivisor:n' where n should be desired value. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: The string 'Ok' if successful """ if components is None: components = ["all"] else: _validate_components(components) self._protocol.set_on_packet(on_packet) cmd = "streamframes %s %s" % (frames, " ".join(components)) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def stream_frames(self, frames="allframes", components=None, on_packet=None): """Stream measured frames from QTM until :func:`~qtm.QRTConnection.stream_frames_stop` is called. :param frames: Which frames to receive, possible values are 'allframes', 'frequency:n' or 'frequencydivisor:n' where n should be desired value. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: The string 'Ok' if successful """ if components is None: components = ["all"] else: _validate_components(components) self._protocol.set_on_packet(on_packet) cmd = "streamframes %s %s" % (frames, " ".join(components)) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Stream", "measured", "frames", "from", "QTM", "until", ":", "func", ":", "~qtm", ".", "QRTConnection", ".", "stream_frames_stop", "is", "called", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L147-L173
[ "async", "def", "stream_frames", "(", "self", ",", "frames", "=", "\"allframes\"", ",", "components", "=", "None", ",", "on_packet", "=", "None", ")", ":", "if", "components", "is", "None", ":", "components", "=", "[", "\"all\"", "]", "else", ":", "_validate_components", "(", "components", ")", "self", ".", "_protocol", ".", "set_on_packet", "(", "on_packet", ")", "cmd", "=", "\"streamframes %s %s\"", "%", "(", "frames", ",", "\" \"", ".", "join", "(", "components", ")", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.stream_frames_stop
Stop streaming frames.
qtm/qrt.py
async def stream_frames_stop(self): """Stop streaming frames.""" self._protocol.set_on_packet(None) cmd = "streamframes stop" await self._protocol.send_command(cmd, callback=False)
async def stream_frames_stop(self): """Stop streaming frames.""" self._protocol.set_on_packet(None) cmd = "streamframes stop" await self._protocol.send_command(cmd, callback=False)
[ "Stop", "streaming", "frames", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L175-L181
[ "async", "def", "stream_frames_stop", "(", "self", ")", ":", "self", ".", "_protocol", ".", "set_on_packet", "(", "None", ")", "cmd", "=", "\"streamframes stop\"", "await", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ",", "callback", "=", "False", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.take_control
Take control of QTM. :param password: Password as entered in QTM.
qtm/qrt.py
async def take_control(self, password): """Take control of QTM. :param password: Password as entered in QTM. """ cmd = "takecontrol %s" % password return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def take_control(self, password): """Take control of QTM. :param password: Password as entered in QTM. """ cmd = "takecontrol %s" % password return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Take", "control", "of", "QTM", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L184-L192
[ "async", "def", "take_control", "(", "self", ",", "password", ")", ":", "cmd", "=", "\"takecontrol %s\"", "%", "password", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.release_control
Release control of QTM.
qtm/qrt.py
async def release_control(self): """Release control of QTM. """ cmd = "releasecontrol" return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def release_control(self): """Release control of QTM. """ cmd = "releasecontrol" return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Release", "control", "of", "QTM", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L195-L202
[ "async", "def", "release_control", "(", "self", ")", ":", "cmd", "=", "\"releasecontrol\"", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.start
Start RT from file. You need to be in control of QTM to be able to do this.
qtm/qrt.py
async def start(self, rtfromfile=False): """Start RT from file. You need to be in control of QTM to be able to do this. """ cmd = "start" + (" rtfromfile" if rtfromfile else "") return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def start(self, rtfromfile=False): """Start RT from file. You need to be in control of QTM to be able to do this. """ cmd = "start" + (" rtfromfile" if rtfromfile else "") return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Start", "RT", "from", "file", ".", "You", "need", "to", "be", "in", "control", "of", "QTM", "to", "be", "able", "to", "do", "this", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L230-L236
[ "async", "def", "start", "(", "self", ",", "rtfromfile", "=", "False", ")", ":", "cmd", "=", "\"start\"", "+", "(", "\" rtfromfile\"", "if", "rtfromfile", "else", "\"\"", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.load
Load a measurement. :param filename: Path to measurement you want to load.
qtm/qrt.py
async def load(self, filename): """Load a measurement. :param filename: Path to measurement you want to load. """ cmd = "load %s" % filename return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def load(self, filename): """Load a measurement. :param filename: Path to measurement you want to load. """ cmd = "load %s" % filename return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Load", "a", "measurement", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L247-L255
[ "async", "def", "load", "(", "self", ",", "filename", ")", ":", "cmd", "=", "\"load %s\"", "%", "filename", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.save
Save a measurement. :param filename: Filename you wish to save as. :param overwrite: If QTM should overwrite existing measurement.
qtm/qrt.py
async def save(self, filename, overwrite=False): """Save a measurement. :param filename: Filename you wish to save as. :param overwrite: If QTM should overwrite existing measurement. """ cmd = "save %s%s" % (filename, " overwrite" if overwrite else "") return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def save(self, filename, overwrite=False): """Save a measurement. :param filename: Filename you wish to save as. :param overwrite: If QTM should overwrite existing measurement. """ cmd = "save %s%s" % (filename, " overwrite" if overwrite else "") return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Save", "a", "measurement", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L258-L267
[ "async", "def", "save", "(", "self", ",", "filename", ",", "overwrite", "=", "False", ")", ":", "cmd", "=", "\"save %s%s\"", "%", "(", "filename", ",", "\" overwrite\"", "if", "overwrite", "else", "\"\"", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.load_project
Load a project. :param project_path: Path to project you want to load.
qtm/qrt.py
async def load_project(self, project_path): """Load a project. :param project_path: Path to project you want to load. """ cmd = "loadproject %s" % project_path return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def load_project(self, project_path): """Load a project. :param project_path: Path to project you want to load. """ cmd = "loadproject %s" % project_path return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Load", "a", "project", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L270-L278
[ "async", "def", "load_project", "(", "self", ",", "project_path", ")", ":", "cmd", "=", "\"loadproject %s\"", "%", "project_path", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.set_qtm_event
Set event in QTM.
qtm/qrt.py
async def set_qtm_event(self, event=None): """Set event in QTM.""" cmd = "event%s" % ("" if event is None else " " + event) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
async def set_qtm_event(self, event=None): """Set event in QTM.""" cmd = "event%s" % ("" if event is None else " " + event) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
[ "Set", "event", "in", "QTM", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L289-L294
[ "async", "def", "set_qtm_event", "(", "self", ",", "event", "=", "None", ")", ":", "cmd", "=", "\"event%s\"", "%", "(", "\"\"", "if", "event", "is", "None", "else", "\" \"", "+", "event", ")", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "cmd", ")", ",", "timeout", "=", "self", ".", "_timeout", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTConnection.send_xml
Used to update QTM settings, see QTM RT protocol for more information. :param xml: XML document as a str. See QTM RT Documentation for details.
qtm/qrt.py
async def send_xml(self, xml): """Used to update QTM settings, see QTM RT protocol for more information. :param xml: XML document as a str. See QTM RT Documentation for details. """ return await asyncio.wait_for( self._protocol.send_command(xml, command_type=QRTPacketType.PacketXML), timeout=self._timeout, )
async def send_xml(self, xml): """Used to update QTM settings, see QTM RT protocol for more information. :param xml: XML document as a str. See QTM RT Documentation for details. """ return await asyncio.wait_for( self._protocol.send_command(xml, command_type=QRTPacketType.PacketXML), timeout=self._timeout, )
[ "Used", "to", "update", "QTM", "settings", "see", "QTM", "RT", "protocol", "for", "more", "information", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/qrt.py#L296-L304
[ "async", "def", "send_xml", "(", "self", ",", "xml", ")", ":", "return", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_protocol", ".", "send_command", "(", "xml", ",", "command_type", "=", "QRTPacketType", ".", "PacketXML", ")", ",", "timeout", "=", "self", ".", "_timeout", ",", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
Receiver.data_received
Received from QTM and route accordingly
qtm/receiver.py
def data_received(self, data): """ Received from QTM and route accordingly """ self._received_data += data h_size = RTheader.size data = self._received_data size, type_ = RTheader.unpack_from(data, 0) while len(data) >= size: self._parse_received(data[h_size:size], type_) data = data[size:] if len(data) < h_size: break size, type_ = RTheader.unpack_from(data, 0) self._received_data = data
def data_received(self, data): """ Received from QTM and route accordingly """ self._received_data += data h_size = RTheader.size data = self._received_data size, type_ = RTheader.unpack_from(data, 0) while len(data) >= size: self._parse_received(data[h_size:size], type_) data = data[size:] if len(data) < h_size: break size, type_ = RTheader.unpack_from(data, 0) self._received_data = data
[ "Received", "from", "QTM", "and", "route", "accordingly" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/receiver.py#L15-L32
[ "def", "data_received", "(", "self", ",", "data", ")", ":", "self", ".", "_received_data", "+=", "data", "h_size", "=", "RTheader", ".", "size", "data", "=", "self", ".", "_received_data", "size", ",", "type_", "=", "RTheader", ".", "unpack_from", "(", "data", ",", "0", ")", "while", "len", "(", "data", ")", ">=", "size", ":", "self", ".", "_parse_received", "(", "data", "[", "h_size", ":", "size", "]", ",", "type_", ")", "data", "=", "data", "[", "size", ":", "]", "if", "len", "(", "data", ")", "<", "h_size", ":", "break", "size", ",", "type_", "=", "RTheader", ".", "unpack_from", "(", "data", ",", "0", ")", "self", ".", "_received_data", "=", "data" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_analog
Get analog data.
qtm/packet.py
def get_analog(self, component_info=None, data=None, component_position=None): """Get analog data.""" components = [] append_components = components.append for _ in range(component_info.device_count): component_position, device = QRTPacket._get_exact( RTAnalogDevice, data, component_position ) if device.sample_count > 0: component_position, sample_number = QRTPacket._get_exact( RTSampleNumber, data, component_position ) RTAnalogChannel.format = struct.Struct( RTAnalogChannel.format_str % device.sample_count ) for _ in range(device.channel_count): component_position, channel = QRTPacket._get_tuple( RTAnalogChannel, data, component_position ) append_components((device, sample_number, channel)) return components
def get_analog(self, component_info=None, data=None, component_position=None): """Get analog data.""" components = [] append_components = components.append for _ in range(component_info.device_count): component_position, device = QRTPacket._get_exact( RTAnalogDevice, data, component_position ) if device.sample_count > 0: component_position, sample_number = QRTPacket._get_exact( RTSampleNumber, data, component_position ) RTAnalogChannel.format = struct.Struct( RTAnalogChannel.format_str % device.sample_count ) for _ in range(device.channel_count): component_position, channel = QRTPacket._get_tuple( RTAnalogChannel, data, component_position ) append_components((device, sample_number, channel)) return components
[ "Get", "analog", "data", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L318-L340
[ "def", "get_analog", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "device_count", ")", ":", "component_position", ",", "device", "=", "QRTPacket", ".", "_get_exact", "(", "RTAnalogDevice", ",", "data", ",", "component_position", ")", "if", "device", ".", "sample_count", ">", "0", ":", "component_position", ",", "sample_number", "=", "QRTPacket", ".", "_get_exact", "(", "RTSampleNumber", ",", "data", ",", "component_position", ")", "RTAnalogChannel", ".", "format", "=", "struct", ".", "Struct", "(", "RTAnalogChannel", ".", "format_str", "%", "device", ".", "sample_count", ")", "for", "_", "in", "range", "(", "device", ".", "channel_count", ")", ":", "component_position", ",", "channel", "=", "QRTPacket", ".", "_get_tuple", "(", "RTAnalogChannel", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "device", ",", "sample_number", ",", "channel", ")", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_analog_single
Get a single analog data channel.
qtm/packet.py
def get_analog_single( self, component_info=None, data=None, component_position=None ): """Get a single analog data channel.""" components = [] append_components = components.append for _ in range(component_info.device_count): component_position, device = QRTPacket._get_exact( RTAnalogDeviceSingle, data, component_position ) RTAnalogDeviceSamples.format = struct.Struct( RTAnalogDeviceSamples.format_str % device.channel_count ) component_position, sample = QRTPacket._get_tuple( RTAnalogDeviceSamples, data, component_position ) append_components((device, sample)) return components
def get_analog_single( self, component_info=None, data=None, component_position=None ): """Get a single analog data channel.""" components = [] append_components = components.append for _ in range(component_info.device_count): component_position, device = QRTPacket._get_exact( RTAnalogDeviceSingle, data, component_position ) RTAnalogDeviceSamples.format = struct.Struct( RTAnalogDeviceSamples.format_str % device.channel_count ) component_position, sample = QRTPacket._get_tuple( RTAnalogDeviceSamples, data, component_position ) append_components((device, sample)) return components
[ "Get", "a", "single", "analog", "data", "channel", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L343-L361
[ "def", "get_analog_single", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "device_count", ")", ":", "component_position", ",", "device", "=", "QRTPacket", ".", "_get_exact", "(", "RTAnalogDeviceSingle", ",", "data", ",", "component_position", ")", "RTAnalogDeviceSamples", ".", "format", "=", "struct", ".", "Struct", "(", "RTAnalogDeviceSamples", ".", "format_str", "%", "device", ".", "channel_count", ")", "component_position", ",", "sample", "=", "QRTPacket", ".", "_get_tuple", "(", "RTAnalogDeviceSamples", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "device", ",", "sample", ")", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_force
Get force data.
qtm/packet.py
def get_force(self, component_info=None, data=None, component_position=None): """Get force data.""" components = [] append_components = components.append for _ in range(component_info.plate_count): component_position, plate = QRTPacket._get_exact( RTForcePlate, data, component_position ) force_list = [] for _ in range(plate.force_count): component_position, force = QRTPacket._get_exact( RTForce, data, component_position ) force_list.append(force) append_components((plate, force_list)) return components
def get_force(self, component_info=None, data=None, component_position=None): """Get force data.""" components = [] append_components = components.append for _ in range(component_info.plate_count): component_position, plate = QRTPacket._get_exact( RTForcePlate, data, component_position ) force_list = [] for _ in range(plate.force_count): component_position, force = QRTPacket._get_exact( RTForce, data, component_position ) force_list.append(force) append_components((plate, force_list)) return components
[ "Get", "force", "data", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L364-L379
[ "def", "get_force", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "plate_count", ")", ":", "component_position", ",", "plate", "=", "QRTPacket", ".", "_get_exact", "(", "RTForcePlate", ",", "data", ",", "component_position", ")", "force_list", "=", "[", "]", "for", "_", "in", "range", "(", "plate", ".", "force_count", ")", ":", "component_position", ",", "force", "=", "QRTPacket", ".", "_get_exact", "(", "RTForce", ",", "data", ",", "component_position", ")", "force_list", ".", "append", "(", "force", ")", "append_components", "(", "(", "plate", ",", "force_list", ")", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_force_single
Get a single force data channel.
qtm/packet.py
def get_force_single(self, component_info=None, data=None, component_position=None): """Get a single force data channel.""" components = [] append_components = components.append for _ in range(component_info.plate_count): component_position, plate = QRTPacket._get_exact( RTForcePlateSingle, data, component_position ) component_position, force = QRTPacket._get_exact( RTForce, data, component_position ) append_components((plate, force)) return components
def get_force_single(self, component_info=None, data=None, component_position=None): """Get a single force data channel.""" components = [] append_components = components.append for _ in range(component_info.plate_count): component_position, plate = QRTPacket._get_exact( RTForcePlateSingle, data, component_position ) component_position, force = QRTPacket._get_exact( RTForce, data, component_position ) append_components((plate, force)) return components
[ "Get", "a", "single", "force", "data", "channel", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L382-L394
[ "def", "get_force_single", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "plate_count", ")", ":", "component_position", ",", "plate", "=", "QRTPacket", ".", "_get_exact", "(", "RTForcePlateSingle", ",", "data", ",", "component_position", ")", "component_position", ",", "force", "=", "QRTPacket", ".", "_get_exact", "(", "RTForce", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "plate", ",", "force", ")", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_6d
Get 6D data.
qtm/packet.py
def get_6d(self, component_info=None, data=None, component_position=None): """Get 6D data.""" components = [] append_components = components.append for _ in range(component_info.body_count): component_position, position = QRTPacket._get_exact( RT6DBodyPosition, data, component_position ) component_position, matrix = QRTPacket._get_tuple( RT6DBodyRotation, data, component_position ) append_components((position, matrix)) return components
def get_6d(self, component_info=None, data=None, component_position=None): """Get 6D data.""" components = [] append_components = components.append for _ in range(component_info.body_count): component_position, position = QRTPacket._get_exact( RT6DBodyPosition, data, component_position ) component_position, matrix = QRTPacket._get_tuple( RT6DBodyRotation, data, component_position ) append_components((position, matrix)) return components
[ "Get", "6D", "data", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L397-L409
[ "def", "get_6d", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "body_count", ")", ":", "component_position", ",", "position", "=", "QRTPacket", ".", "_get_exact", "(", "RT6DBodyPosition", ",", "data", ",", "component_position", ")", "component_position", ",", "matrix", "=", "QRTPacket", ".", "_get_tuple", "(", "RT6DBodyRotation", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "position", ",", "matrix", ")", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_6d_euler
Get 6D data with euler rotations.
qtm/packet.py
def get_6d_euler(self, component_info=None, data=None, component_position=None): """Get 6D data with euler rotations.""" components = [] append_components = components.append for _ in range(component_info.body_count): component_position, position = QRTPacket._get_exact( RT6DBodyPosition, data, component_position ) component_position, euler = QRTPacket._get_exact( RT6DBodyEuler, data, component_position ) append_components((position, euler)) return components
def get_6d_euler(self, component_info=None, data=None, component_position=None): """Get 6D data with euler rotations.""" components = [] append_components = components.append for _ in range(component_info.body_count): component_position, position = QRTPacket._get_exact( RT6DBodyPosition, data, component_position ) component_position, euler = QRTPacket._get_exact( RT6DBodyEuler, data, component_position ) append_components((position, euler)) return components
[ "Get", "6D", "data", "with", "euler", "rotations", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L430-L442
[ "def", "get_6d_euler", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "body_count", ")", ":", "component_position", ",", "position", "=", "QRTPacket", ".", "_get_exact", "(", "RT6DBodyPosition", ",", "data", ",", "component_position", ")", "component_position", ",", "euler", "=", "QRTPacket", ".", "_get_exact", "(", "RT6DBodyEuler", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "position", ",", "euler", ")", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_image
Get image.
qtm/packet.py
def get_image(self, component_info=None, data=None, component_position=None): """Get image.""" components = [] append_components = components.append for _ in range(component_info.image_count): component_position, image_info = QRTPacket._get_exact( RTImage, data, component_position ) append_components((image_info, data[component_position:-1])) return components
def get_image(self, component_info=None, data=None, component_position=None): """Get image.""" components = [] append_components = components.append for _ in range(component_info.image_count): component_position, image_info = QRTPacket._get_exact( RTImage, data, component_position ) append_components((image_info, data[component_position:-1])) return components
[ "Get", "image", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L465-L474
[ "def", "get_image", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "image_count", ")", ":", "component_position", ",", "image_info", "=", "QRTPacket", ".", "_get_exact", "(", "RTImage", ",", "data", ",", "component_position", ")", "append_components", "(", "(", "image_info", ",", "data", "[", "component_position", ":", "-", "1", "]", ")", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_3d_markers
Get 3D markers.
qtm/packet.py
def get_3d_markers(self, component_info=None, data=None, component_position=None): """Get 3D markers.""" return self._get_3d_markers( RT3DMarkerPosition, component_info, data, component_position )
def get_3d_markers(self, component_info=None, data=None, component_position=None): """Get 3D markers.""" return self._get_3d_markers( RT3DMarkerPosition, component_info, data, component_position )
[ "Get", "3D", "markers", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L477-L481
[ "def", "get_3d_markers", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPosition", ",", "component_info", ",", "data", ",", "component_position", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_3d_markers_residual
Get 3D markers with residual.
qtm/packet.py
def get_3d_markers_residual( self, component_info=None, data=None, component_position=None ): """Get 3D markers with residual.""" return self._get_3d_markers( RT3DMarkerPositionResidual, component_info, data, component_position )
def get_3d_markers_residual( self, component_info=None, data=None, component_position=None ): """Get 3D markers with residual.""" return self._get_3d_markers( RT3DMarkerPositionResidual, component_info, data, component_position )
[ "Get", "3D", "markers", "with", "residual", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L484-L490
[ "def", "get_3d_markers_residual", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPositionResidual", ",", "component_info", ",", "data", ",", "component_position", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_3d_markers_no_label
Get 3D markers without label.
qtm/packet.py
def get_3d_markers_no_label( self, component_info=None, data=None, component_position=None ): """Get 3D markers without label.""" return self._get_3d_markers( RT3DMarkerPositionNoLabel, component_info, data, component_position )
def get_3d_markers_no_label( self, component_info=None, data=None, component_position=None ): """Get 3D markers without label.""" return self._get_3d_markers( RT3DMarkerPositionNoLabel, component_info, data, component_position )
[ "Get", "3D", "markers", "without", "label", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L493-L499
[ "def", "get_3d_markers_no_label", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPositionNoLabel", ",", "component_info", ",", "data", ",", "component_position", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_3d_markers_no_label_residual
Get 3D markers without label with residual.
qtm/packet.py
def get_3d_markers_no_label_residual( self, component_info=None, data=None, component_position=None ): """Get 3D markers without label with residual.""" return self._get_3d_markers( RT3DMarkerPositionNoLabelResidual, component_info, data, component_position )
def get_3d_markers_no_label_residual( self, component_info=None, data=None, component_position=None ): """Get 3D markers without label with residual.""" return self._get_3d_markers( RT3DMarkerPositionNoLabelResidual, component_info, data, component_position )
[ "Get", "3D", "markers", "without", "label", "with", "residual", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L502-L508
[ "def", "get_3d_markers_no_label_residual", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "return", "self", ".", "_get_3d_markers", "(", "RT3DMarkerPositionNoLabelResidual", ",", "component_info", ",", "data", ",", "component_position", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_2d_markers
Get 2D markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.
qtm/packet.py
def get_2d_markers( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ return self._get_2d_markers( data, component_info, component_position, index=index )
def get_2d_markers( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ return self._get_2d_markers( data, component_info, component_position, index=index )
[ "Get", "2D", "markers", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L511-L521
[ "def", "get_2d_markers", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ",", "index", "=", "None", ")", ":", "return", "self", ".", "_get_2d_markers", "(", "data", ",", "component_info", ",", "component_position", ",", "index", "=", "index", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_2d_markers_linearized
Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array.
qtm/packet.py
def get_2d_markers_linearized( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ return self._get_2d_markers( data, component_info, component_position, index=index )
def get_2d_markers_linearized( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ return self._get_2d_markers( data, component_info, component_position, index=index )
[ "Get", "2D", "linearized", "markers", "." ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L524-L535
[ "def", "get_2d_markers_linearized", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ",", "index", "=", "None", ")", ":", "return", "self", ".", "_get_2d_markers", "(", "data", ",", "component_info", ",", "component_position", ",", "index", "=", "index", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTPacket.get_skeletons
Get skeletons
qtm/packet.py
def get_skeletons(self, component_info=None, data=None, component_position=None): """Get skeletons """ components = [] append_components = components.append for _ in range(component_info.skeleton_count): component_position, info = QRTPacket._get_exact( RTSegmentCount, data, component_position ) segments = [] for __ in range(info.segment_count): component_position, segment = QRTPacket._get_exact( RTSegmentId, data, component_position ) component_position, position = QRTPacket._get_exact( RTSegmentPosition, data, component_position ) component_position, rotation = QRTPacket._get_exact( RTSegmentRotation, data, component_position ) segments.append((segment.id, position, rotation)) append_components(segments) return components
def get_skeletons(self, component_info=None, data=None, component_position=None): """Get skeletons """ components = [] append_components = components.append for _ in range(component_info.skeleton_count): component_position, info = QRTPacket._get_exact( RTSegmentCount, data, component_position ) segments = [] for __ in range(info.segment_count): component_position, segment = QRTPacket._get_exact( RTSegmentId, data, component_position ) component_position, position = QRTPacket._get_exact( RTSegmentPosition, data, component_position ) component_position, rotation = QRTPacket._get_exact( RTSegmentRotation, data, component_position ) segments.append((segment.id, position, rotation)) append_components(segments) return components
[ "Get", "skeletons" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/packet.py#L538-L563
[ "def", "get_skeletons", "(", "self", ",", "component_info", "=", "None", ",", "data", "=", "None", ",", "component_position", "=", "None", ")", ":", "components", "=", "[", "]", "append_components", "=", "components", ".", "append", "for", "_", "in", "range", "(", "component_info", ".", "skeleton_count", ")", ":", "component_position", ",", "info", "=", "QRTPacket", ".", "_get_exact", "(", "RTSegmentCount", ",", "data", ",", "component_position", ")", "segments", "=", "[", "]", "for", "__", "in", "range", "(", "info", ".", "segment_count", ")", ":", "component_position", ",", "segment", "=", "QRTPacket", ".", "_get_exact", "(", "RTSegmentId", ",", "data", ",", "component_position", ")", "component_position", ",", "position", "=", "QRTPacket", ".", "_get_exact", "(", "RTSegmentPosition", ",", "data", ",", "component_position", ")", "component_position", ",", "rotation", "=", "QRTPacket", ".", "_get_exact", "(", "RTSegmentRotation", ",", "data", ",", "component_position", ")", "segments", ".", "append", "(", "(", "segment", ".", "id", ",", "position", ",", "rotation", ")", ")", "append_components", "(", "segments", ")", "return", "components" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QTMProtocol.await_event
Wait for any or specified event
qtm/protocol.py
async def await_event(self, event=None, timeout=None): """ Wait for any or specified event """ if self.event_future is not None: raise Exception("Can't wait on multiple events!") result = await asyncio.wait_for(self._wait_loop(event), timeout) return result
async def await_event(self, event=None, timeout=None): """ Wait for any or specified event """ if self.event_future is not None: raise Exception("Can't wait on multiple events!") result = await asyncio.wait_for(self._wait_loop(event), timeout) return result
[ "Wait", "for", "any", "or", "specified", "event" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/protocol.py#L81-L87
[ "async", "def", "await_event", "(", "self", ",", "event", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "event_future", "is", "not", "None", ":", "raise", "Exception", "(", "\"Can't wait on multiple events!\"", ")", "result", "=", "await", "asyncio", ".", "wait_for", "(", "self", ".", "_wait_loop", "(", "event", ")", ",", "timeout", ")", "return", "result" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QTMProtocol.send_command
Sends commands to QTM
qtm/protocol.py
def send_command( self, command, callback=True, command_type=QRTPacketType.PacketCommand ): """ Sends commands to QTM """ if self.transport is not None: cmd_length = len(command) LOG.debug("S: %s", command) self.transport.write( struct.pack( RTCommand % cmd_length, RTheader.size + cmd_length + 1, command_type.value, command.encode(), b"\0", ) ) future = self.loop.create_future() if callback: self.request_queue.append(future) else: future.set_result(None) return future raise QRTCommandException("Not connected!")
def send_command( self, command, callback=True, command_type=QRTPacketType.PacketCommand ): """ Sends commands to QTM """ if self.transport is not None: cmd_length = len(command) LOG.debug("S: %s", command) self.transport.write( struct.pack( RTCommand % cmd_length, RTheader.size + cmd_length + 1, command_type.value, command.encode(), b"\0", ) ) future = self.loop.create_future() if callback: self.request_queue.append(future) else: future.set_result(None) return future raise QRTCommandException("Not connected!")
[ "Sends", "commands", "to", "QTM" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/protocol.py#L89-L113
[ "def", "send_command", "(", "self", ",", "command", ",", "callback", "=", "True", ",", "command_type", "=", "QRTPacketType", ".", "PacketCommand", ")", ":", "if", "self", ".", "transport", "is", "not", "None", ":", "cmd_length", "=", "len", "(", "command", ")", "LOG", ".", "debug", "(", "\"S: %s\"", ",", "command", ")", "self", ".", "transport", ".", "write", "(", "struct", ".", "pack", "(", "RTCommand", "%", "cmd_length", ",", "RTheader", ".", "size", "+", "cmd_length", "+", "1", ",", "command_type", ".", "value", ",", "command", ".", "encode", "(", ")", ",", "b\"\\0\"", ",", ")", ")", "future", "=", "self", ".", "loop", ".", "create_future", "(", ")", "if", "callback", ":", "self", ".", "request_queue", ".", "append", "(", "future", ")", "else", ":", "future", ".", "set_result", "(", "None", ")", "return", "future", "raise", "QRTCommandException", "(", "\"Not connected!\"", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
reboot
async function to reboot QTM cameras
qtm/reboot.py
async def reboot(ip_address): """ async function to reboot QTM cameras """ _, protocol = await asyncio.get_event_loop().create_datagram_endpoint( QRebootProtocol, local_addr=(ip_address, 0), allow_broadcast=True, reuse_address=True, ) LOG.info("Sending reboot on %s", ip_address) protocol.send_reboot()
async def reboot(ip_address): """ async function to reboot QTM cameras """ _, protocol = await asyncio.get_event_loop().create_datagram_endpoint( QRebootProtocol, local_addr=(ip_address, 0), allow_broadcast=True, reuse_address=True, ) LOG.info("Sending reboot on %s", ip_address) protocol.send_reboot()
[ "async", "function", "to", "reboot", "QTM", "cameras" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/reboot.py#L11-L21
[ "async", "def", "reboot", "(", "ip_address", ")", ":", "_", ",", "protocol", "=", "await", "asyncio", ".", "get_event_loop", "(", ")", ".", "create_datagram_endpoint", "(", "QRebootProtocol", ",", "local_addr", "=", "(", "ip_address", ",", "0", ")", ",", "allow_broadcast", "=", "True", ",", "reuse_address", "=", "True", ",", ")", "LOG", ".", "info", "(", "\"Sending reboot on %s\"", ",", "ip_address", ")", "protocol", ".", "send_reboot", "(", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
on_packet
Callback function that is called everytime a data packet arrives from QTM
examples/basic_example.py
def on_packet(packet): """ Callback function that is called everytime a data packet arrives from QTM """ print("Framenumber: {}".format(packet.framenumber)) header, markers = packet.get_3d_markers() print("Component info: {}".format(header)) for marker in markers: print("\t", marker)
def on_packet(packet): """ Callback function that is called everytime a data packet arrives from QTM """ print("Framenumber: {}".format(packet.framenumber)) header, markers = packet.get_3d_markers() print("Component info: {}".format(header)) for marker in markers: print("\t", marker)
[ "Callback", "function", "that", "is", "called", "everytime", "a", "data", "packet", "arrives", "from", "QTM" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/basic_example.py#L11-L17
[ "def", "on_packet", "(", "packet", ")", ":", "print", "(", "\"Framenumber: {}\"", ".", "format", "(", "packet", ".", "framenumber", ")", ")", "header", ",", "markers", "=", "packet", ".", "get_3d_markers", "(", ")", "print", "(", "\"Component info: {}\"", ".", "format", "(", "header", ")", ")", "for", "marker", "in", "markers", ":", "print", "(", "\"\\t\"", ",", "marker", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
setup
Main function
examples/basic_example.py
async def setup(): """ Main function """ connection = await qtm.connect("127.0.0.1") if connection is None: return await connection.stream_frames(components=["3d"], on_packet=on_packet)
async def setup(): """ Main function """ connection = await qtm.connect("127.0.0.1") if connection is None: return await connection.stream_frames(components=["3d"], on_packet=on_packet)
[ "Main", "function" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/basic_example.py#L20-L26
[ "async", "def", "setup", "(", ")", ":", "connection", "=", "await", "qtm", ".", "connect", "(", "\"127.0.0.1\"", ")", "if", "connection", "is", "None", ":", "return", "await", "connection", ".", "stream_frames", "(", "components", "=", "[", "\"3d\"", "]", ",", "on_packet", "=", "on_packet", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTDiscoveryProtocol.connection_made
On socket creation
qtm/discovery.py
def connection_made(self, transport): """ On socket creation """ self.transport = transport sock = transport.get_extra_info("socket") self.port = sock.getsockname()[1]
def connection_made(self, transport): """ On socket creation """ self.transport = transport sock = transport.get_extra_info("socket") self.port = sock.getsockname()[1]
[ "On", "socket", "creation" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/discovery.py#L29-L34
[ "def", "connection_made", "(", "self", ",", "transport", ")", ":", "self", ".", "transport", "=", "transport", "sock", "=", "transport", ".", "get_extra_info", "(", "\"socket\"", ")", "self", ".", "port", "=", "sock", ".", "getsockname", "(", ")", "[", "1", "]" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTDiscoveryProtocol.datagram_received
Parse response from QTM instances
qtm/discovery.py
def datagram_received(self, datagram, address): """ Parse response from QTM instances """ size, _ = RTheader.unpack_from(datagram, 0) info, = struct.unpack_from("{0}s".format(size - 3 - 8), datagram, RTheader.size) base_port, = QRTDiscoveryBasePort.unpack_from(datagram, size - 2) if self.receiver is not None: self.receiver(QRTDiscoveryResponse(info, address[0], base_port))
def datagram_received(self, datagram, address): """ Parse response from QTM instances """ size, _ = RTheader.unpack_from(datagram, 0) info, = struct.unpack_from("{0}s".format(size - 3 - 8), datagram, RTheader.size) base_port, = QRTDiscoveryBasePort.unpack_from(datagram, size - 2) if self.receiver is not None: self.receiver(QRTDiscoveryResponse(info, address[0], base_port))
[ "Parse", "response", "from", "QTM", "instances" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/discovery.py#L36-L43
[ "def", "datagram_received", "(", "self", ",", "datagram", ",", "address", ")", ":", "size", ",", "_", "=", "RTheader", ".", "unpack_from", "(", "datagram", ",", "0", ")", "info", ",", "=", "struct", ".", "unpack_from", "(", "\"{0}s\"", ".", "format", "(", "size", "-", "3", "-", "8", ")", ",", "datagram", ",", "RTheader", ".", "size", ")", "base_port", ",", "=", "QRTDiscoveryBasePort", ".", "unpack_from", "(", "datagram", ",", "size", "-", "2", ")", "if", "self", ".", "receiver", "is", "not", "None", ":", "self", ".", "receiver", "(", "QRTDiscoveryResponse", "(", "info", ",", "address", "[", "0", "]", ",", "base_port", ")", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
QRTDiscoveryProtocol.send_discovery_packet
Send discovery packet for QTM to respond to
qtm/discovery.py
def send_discovery_packet(self): """ Send discovery packet for QTM to respond to """ if self.port is None: return self.transport.sendto( QRTDiscoveryP1.pack( QRTDiscoveryPacketSize, QRTPacketType.PacketDiscover.value ) + QRTDiscoveryP2.pack(self.port), ("<broadcast>", 22226), )
def send_discovery_packet(self): """ Send discovery packet for QTM to respond to """ if self.port is None: return self.transport.sendto( QRTDiscoveryP1.pack( QRTDiscoveryPacketSize, QRTPacketType.PacketDiscover.value ) + QRTDiscoveryP2.pack(self.port), ("<broadcast>", 22226), )
[ "Send", "discovery", "packet", "for", "QTM", "to", "respond", "to" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/qtm/discovery.py#L45-L56
[ "def", "send_discovery_packet", "(", "self", ")", ":", "if", "self", ".", "port", "is", "None", ":", "return", "self", ".", "transport", ".", "sendto", "(", "QRTDiscoveryP1", ".", "pack", "(", "QRTDiscoveryPacketSize", ",", "QRTPacketType", ".", "PacketDiscover", ".", "value", ")", "+", "QRTDiscoveryP2", ".", "pack", "(", "self", ".", "port", ")", ",", "(", "\"<broadcast>\"", ",", "22226", ")", ",", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
packet_receiver
Asynchronous function that processes queue until None is posted in queue
examples/asyncio_everything.py
async def packet_receiver(queue): """ Asynchronous function that processes queue until None is posted in queue """ LOG.info("Entering packet_receiver") while True: packet = await queue.get() if packet is None: break LOG.info("Framenumber %s", packet.framenumber) LOG.info("Exiting packet_receiver")
async def packet_receiver(queue): """ Asynchronous function that processes queue until None is posted in queue """ LOG.info("Entering packet_receiver") while True: packet = await queue.get() if packet is None: break LOG.info("Framenumber %s", packet.framenumber) LOG.info("Exiting packet_receiver")
[ "Asynchronous", "function", "that", "processes", "queue", "until", "None", "is", "posted", "in", "queue" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/asyncio_everything.py#L35-L44
[ "async", "def", "packet_receiver", "(", "queue", ")", ":", "LOG", ".", "info", "(", "\"Entering packet_receiver\"", ")", "while", "True", ":", "packet", "=", "await", "queue", ".", "get", "(", ")", "if", "packet", "is", "None", ":", "break", "LOG", ".", "info", "(", "\"Framenumber %s\"", ",", "packet", ".", "framenumber", ")", "LOG", ".", "info", "(", "\"Exiting packet_receiver\"", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
choose_qtm_instance
List running QTM instances, asks for input and return chosen QTM
examples/asyncio_everything.py
async def choose_qtm_instance(interface): """ List running QTM instances, asks for input and return chosen QTM """ instances = {} print("Available QTM instances:") async for i, qtm_instance in AsyncEnumerate(qtm.Discover(interface), start=1): instances[i] = qtm_instance print("{} - {}".format(i, qtm_instance.info)) try: choice = int(input("Connect to: ")) if choice not in instances: raise ValueError except ValueError: LOG.error("Invalid choice") return None return instances[choice].host
async def choose_qtm_instance(interface): """ List running QTM instances, asks for input and return chosen QTM """ instances = {} print("Available QTM instances:") async for i, qtm_instance in AsyncEnumerate(qtm.Discover(interface), start=1): instances[i] = qtm_instance print("{} - {}".format(i, qtm_instance.info)) try: choice = int(input("Connect to: ")) if choice not in instances: raise ValueError except ValueError: LOG.error("Invalid choice") return None return instances[choice].host
[ "List", "running", "QTM", "instances", "asks", "for", "input", "and", "return", "chosen", "QTM" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/asyncio_everything.py#L47-L66
[ "async", "def", "choose_qtm_instance", "(", "interface", ")", ":", "instances", "=", "{", "}", "print", "(", "\"Available QTM instances:\"", ")", "async", "for", "i", ",", "qtm_instance", "in", "AsyncEnumerate", "(", "qtm", ".", "Discover", "(", "interface", ")", ",", "start", "=", "1", ")", ":", "instances", "[", "i", "]", "=", "qtm_instance", "print", "(", "\"{} - {}\"", ".", "format", "(", "i", ",", "qtm_instance", ".", "info", ")", ")", "try", ":", "choice", "=", "int", "(", "input", "(", "\"Connect to: \"", ")", ")", "if", "choice", "not", "in", "instances", ":", "raise", "ValueError", "except", "ValueError", ":", "LOG", ".", "error", "(", "\"Invalid choice\"", ")", "return", "None", "return", "instances", "[", "choice", "]", ".", "host" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
main
Main function
examples/asyncio_everything.py
async def main(interface=None): """ Main function """ qtm_ip = await choose_qtm_instance(interface) if qtm_ip is None: return while True: connection = await qtm.connect(qtm_ip, 22223, version="1.18") if connection is None: return await connection.get_state() await connection.byte_order() async with qtm.TakeControl(connection, "password"): result = await connection.close() if result == b"Closing connection": await connection.await_event(qtm.QRTEvent.EventConnectionClosed) await connection.load(QTM_FILE) await connection.start(rtfromfile=True) (await connection.get_current_frame()).get_3d_markers() queue = asyncio.Queue() asyncio.ensure_future(packet_receiver(queue)) try: await connection.stream_frames( components=["incorrect"], on_packet=queue.put_nowait ) except qtm.QRTCommandException as exception: LOG.info("exception %s", exception) await connection.stream_frames( components=["3d"], on_packet=queue.put_nowait ) await asyncio.sleep(0.5) await connection.byte_order() await asyncio.sleep(0.5) await connection.stream_frames_stop() queue.put_nowait(None) await connection.get_parameters(parameters=["3d"]) await connection.stop() await connection.await_event() await connection.new() await connection.await_event(qtm.QRTEvent.EventConnected) await connection.start() await connection.await_event(qtm.QRTEvent.EventWaitingForTrigger) await connection.trig() await connection.await_event(qtm.QRTEvent.EventCaptureStarted) await asyncio.sleep(0.5) await connection.set_qtm_event() await asyncio.sleep(0.001) await connection.set_qtm_event("with_label") await asyncio.sleep(0.5) await connection.stop() await connection.await_event(qtm.QRTEvent.EventCaptureStopped) await connection.save(r"measurement.qtm") await asyncio.sleep(3) await connection.close() connection.disconnect()
async def main(interface=None): """ Main function """ qtm_ip = await choose_qtm_instance(interface) if qtm_ip is None: return while True: connection = await qtm.connect(qtm_ip, 22223, version="1.18") if connection is None: return await connection.get_state() await connection.byte_order() async with qtm.TakeControl(connection, "password"): result = await connection.close() if result == b"Closing connection": await connection.await_event(qtm.QRTEvent.EventConnectionClosed) await connection.load(QTM_FILE) await connection.start(rtfromfile=True) (await connection.get_current_frame()).get_3d_markers() queue = asyncio.Queue() asyncio.ensure_future(packet_receiver(queue)) try: await connection.stream_frames( components=["incorrect"], on_packet=queue.put_nowait ) except qtm.QRTCommandException as exception: LOG.info("exception %s", exception) await connection.stream_frames( components=["3d"], on_packet=queue.put_nowait ) await asyncio.sleep(0.5) await connection.byte_order() await asyncio.sleep(0.5) await connection.stream_frames_stop() queue.put_nowait(None) await connection.get_parameters(parameters=["3d"]) await connection.stop() await connection.await_event() await connection.new() await connection.await_event(qtm.QRTEvent.EventConnected) await connection.start() await connection.await_event(qtm.QRTEvent.EventWaitingForTrigger) await connection.trig() await connection.await_event(qtm.QRTEvent.EventCaptureStarted) await asyncio.sleep(0.5) await connection.set_qtm_event() await asyncio.sleep(0.001) await connection.set_qtm_event("with_label") await asyncio.sleep(0.5) await connection.stop() await connection.await_event(qtm.QRTEvent.EventCaptureStopped) await connection.save(r"measurement.qtm") await asyncio.sleep(3) await connection.close() connection.disconnect()
[ "Main", "function" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/asyncio_everything.py#L69-L150
[ "async", "def", "main", "(", "interface", "=", "None", ")", ":", "qtm_ip", "=", "await", "choose_qtm_instance", "(", "interface", ")", "if", "qtm_ip", "is", "None", ":", "return", "while", "True", ":", "connection", "=", "await", "qtm", ".", "connect", "(", "qtm_ip", ",", "22223", ",", "version", "=", "\"1.18\"", ")", "if", "connection", "is", "None", ":", "return", "await", "connection", ".", "get_state", "(", ")", "await", "connection", ".", "byte_order", "(", ")", "async", "with", "qtm", ".", "TakeControl", "(", "connection", ",", "\"password\"", ")", ":", "result", "=", "await", "connection", ".", "close", "(", ")", "if", "result", "==", "b\"Closing connection\"", ":", "await", "connection", ".", "await_event", "(", "qtm", ".", "QRTEvent", ".", "EventConnectionClosed", ")", "await", "connection", ".", "load", "(", "QTM_FILE", ")", "await", "connection", ".", "start", "(", "rtfromfile", "=", "True", ")", "(", "await", "connection", ".", "get_current_frame", "(", ")", ")", ".", "get_3d_markers", "(", ")", "queue", "=", "asyncio", ".", "Queue", "(", ")", "asyncio", ".", "ensure_future", "(", "packet_receiver", "(", "queue", ")", ")", "try", ":", "await", "connection", ".", "stream_frames", "(", "components", "=", "[", "\"incorrect\"", "]", ",", "on_packet", "=", "queue", ".", "put_nowait", ")", "except", "qtm", ".", "QRTCommandException", "as", "exception", ":", "LOG", ".", "info", "(", "\"exception %s\"", ",", "exception", ")", "await", "connection", ".", "stream_frames", "(", "components", "=", "[", "\"3d\"", "]", ",", "on_packet", "=", "queue", ".", "put_nowait", ")", "await", "asyncio", ".", "sleep", "(", "0.5", ")", "await", "connection", ".", "byte_order", "(", ")", "await", "asyncio", ".", "sleep", "(", "0.5", ")", "await", "connection", ".", "stream_frames_stop", "(", ")", "queue", ".", "put_nowait", "(", "None", ")", "await", "connection", ".", "get_parameters", "(", "parameters", "=", "[", "\"3d\"", "]", ")", "await", "connection", ".", "stop", "(", ")", "await", "connection", ".", "await_event", "(", ")", "await", "connection", ".", "new", "(", ")", "await", "connection", ".", "await_event", "(", "qtm", ".", "QRTEvent", ".", "EventConnected", ")", "await", "connection", ".", "start", "(", ")", "await", "connection", ".", "await_event", "(", "qtm", ".", "QRTEvent", ".", "EventWaitingForTrigger", ")", "await", "connection", ".", "trig", "(", ")", "await", "connection", ".", "await_event", "(", "qtm", ".", "QRTEvent", ".", "EventCaptureStarted", ")", "await", "asyncio", ".", "sleep", "(", "0.5", ")", "await", "connection", ".", "set_qtm_event", "(", ")", "await", "asyncio", ".", "sleep", "(", "0.001", ")", "await", "connection", ".", "set_qtm_event", "(", "\"with_label\"", ")", "await", "asyncio", ".", "sleep", "(", "0.5", ")", "await", "connection", ".", "stop", "(", ")", "await", "connection", ".", "await_event", "(", "qtm", ".", "QRTEvent", ".", "EventCaptureStopped", ")", "await", "connection", ".", "save", "(", "r\"measurement.qtm\"", ")", "await", "asyncio", ".", "sleep", "(", "3", ")", "await", "connection", ".", "close", "(", ")", "connection", ".", "disconnect", "(", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
package_receiver
Asynchronous function that processes queue until None is posted in queue
examples/advanced_example.py
async def package_receiver(queue): """ Asynchronous function that processes queue until None is posted in queue """ LOG.info("Entering package_receiver") while True: packet = await queue.get() if packet is None: break LOG.info("Framenumber %s", packet.framenumber) header, cameras = packet.get_2d_markers() LOG.info("Component info: %s", header) for i, camera in enumerate(cameras, 1): LOG.info("Camera %d", i) for marker in camera: LOG.info("\t%s", marker) LOG.info("Exiting package_receiver")
async def package_receiver(queue): """ Asynchronous function that processes queue until None is posted in queue """ LOG.info("Entering package_receiver") while True: packet = await queue.get() if packet is None: break LOG.info("Framenumber %s", packet.framenumber) header, cameras = packet.get_2d_markers() LOG.info("Component info: %s", header) for i, camera in enumerate(cameras, 1): LOG.info("Camera %d", i) for marker in camera: LOG.info("\t%s", marker) LOG.info("Exiting package_receiver")
[ "Asynchronous", "function", "that", "processes", "queue", "until", "None", "is", "posted", "in", "queue" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/advanced_example.py#L11-L28
[ "async", "def", "package_receiver", "(", "queue", ")", ":", "LOG", ".", "info", "(", "\"Entering package_receiver\"", ")", "while", "True", ":", "packet", "=", "await", "queue", ".", "get", "(", ")", "if", "packet", "is", "None", ":", "break", "LOG", ".", "info", "(", "\"Framenumber %s\"", ",", "packet", ".", "framenumber", ")", "header", ",", "cameras", "=", "packet", ".", "get_2d_markers", "(", ")", "LOG", ".", "info", "(", "\"Component info: %s\"", ",", "header", ")", "for", "i", ",", "camera", "in", "enumerate", "(", "cameras", ",", "1", ")", ":", "LOG", ".", "info", "(", "\"Camera %d\"", ",", "i", ")", "for", "marker", "in", "camera", ":", "LOG", ".", "info", "(", "\"\\t%s\"", ",", "marker", ")", "LOG", ".", "info", "(", "\"Exiting package_receiver\"", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
setup
main function
examples/advanced_example.py
async def setup(): """ main function """ connection = await qtm.connect("127.0.0.1") if connection is None: return -1 async with qtm.TakeControl(connection, "password"): state = await connection.get_state() if state != qtm.QRTEvent.EventConnected: await connection.new() try: await connection.await_event(qtm.QRTEvent.EventConnected, timeout=10) except asyncio.TimeoutError: LOG.error("Failed to start new measurement") return -1 queue = asyncio.Queue() receiver_future = asyncio.ensure_future(package_receiver(queue)) await connection.stream_frames(components=["2d"], on_packet=queue.put_nowait) asyncio.ensure_future(shutdown(30, connection, receiver_future, queue))
async def setup(): """ main function """ connection = await qtm.connect("127.0.0.1") if connection is None: return -1 async with qtm.TakeControl(connection, "password"): state = await connection.get_state() if state != qtm.QRTEvent.EventConnected: await connection.new() try: await connection.await_event(qtm.QRTEvent.EventConnected, timeout=10) except asyncio.TimeoutError: LOG.error("Failed to start new measurement") return -1 queue = asyncio.Queue() receiver_future = asyncio.ensure_future(package_receiver(queue)) await connection.stream_frames(components=["2d"], on_packet=queue.put_nowait) asyncio.ensure_future(shutdown(30, connection, receiver_future, queue))
[ "main", "function" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/advanced_example.py#L47-L72
[ "async", "def", "setup", "(", ")", ":", "connection", "=", "await", "qtm", ".", "connect", "(", "\"127.0.0.1\"", ")", "if", "connection", "is", "None", ":", "return", "-", "1", "async", "with", "qtm", ".", "TakeControl", "(", "connection", ",", "\"password\"", ")", ":", "state", "=", "await", "connection", ".", "get_state", "(", ")", "if", "state", "!=", "qtm", ".", "QRTEvent", ".", "EventConnected", ":", "await", "connection", ".", "new", "(", ")", "try", ":", "await", "connection", ".", "await_event", "(", "qtm", ".", "QRTEvent", ".", "EventConnected", ",", "timeout", "=", "10", ")", "except", "asyncio", ".", "TimeoutError", ":", "LOG", ".", "error", "(", "\"Failed to start new measurement\"", ")", "return", "-", "1", "queue", "=", "asyncio", ".", "Queue", "(", ")", "receiver_future", "=", "asyncio", ".", "ensure_future", "(", "package_receiver", "(", "queue", ")", ")", "await", "connection", ".", "stream_frames", "(", "components", "=", "[", "\"2d\"", "]", ",", "on_packet", "=", "queue", ".", "put_nowait", ")", "asyncio", ".", "ensure_future", "(", "shutdown", "(", "30", ",", "connection", ",", "receiver_future", ",", "queue", ")", ")" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
create_body_index
Extract a name to index dictionary from 6dof settings xml
examples/stream_6dof_example.py
def create_body_index(xml_string): """ Extract a name to index dictionary from 6dof settings xml """ xml = ET.fromstring(xml_string) body_to_index = {} for index, body in enumerate(xml.findall("*/Body/Name")): body_to_index[body.text.strip()] = index return body_to_index
def create_body_index(xml_string): """ Extract a name to index dictionary from 6dof settings xml """ xml = ET.fromstring(xml_string) body_to_index = {} for index, body in enumerate(xml.findall("*/Body/Name")): body_to_index[body.text.strip()] = index return body_to_index
[ "Extract", "a", "name", "to", "index", "dictionary", "from", "6dof", "settings", "xml" ]
qualisys/qualisys_python_sdk
python
https://github.com/qualisys/qualisys_python_sdk/blob/127d7eeebc2b38b5cafdfa5d1d0198437fedd274/examples/stream_6dof_example.py#L14-L22
[ "def", "create_body_index", "(", "xml_string", ")", ":", "xml", "=", "ET", ".", "fromstring", "(", "xml_string", ")", "body_to_index", "=", "{", "}", "for", "index", ",", "body", "in", "enumerate", "(", "xml", ".", "findall", "(", "\"*/Body/Name\"", ")", ")", ":", "body_to_index", "[", "body", ".", "text", ".", "strip", "(", ")", "]", "=", "index", "return", "body_to_index" ]
127d7eeebc2b38b5cafdfa5d1d0198437fedd274
valid
find_executable
Try to find 'executable' in the directories listed in 'path' (a string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']).
setup.py
def find_executable(executable, path=None): '''Try to find 'executable' in the directories listed in 'path' (a string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']).''' if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) extlist = [''] if os.name == 'os2': ext = os.path.splitext(executable) # executable files on OS/2 can have an arbitrary extension, but # .exe is automatically appended if no dot is present in the name if not ext: executable = executable + ".exe" elif sys.platform == 'win32': pathext = os.environ['PATHEXT'].lower().split(os.pathsep) ext = os.path.splitext(executable) if ext not in pathext: extlist = pathext for ext in extlist: execname = executable + ext if os.path.isfile(execname): return execname else: for pth in paths: fil = os.path.join(pth, execname) if os.path.isfile(fil): return fil break else: return None
def find_executable(executable, path=None): '''Try to find 'executable' in the directories listed in 'path' (a string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']).''' if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) extlist = [''] if os.name == 'os2': ext = os.path.splitext(executable) # executable files on OS/2 can have an arbitrary extension, but # .exe is automatically appended if no dot is present in the name if not ext: executable = executable + ".exe" elif sys.platform == 'win32': pathext = os.environ['PATHEXT'].lower().split(os.pathsep) ext = os.path.splitext(executable) if ext not in pathext: extlist = pathext for ext in extlist: execname = executable + ext if os.path.isfile(execname): return execname else: for pth in paths: fil = os.path.join(pth, execname) if os.path.isfile(fil): return fil break else: return None
[ "Try", "to", "find", "executable", "in", "the", "directories", "listed", "in", "path", "(", "a", "string", "listing", "directories", "separated", "by", "os", ".", "pathsep", ";", "defaults", "to", "os", ".", "environ", "[", "PATH", "]", ")", "." ]
FutureLinkCorporation/fann2
python
https://github.com/FutureLinkCorporation/fann2/blob/bc45277e11f0c34d3315f8070cd4a13d13618096/setup.py#L16-L46
[ "def", "find_executable", "(", "executable", ",", "path", "=", "None", ")", ":", "if", "path", "is", "None", ":", "path", "=", "os", ".", "environ", "[", "'PATH'", "]", "paths", "=", "path", ".", "split", "(", "os", ".", "pathsep", ")", "extlist", "=", "[", "''", "]", "if", "os", ".", "name", "==", "'os2'", ":", "ext", "=", "os", ".", "path", ".", "splitext", "(", "executable", ")", "# executable files on OS/2 can have an arbitrary extension, but", "# .exe is automatically appended if no dot is present in the name", "if", "not", "ext", ":", "executable", "=", "executable", "+", "\".exe\"", "elif", "sys", ".", "platform", "==", "'win32'", ":", "pathext", "=", "os", ".", "environ", "[", "'PATHEXT'", "]", ".", "lower", "(", ")", ".", "split", "(", "os", ".", "pathsep", ")", "ext", "=", "os", ".", "path", ".", "splitext", "(", "executable", ")", "if", "ext", "not", "in", "pathext", ":", "extlist", "=", "pathext", "for", "ext", "in", "extlist", ":", "execname", "=", "executable", "+", "ext", "if", "os", ".", "path", ".", "isfile", "(", "execname", ")", ":", "return", "execname", "else", ":", "for", "pth", "in", "paths", ":", "fil", "=", "os", ".", "path", ".", "join", "(", "pth", ",", "execname", ")", "if", "os", ".", "path", ".", "isfile", "(", "fil", ")", ":", "return", "fil", "break", "else", ":", "return", "None" ]
bc45277e11f0c34d3315f8070cd4a13d13618096
valid
find_x
Return true if substring is in string for files in specified path
setup.py
def find_x(path1): '''Return true if substring is in string for files in specified path''' libs = os.listdir(path1) for lib_dir in libs: if "doublefann" in lib_dir: return True
def find_x(path1): '''Return true if substring is in string for files in specified path''' libs = os.listdir(path1) for lib_dir in libs: if "doublefann" in lib_dir: return True
[ "Return", "true", "if", "substring", "is", "in", "string", "for", "files", "in", "specified", "path" ]
FutureLinkCorporation/fann2
python
https://github.com/FutureLinkCorporation/fann2/blob/bc45277e11f0c34d3315f8070cd4a13d13618096/setup.py#L48-L54
[ "def", "find_x", "(", "path1", ")", ":", "libs", "=", "os", ".", "listdir", "(", "path1", ")", "for", "lib_dir", "in", "libs", ":", "if", "\"doublefann\"", "in", "lib_dir", ":", "return", "True" ]
bc45277e11f0c34d3315f8070cd4a13d13618096
valid
find_fann
Find doublefann library
setup.py
def find_fann(): '''Find doublefann library''' # FANN possible libs directories (as $LD_LIBRARY_PATH), also includes # pkgsrc framework support. if sys.platform == "win32": dirs = sys.path for ver in dirs: if os.path.isdir(ver): if find_x(ver): return True raise Exception("Couldn't find FANN source libs!") else: dirs = ['/lib', '/usr/lib', '/usr/lib64', '/usr/local/lib', '/usr/pkg/lib'] for path in dirs: if os.path.isdir(path): if find_x(path): return True raise Exception("Couldn't find FANN source libs!")
def find_fann(): '''Find doublefann library''' # FANN possible libs directories (as $LD_LIBRARY_PATH), also includes # pkgsrc framework support. if sys.platform == "win32": dirs = sys.path for ver in dirs: if os.path.isdir(ver): if find_x(ver): return True raise Exception("Couldn't find FANN source libs!") else: dirs = ['/lib', '/usr/lib', '/usr/lib64', '/usr/local/lib', '/usr/pkg/lib'] for path in dirs: if os.path.isdir(path): if find_x(path): return True raise Exception("Couldn't find FANN source libs!")
[ "Find", "doublefann", "library" ]
FutureLinkCorporation/fann2
python
https://github.com/FutureLinkCorporation/fann2/blob/bc45277e11f0c34d3315f8070cd4a13d13618096/setup.py#L56-L73
[ "def", "find_fann", "(", ")", ":", "# FANN possible libs directories (as $LD_LIBRARY_PATH), also includes", "# pkgsrc framework support.", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "dirs", "=", "sys", ".", "path", "for", "ver", "in", "dirs", ":", "if", "os", ".", "path", ".", "isdir", "(", "ver", ")", ":", "if", "find_x", "(", "ver", ")", ":", "return", "True", "raise", "Exception", "(", "\"Couldn't find FANN source libs!\"", ")", "else", ":", "dirs", "=", "[", "'/lib'", ",", "'/usr/lib'", ",", "'/usr/lib64'", ",", "'/usr/local/lib'", ",", "'/usr/pkg/lib'", "]", "for", "path", "in", "dirs", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "if", "find_x", "(", "path", ")", ":", "return", "True", "raise", "Exception", "(", "\"Couldn't find FANN source libs!\"", ")" ]
bc45277e11f0c34d3315f8070cd4a13d13618096
valid
build_swig
Run SWIG with specified parameters
setup.py
def build_swig(): '''Run SWIG with specified parameters''' print("Looking for FANN libs...") find_fann() print("running SWIG...") swig_bin = find_swig() swig_cmd = [swig_bin, '-c++', '-python', 'fann2/fann2.i'] subprocess.Popen(swig_cmd).wait()
def build_swig(): '''Run SWIG with specified parameters''' print("Looking for FANN libs...") find_fann() print("running SWIG...") swig_bin = find_swig() swig_cmd = [swig_bin, '-c++', '-python', 'fann2/fann2.i'] subprocess.Popen(swig_cmd).wait()
[ "Run", "SWIG", "with", "specified", "parameters" ]
FutureLinkCorporation/fann2
python
https://github.com/FutureLinkCorporation/fann2/blob/bc45277e11f0c34d3315f8070cd4a13d13618096/setup.py#L82-L89
[ "def", "build_swig", "(", ")", ":", "print", "(", "\"Looking for FANN libs...\"", ")", "find_fann", "(", ")", "print", "(", "\"running SWIG...\"", ")", "swig_bin", "=", "find_swig", "(", ")", "swig_cmd", "=", "[", "swig_bin", ",", "'-c++'", ",", "'-python'", ",", "'fann2/fann2.i'", "]", "subprocess", ".", "Popen", "(", "swig_cmd", ")", ".", "wait", "(", ")" ]
bc45277e11f0c34d3315f8070cd4a13d13618096
valid
experiment
Commands for experiments.
polyaxon_cli/cli/experiment.py
def experiment(ctx, project, experiment): # pylint:disable=redefined-outer-name """Commands for experiments.""" ctx.obj = ctx.obj or {} ctx.obj['project'] = project ctx.obj['experiment'] = experiment
def experiment(ctx, project, experiment): # pylint:disable=redefined-outer-name """Commands for experiments.""" ctx.obj = ctx.obj or {} ctx.obj['project'] = project ctx.obj['experiment'] = experiment
[ "Commands", "for", "experiments", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L64-L68
[ "def", "experiment", "(", "ctx", ",", "project", ",", "experiment", ")", ":", "# pylint:disable=redefined-outer-name", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'project'", "]", "=", "project", "ctx", ".", "obj", "[", "'experiment'", "]", "=", "experiment" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
get
Get experiment or experiment job. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting an experiment: \b ```bash $ polyaxon experiment get # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get ``` Examples for getting an experiment job: \b ```bash $ polyaxon experiment get -j 1 # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get --job=10 ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2 ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2 ```
polyaxon_cli/cli/experiment.py
def get(ctx, job): """Get experiment or experiment job. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting an experiment: \b ```bash $ polyaxon experiment get # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get ``` Examples for getting an experiment job: \b ```bash $ polyaxon experiment get -j 1 # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get --job=10 ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2 ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2 ``` """ def get_experiment(): try: response = PolyaxonClient().experiment.get_experiment(user, project_name, _experiment) cache.cache(config_manager=ExperimentManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load experiment `{}` info.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_experiment_details(response) def get_experiment_job(): try: response = PolyaxonClient().experiment_job.get_job(user, project_name, _experiment, _job) cache.cache(config_manager=ExperimentJobManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.resources: get_resources(response.resources.to_dict(), header="Job resources:") response = Printer.add_status_color(response.to_light_dict( humanize_values=True, exclude_attrs=['uuid', 'definition', 'experiment', 'unique_name', 'resources'] )) Printer.print_header("Job info:") dict_tabulate(response) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job() else: get_experiment()
def get(ctx, job): """Get experiment or experiment job. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting an experiment: \b ```bash $ polyaxon experiment get # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get ``` Examples for getting an experiment job: \b ```bash $ polyaxon experiment get -j 1 # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get --job=10 ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2 ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2 ``` """ def get_experiment(): try: response = PolyaxonClient().experiment.get_experiment(user, project_name, _experiment) cache.cache(config_manager=ExperimentManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load experiment `{}` info.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_experiment_details(response) def get_experiment_job(): try: response = PolyaxonClient().experiment_job.get_job(user, project_name, _experiment, _job) cache.cache(config_manager=ExperimentJobManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.resources: get_resources(response.resources.to_dict(), header="Job resources:") response = Printer.add_status_color(response.to_light_dict( humanize_values=True, exclude_attrs=['uuid', 'definition', 'experiment', 'unique_name', 'resources'] )) Printer.print_header("Job info:") dict_tabulate(response) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job() else: get_experiment()
[ "Get", "experiment", "or", "experiment", "job", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L75-L165
[ "def", "get", "(", "ctx", ",", "job", ")", ":", "def", "get_experiment", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "get_experiment", "(", "user", ",", "project_name", ",", "_experiment", ")", "cache", ".", "cache", "(", "config_manager", "=", "ExperimentManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load experiment `{}` info.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_experiment_details", "(", "response", ")", "def", "get_experiment_job", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "get_job", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ")", "cache", ".", "cache", "(", "config_manager", "=", "ExperimentJobManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "resources", ":", "get_resources", "(", "response", ".", "resources", ".", "to_dict", "(", ")", ",", "header", "=", "\"Job resources:\"", ")", "response", "=", "Printer", ".", "add_status_color", "(", "response", ".", "to_light_dict", "(", "humanize_values", "=", "True", ",", "exclude_attrs", "=", "[", "'uuid'", ",", "'definition'", ",", "'experiment'", ",", "'unique_name'", ",", "'resources'", "]", ")", ")", "Printer", ".", "print_header", "(", "\"Job info:\"", ")", "dict_tabulate", "(", "response", ")", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job", "(", ")", "else", ":", "get_experiment", "(", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
delete
Delete experiment. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon experiment delete ```
polyaxon_cli/cli/experiment.py
def delete(ctx): """Delete experiment. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon experiment delete ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if not click.confirm("Are sure you want to delete experiment `{}`".format(_experiment)): click.echo('Existing without deleting experiment.') sys.exit(1) try: response = PolyaxonClient().experiment.delete_experiment( user, project_name, _experiment) # Purge caching ExperimentManager.purge() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not delete experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Experiment `{}` was delete successfully".format(_experiment))
def delete(ctx): """Delete experiment. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon experiment delete ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if not click.confirm("Are sure you want to delete experiment `{}`".format(_experiment)): click.echo('Existing without deleting experiment.') sys.exit(1) try: response = PolyaxonClient().experiment.delete_experiment( user, project_name, _experiment) # Purge caching ExperimentManager.purge() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not delete experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Experiment `{}` was delete successfully".format(_experiment))
[ "Delete", "experiment", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L171-L200
[ "def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "not", "click", ".", "confirm", "(", "\"Are sure you want to delete experiment `{}`\"", ".", "format", "(", "_experiment", ")", ")", ":", "click", ".", "echo", "(", "'Existing without deleting experiment.'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "delete_experiment", "(", "user", ",", "project_name", ",", "_experiment", ")", "# Purge caching", "ExperimentManager", ".", "purge", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "204", ":", "Printer", ".", "print_success", "(", "\"Experiment `{}` was delete successfully\"", ".", "format", "(", "_experiment", ")", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
update
Update experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment -xp 2 update --description="new description for my experiments" ``` \b ```bash $ polyaxon experiment -xp 2 update --tags="foo, bar" --name="unique-name" ```
polyaxon_cli/cli/experiment.py
def update(ctx, name, description, tags): """Update experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment -xp 2 update --description="new description for my experiments" ``` \b ```bash $ polyaxon experiment -xp 2 update --tags="foo, bar" --name="unique-name" ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) update_dict = {} if name: update_dict['name'] = name if description: update_dict['description'] = description tags = validate_tags(tags) if tags: update_dict['tags'] = tags if not update_dict: Printer.print_warning('No argument was provided to update the experiment.') sys.exit(0) try: response = PolyaxonClient().experiment.update_experiment( user, project_name, _experiment, update_dict) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not update experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment updated.") get_experiment_details(response)
def update(ctx, name, description, tags): """Update experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment -xp 2 update --description="new description for my experiments" ``` \b ```bash $ polyaxon experiment -xp 2 update --tags="foo, bar" --name="unique-name" ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) update_dict = {} if name: update_dict['name'] = name if description: update_dict['description'] = description tags = validate_tags(tags) if tags: update_dict['tags'] = tags if not update_dict: Printer.print_warning('No argument was provided to update the experiment.') sys.exit(0) try: response = PolyaxonClient().experiment.update_experiment( user, project_name, _experiment, update_dict) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not update experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment updated.") get_experiment_details(response)
[ "Update", "experiment", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L210-L254
[ "def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "update_dict", "=", "{", "}", "if", "name", ":", "update_dict", "[", "'name'", "]", "=", "name", "if", "description", ":", "update_dict", "[", "'description'", "]", "=", "description", "tags", "=", "validate_tags", "(", "tags", ")", "if", "tags", ":", "update_dict", "[", "'tags'", "]", "=", "tags", "if", "not", "update_dict", ":", "Printer", ".", "print_warning", "(", "'No argument was provided to update the experiment.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "update_experiment", "(", "user", ",", "project_name", ",", "_experiment", ",", "update_dict", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not update experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiment updated.\"", ")", "get_experiment_details", "(", "response", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
stop
Stop experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment stop ``` \b ```bash $ polyaxon experiment -xp 2 stop ```
polyaxon_cli/cli/experiment.py
def stop(ctx, yes): """Stop experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment stop ``` \b ```bash $ polyaxon experiment -xp 2 stop ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if not yes and not click.confirm("Are sure you want to stop " "experiment `{}`".format(_experiment)): click.echo('Existing without stopping experiment.') sys.exit(0) try: PolyaxonClient().experiment.stop(user, project_name, _experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not stop experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment is being stopped.")
def stop(ctx, yes): """Stop experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment stop ``` \b ```bash $ polyaxon experiment -xp 2 stop ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if not yes and not click.confirm("Are sure you want to stop " "experiment `{}`".format(_experiment)): click.echo('Existing without stopping experiment.') sys.exit(0) try: PolyaxonClient().experiment.stop(user, project_name, _experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not stop experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment is being stopped.")
[ "Stop", "experiment", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L263-L294
[ "def", "stop", "(", "ctx", ",", "yes", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "not", "yes", "and", "not", "click", ".", "confirm", "(", "\"Are sure you want to stop \"", "\"experiment `{}`\"", ".", "format", "(", "_experiment", ")", ")", ":", "click", ".", "echo", "(", "'Existing without stopping experiment.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment", ".", "stop", "(", "user", ",", "project_name", ",", "_experiment", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not stop experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiment is being stopped.\"", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
restart
Restart experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment --experiment=1 restart ```
polyaxon_cli/cli/experiment.py
def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin """Restart experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment --experiment=1 restart ``` """ config = None update_code = None if file: config = rhea.read(file) # Check if we need to upload if u: ctx.invoke(upload, sync=False) update_code = True user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) try: if copy: response = PolyaxonClient().experiment.copy( user, project_name, _experiment, config=config, update_code=update_code) Printer.print_success('Experiment was copied with id {}'.format(response.id)) else: response = PolyaxonClient().experiment.restart( user, project_name, _experiment, config=config, update_code=update_code) Printer.print_success('Experiment was restarted with id {}'.format(response.id)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not restart experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1)
def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin """Restart experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment --experiment=1 restart ``` """ config = None update_code = None if file: config = rhea.read(file) # Check if we need to upload if u: ctx.invoke(upload, sync=False) update_code = True user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) try: if copy: response = PolyaxonClient().experiment.copy( user, project_name, _experiment, config=config, update_code=update_code) Printer.print_success('Experiment was copied with id {}'.format(response.id)) else: response = PolyaxonClient().experiment.restart( user, project_name, _experiment, config=config, update_code=update_code) Printer.print_success('Experiment was restarted with id {}'.format(response.id)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not restart experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1)
[ "Restart", "experiment", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L306-L342
[ "def", "restart", "(", "ctx", ",", "copy", ",", "file", ",", "u", ")", ":", "# pylint:disable=redefined-builtin", "config", "=", "None", "update_code", "=", "None", "if", "file", ":", "config", "=", "rhea", ".", "read", "(", "file", ")", "# Check if we need to upload", "if", "u", ":", "ctx", ".", "invoke", "(", "upload", ",", "sync", "=", "False", ")", "update_code", "=", "True", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "try", ":", "if", "copy", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "copy", "(", "user", ",", "project_name", ",", "_experiment", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "Printer", ".", "print_success", "(", "'Experiment was copied with id {}'", ".", "format", "(", "response", ".", "id", ")", ")", "else", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "restart", "(", "user", ",", "project_name", ",", "_experiment", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "Printer", ".", "print_success", "(", "'Experiment was restarted with id {}'", ".", "format", "(", "response", ".", "id", ")", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not restart experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
statuses
Get experiment or experiment job statuses. Uses [Caching](/references/polyaxon-cli/#caching) Examples getting experiment statuses: \b ```bash $ polyaxon experiment statuses ``` \b ```bash $ polyaxon experiment -xp 1 statuses ``` Examples getting experiment job statuses: \b ```bash $ polyaxon experiment statuses -j 3 ``` \b ```bash $ polyaxon experiment -xp 1 statuses --job 1 ```
polyaxon_cli/cli/experiment.py
def statuses(ctx, job, page): """Get experiment or experiment job statuses. Uses [Caching](/references/polyaxon-cli/#caching) Examples getting experiment statuses: \b ```bash $ polyaxon experiment statuses ``` \b ```bash $ polyaxon experiment -xp 1 statuses ``` Examples getting experiment job statuses: \b ```bash $ polyaxon experiment statuses -j 3 ``` \b ```bash $ polyaxon experiment -xp 1 statuses --job 1 ``` """ def get_experiment_statuses(): try: response = PolyaxonClient().experiment.get_statuses( user, project_name, _experiment, page=page) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could get status for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) meta = get_meta_response(response) if meta: Printer.print_header('Statuses for experiment `{}`.'.format(_experiment)) Printer.print_header('Navigation:') dict_tabulate(meta) else: Printer.print_header('No statuses found for experiment `{}`.'.format(_experiment)) objects = list_dicts_to_tabulate( [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status') for o in response['results']]) if objects: Printer.print_header("Statuses:") objects.pop('experiment', None) dict_tabulate(objects, is_list_dict=True) def get_experiment_job_statuses(): try: response = PolyaxonClient().experiment_job.get_statuses(user, project_name, _experiment, _job, page=page) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get status for job `{}`.'.format(job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) meta = get_meta_response(response) if meta: Printer.print_header('Statuses for Job `{}`.'.format(_job)) Printer.print_header('Navigation:') dict_tabulate(meta) else: Printer.print_header('No statuses found for job `{}`.'.format(_job)) objects = list_dicts_to_tabulate( [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status') for o in response['results']]) if objects: Printer.print_header("Statuses:") objects.pop('job', None) dict_tabulate(objects, is_list_dict=True) page = page or 1 user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_statuses() else: get_experiment_statuses()
def statuses(ctx, job, page): """Get experiment or experiment job statuses. Uses [Caching](/references/polyaxon-cli/#caching) Examples getting experiment statuses: \b ```bash $ polyaxon experiment statuses ``` \b ```bash $ polyaxon experiment -xp 1 statuses ``` Examples getting experiment job statuses: \b ```bash $ polyaxon experiment statuses -j 3 ``` \b ```bash $ polyaxon experiment -xp 1 statuses --job 1 ``` """ def get_experiment_statuses(): try: response = PolyaxonClient().experiment.get_statuses( user, project_name, _experiment, page=page) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could get status for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) meta = get_meta_response(response) if meta: Printer.print_header('Statuses for experiment `{}`.'.format(_experiment)) Printer.print_header('Navigation:') dict_tabulate(meta) else: Printer.print_header('No statuses found for experiment `{}`.'.format(_experiment)) objects = list_dicts_to_tabulate( [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status') for o in response['results']]) if objects: Printer.print_header("Statuses:") objects.pop('experiment', None) dict_tabulate(objects, is_list_dict=True) def get_experiment_job_statuses(): try: response = PolyaxonClient().experiment_job.get_statuses(user, project_name, _experiment, _job, page=page) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get status for job `{}`.'.format(job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) meta = get_meta_response(response) if meta: Printer.print_header('Statuses for Job `{}`.'.format(_job)) Printer.print_header('Navigation:') dict_tabulate(meta) else: Printer.print_header('No statuses found for job `{}`.'.format(_job)) objects = list_dicts_to_tabulate( [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status') for o in response['results']]) if objects: Printer.print_header("Statuses:") objects.pop('job', None) dict_tabulate(objects, is_list_dict=True) page = page or 1 user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_statuses() else: get_experiment_statuses()
[ "Get", "experiment", "or", "experiment", "job", "statuses", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L435-L527
[ "def", "statuses", "(", "ctx", ",", "job", ",", "page", ")", ":", "def", "get_experiment_statuses", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "get_statuses", "(", "user", ",", "project_name", ",", "_experiment", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could get status for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Statuses for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No statuses found for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "objects", "=", "list_dicts_to_tabulate", "(", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ",", "status_key", "=", "'status'", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Statuses:\"", ")", "objects", ".", "pop", "(", "'experiment'", ",", "None", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")", "def", "get_experiment_job_statuses", "(", ")", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "get_statuses", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "page", "=", "page", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get status for job `{}`.'", ".", "format", "(", "job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "meta", "=", "get_meta_response", "(", "response", ")", "if", "meta", ":", "Printer", ".", "print_header", "(", "'Statuses for Job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_header", "(", "'Navigation:'", ")", "dict_tabulate", "(", "meta", ")", "else", ":", "Printer", ".", "print_header", "(", "'No statuses found for job `{}`.'", ".", "format", "(", "_job", ")", ")", "objects", "=", "list_dicts_to_tabulate", "(", "[", "Printer", ".", "add_status_color", "(", "o", ".", "to_light_dict", "(", "humanize_values", "=", "True", ")", ",", "status_key", "=", "'status'", ")", "for", "o", "in", "response", "[", "'results'", "]", "]", ")", "if", "objects", ":", "Printer", ".", "print_header", "(", "\"Statuses:\"", ")", "objects", ".", "pop", "(", "'job'", ",", "None", ")", "dict_tabulate", "(", "objects", ",", "is_list_dict", "=", "True", ")", "page", "=", "page", "or", "1", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job_statuses", "(", ")", "else", ":", "get_experiment_statuses", "(", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
resources
Get experiment or experiment job resources. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment resources: \b ```bash $ polyaxon experiment -xp 19 resources ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources --gpu ``` Examples for getting experiment job resources: \b ```bash $ polyaxon experiment -xp 19 resources -j 1 ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources -j 1 --gpu ```
polyaxon_cli/cli/experiment.py
def resources(ctx, job, gpu): """Get experiment or experiment job resources. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment resources: \b ```bash $ polyaxon experiment -xp 19 resources ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources --gpu ``` Examples for getting experiment job resources: \b ```bash $ polyaxon experiment -xp 19 resources -j 1 ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources -j 1 --gpu ``` """ def get_experiment_resources(): try: message_handler = Printer.gpu_resources if gpu else Printer.resources PolyaxonClient().experiment.resources( user, project_name, _experiment, message_handler=message_handler) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get resources for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) def get_experiment_job_resources(): try: message_handler = Printer.gpu_resources if gpu else Printer.resources PolyaxonClient().experiment_job.resources(user, project_name, _experiment, _job, message_handler=message_handler) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get resources for job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_resources() else: get_experiment_resources()
def resources(ctx, job, gpu): """Get experiment or experiment job resources. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment resources: \b ```bash $ polyaxon experiment -xp 19 resources ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources --gpu ``` Examples for getting experiment job resources: \b ```bash $ polyaxon experiment -xp 19 resources -j 1 ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources -j 1 --gpu ``` """ def get_experiment_resources(): try: message_handler = Printer.gpu_resources if gpu else Printer.resources PolyaxonClient().experiment.resources( user, project_name, _experiment, message_handler=message_handler) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get resources for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) def get_experiment_job_resources(): try: message_handler = Printer.gpu_resources if gpu else Printer.resources PolyaxonClient().experiment_job.resources(user, project_name, _experiment, _job, message_handler=message_handler) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get resources for job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_resources() else: get_experiment_resources()
[ "Get", "experiment", "or", "experiment", "job", "resources", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L535-L599
[ "def", "resources", "(", "ctx", ",", "job", ",", "gpu", ")", ":", "def", "get_experiment_resources", "(", ")", ":", "try", ":", "message_handler", "=", "Printer", ".", "gpu_resources", "if", "gpu", "else", "Printer", ".", "resources", "PolyaxonClient", "(", ")", ".", "experiment", ".", "resources", "(", "user", ",", "project_name", ",", "_experiment", ",", "message_handler", "=", "message_handler", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get resources for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "def", "get_experiment_job_resources", "(", ")", ":", "try", ":", "message_handler", "=", "Printer", ".", "gpu_resources", "if", "gpu", "else", "Printer", ".", "resources", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "resources", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "message_handler", "=", "message_handler", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get resources for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job_resources", "(", ")", "else", ":", "get_experiment_resources", "(", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
logs
Get experiment or experiment job logs. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment logs: \b ```bash $ polyaxon experiment logs ``` \b ```bash $ polyaxon experiment -xp 10 -p mnist logs ``` Examples for getting experiment job logs: \b ```bash $ polyaxon experiment -xp 1 -j 1 logs ```
polyaxon_cli/cli/experiment.py
def logs(ctx, job, past, follow, hide_time): """Get experiment or experiment job logs. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment logs: \b ```bash $ polyaxon experiment logs ``` \b ```bash $ polyaxon experiment -xp 10 -p mnist logs ``` Examples for getting experiment job logs: \b ```bash $ polyaxon experiment -xp 1 -j 1 logs ``` """ def get_experiment_logs(): if past: try: response = PolyaxonClient().experiment.logs( user, project_name, _experiment, stream=False) get_logs_handler(handle_job_info=True, show_timestamp=not hide_time, stream=False)(response.content.decode().split('\n')) print() if not follow: return except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: if not follow: Printer.print_error( 'Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error( 'Error message `{}`.'.format(e)) sys.exit(1) try: PolyaxonClient().experiment.logs( user, project_name, _experiment, message_handler=get_logs_handler(handle_job_info=True, show_timestamp=not hide_time)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) def get_experiment_job_logs(): if past: try: response = PolyaxonClient().experiment_job.logs( user, project_name, _experiment, _job, stream=False) get_logs_handler(handle_job_info=True, show_timestamp=not hide_time, stream=False)(response.content.decode().split('\n')) print() if not follow: return except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: if not follow: Printer.print_error( 'Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error( 'Error message `{}`.'.format(e)) sys.exit(1) try: PolyaxonClient().experiment_job.logs( user, project_name, _experiment, _job, message_handler=get_logs_handler(handle_job_info=True, show_timestamp=not hide_time)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get logs for job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_logs() else: get_experiment_logs()
def logs(ctx, job, past, follow, hide_time): """Get experiment or experiment job logs. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment logs: \b ```bash $ polyaxon experiment logs ``` \b ```bash $ polyaxon experiment -xp 10 -p mnist logs ``` Examples for getting experiment job logs: \b ```bash $ polyaxon experiment -xp 1 -j 1 logs ``` """ def get_experiment_logs(): if past: try: response = PolyaxonClient().experiment.logs( user, project_name, _experiment, stream=False) get_logs_handler(handle_job_info=True, show_timestamp=not hide_time, stream=False)(response.content.decode().split('\n')) print() if not follow: return except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: if not follow: Printer.print_error( 'Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error( 'Error message `{}`.'.format(e)) sys.exit(1) try: PolyaxonClient().experiment.logs( user, project_name, _experiment, message_handler=get_logs_handler(handle_job_info=True, show_timestamp=not hide_time)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) def get_experiment_job_logs(): if past: try: response = PolyaxonClient().experiment_job.logs( user, project_name, _experiment, _job, stream=False) get_logs_handler(handle_job_info=True, show_timestamp=not hide_time, stream=False)(response.content.decode().split('\n')) print() if not follow: return except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: if not follow: Printer.print_error( 'Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error( 'Error message `{}`.'.format(e)) sys.exit(1) try: PolyaxonClient().experiment_job.logs( user, project_name, _experiment, _job, message_handler=get_logs_handler(handle_job_info=True, show_timestamp=not hide_time)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get logs for job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_logs() else: get_experiment_logs()
[ "Get", "experiment", "or", "experiment", "job", "logs", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L611-L712
[ "def", "logs", "(", "ctx", ",", "job", ",", "past", ",", "follow", ",", "hide_time", ")", ":", "def", "get_experiment_logs", "(", ")", ":", "if", "past", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "stream", "=", "False", ")", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ",", "stream", "=", "False", ")", "(", "response", ".", "content", ".", "decode", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "print", "(", ")", "if", "not", "follow", ":", "return", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "if", "not", "follow", ":", "Printer", ".", "print_error", "(", "'Could not get logs for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "message_handler", "=", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ")", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get logs for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "def", "get_experiment_job_logs", "(", ")", ":", "if", "past", ":", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "stream", "=", "False", ")", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ",", "stream", "=", "False", ")", "(", "response", ".", "content", ".", "decode", "(", ")", ".", "split", "(", "'\\n'", ")", ")", "print", "(", ")", "if", "not", "follow", ":", "return", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "if", "not", "follow", ":", "Printer", ".", "print_error", "(", "'Could not get logs for experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment_job", ".", "logs", "(", "user", ",", "project_name", ",", "_experiment", ",", "_job", ",", "message_handler", "=", "get_logs_handler", "(", "handle_job_info", "=", "True", ",", "show_timestamp", "=", "not", "hide_time", ")", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get logs for job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "if", "job", ":", "_job", "=", "get_experiment_job_or_local", "(", "job", ")", "get_experiment_job_logs", "(", ")", "else", ":", "get_experiment_logs", "(", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
unbookmark
Unbookmark experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment unbookmark ``` \b ```bash $ polyaxon experiment -xp 2 unbookmark ```
polyaxon_cli/cli/experiment.py
def unbookmark(ctx): """Unbookmark experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment unbookmark ``` \b ```bash $ polyaxon experiment -xp 2 unbookmark ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) try: PolyaxonClient().experiment.unbookmark(user, project_name, _experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not unbookmark experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment is unbookmarked.")
def unbookmark(ctx): """Unbookmark experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment unbookmark ``` \b ```bash $ polyaxon experiment -xp 2 unbookmark ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) try: PolyaxonClient().experiment.unbookmark(user, project_name, _experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not unbookmark experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment is unbookmarked.")
[ "Unbookmark", "experiment", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/experiment.py#L776-L802
[ "def", "unbookmark", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_experiment", "=", "get_project_experiment_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'experiment'", ")", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "experiment", ".", "unbookmark", "(", "user", ",", "project_name", ",", "_experiment", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not unbookmark experiment `{}`.'", ".", "format", "(", "_experiment", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Experiment is unbookmarked.\"", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
upload
Upload code of the current directory while respecting the .polyaxonignore file.
polyaxon_cli/cli/upload.py
def upload(sync=True): # pylint:disable=assign-to-new-keyword """Upload code of the current directory while respecting the .polyaxonignore file.""" project = ProjectManager.get_config_or_raise() files = IgnoreManager.get_unignored_file_paths() try: with create_tarfile(files, project.name) as file_path: with get_files_in_current_directory('repo', [file_path]) as (files, files_size): try: PolyaxonClient().project.upload_repo(project.user, project.name, files, files_size, sync=sync) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error( 'Could not upload code for project `{}`.'.format(project.name)) Printer.print_error('Error message `{}`.'.format(e)) Printer.print_error( 'Check the project exists, ' 'and that you have access rights, ' 'this could happen as well when uploading large files.' 'If you are running a notebook and mounting the code to the notebook, ' 'you should stop it before uploading.') sys.exit(1) Printer.print_success('Files uploaded.') except Exception as e: Printer.print_error("Could not upload the file.") Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1)
def upload(sync=True): # pylint:disable=assign-to-new-keyword """Upload code of the current directory while respecting the .polyaxonignore file.""" project = ProjectManager.get_config_or_raise() files = IgnoreManager.get_unignored_file_paths() try: with create_tarfile(files, project.name) as file_path: with get_files_in_current_directory('repo', [file_path]) as (files, files_size): try: PolyaxonClient().project.upload_repo(project.user, project.name, files, files_size, sync=sync) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error( 'Could not upload code for project `{}`.'.format(project.name)) Printer.print_error('Error message `{}`.'.format(e)) Printer.print_error( 'Check the project exists, ' 'and that you have access rights, ' 'this could happen as well when uploading large files.' 'If you are running a notebook and mounting the code to the notebook, ' 'you should stop it before uploading.') sys.exit(1) Printer.print_success('Files uploaded.') except Exception as e: Printer.print_error("Could not upload the file.") Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1)
[ "Upload", "code", "of", "the", "current", "directory", "while", "respecting", "the", ".", "polyaxonignore", "file", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/upload.py#L23-L51
[ "def", "upload", "(", "sync", "=", "True", ")", ":", "# pylint:disable=assign-to-new-keyword", "project", "=", "ProjectManager", ".", "get_config_or_raise", "(", ")", "files", "=", "IgnoreManager", ".", "get_unignored_file_paths", "(", ")", "try", ":", "with", "create_tarfile", "(", "files", ",", "project", ".", "name", ")", "as", "file_path", ":", "with", "get_files_in_current_directory", "(", "'repo'", ",", "[", "file_path", "]", ")", "as", "(", "files", ",", "files_size", ")", ":", "try", ":", "PolyaxonClient", "(", ")", ".", "project", ".", "upload_repo", "(", "project", ".", "user", ",", "project", ".", "name", ",", "files", ",", "files_size", ",", "sync", "=", "sync", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not upload code for project `{}`.'", ".", "format", "(", "project", ".", "name", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "Printer", ".", "print_error", "(", "'Check the project exists, '", "'and that you have access rights, '", "'this could happen as well when uploading large files.'", "'If you are running a notebook and mounting the code to the notebook, '", "'you should stop it before uploading.'", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "'Files uploaded.'", ")", "except", "Exception", "as", "e", ":", "Printer", ".", "print_error", "(", "\"Could not upload the file.\"", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
cluster
Get cluster and nodes info.
polyaxon_cli/cli/cluster.py
def cluster(node): """Get cluster and nodes info.""" cluster_client = PolyaxonClient().cluster if node: try: node_config = cluster_client.get_node(node) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load node `{}` info.'.format(node)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_node_info(node_config) else: try: cluster_config = cluster_client.get_cluster() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load cluster info.') Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_cluster_info(cluster_config)
def cluster(node): """Get cluster and nodes info.""" cluster_client = PolyaxonClient().cluster if node: try: node_config = cluster_client.get_node(node) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load node `{}` info.'.format(node)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_node_info(node_config) else: try: cluster_config = cluster_client.get_cluster() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load cluster info.') Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_cluster_info(cluster_config)
[ "Get", "cluster", "and", "nodes", "info", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/cluster.py#L51-L69
[ "def", "cluster", "(", "node", ")", ":", "cluster_client", "=", "PolyaxonClient", "(", ")", ".", "cluster", "if", "node", ":", "try", ":", "node_config", "=", "cluster_client", ".", "get_node", "(", "node", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load node `{}` info.'", ".", "format", "(", "node", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_node_info", "(", "node_config", ")", "else", ":", "try", ":", "cluster_config", "=", "cluster_client", ".", "get_cluster", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not load cluster info.'", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_cluster_info", "(", "cluster_config", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
check
Check a polyaxonfile.
polyaxon_cli/cli/check.py
def check(file, # pylint:disable=redefined-builtin version, definition): """Check a polyaxonfile.""" file = file or 'polyaxonfile.yaml' specification = check_polyaxonfile(file).specification if version: Printer.decorate_format_value('The version is: {}', specification.version, 'yellow') if definition: job_condition = (specification.is_job or specification.is_build or specification.is_notebook or specification.is_tensorboard) if specification.is_experiment: Printer.decorate_format_value('This polyaxon specification has {}', 'One experiment', 'yellow') if job_condition: Printer.decorate_format_value('This {} polyaxon specification is valid', specification.kind, 'yellow') if specification.is_group: experiments_def = specification.experiments_def click.echo( 'This polyaxon specification has experiment group with the following definition:') get_group_experiments_info(**experiments_def) return specification
def check(file, # pylint:disable=redefined-builtin version, definition): """Check a polyaxonfile.""" file = file or 'polyaxonfile.yaml' specification = check_polyaxonfile(file).specification if version: Printer.decorate_format_value('The version is: {}', specification.version, 'yellow') if definition: job_condition = (specification.is_job or specification.is_build or specification.is_notebook or specification.is_tensorboard) if specification.is_experiment: Printer.decorate_format_value('This polyaxon specification has {}', 'One experiment', 'yellow') if job_condition: Printer.decorate_format_value('This {} polyaxon specification is valid', specification.kind, 'yellow') if specification.is_group: experiments_def = specification.experiments_def click.echo( 'This polyaxon specification has experiment group with the following definition:') get_group_experiments_info(**experiments_def) return specification
[ "Check", "a", "polyaxonfile", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/check.py#L67-L98
[ "def", "check", "(", "file", ",", "# pylint:disable=redefined-builtin", "version", ",", "definition", ")", ":", "file", "=", "file", "or", "'polyaxonfile.yaml'", "specification", "=", "check_polyaxonfile", "(", "file", ")", ".", "specification", "if", "version", ":", "Printer", ".", "decorate_format_value", "(", "'The version is: {}'", ",", "specification", ".", "version", ",", "'yellow'", ")", "if", "definition", ":", "job_condition", "=", "(", "specification", ".", "is_job", "or", "specification", ".", "is_build", "or", "specification", ".", "is_notebook", "or", "specification", ".", "is_tensorboard", ")", "if", "specification", ".", "is_experiment", ":", "Printer", ".", "decorate_format_value", "(", "'This polyaxon specification has {}'", ",", "'One experiment'", ",", "'yellow'", ")", "if", "job_condition", ":", "Printer", ".", "decorate_format_value", "(", "'This {} polyaxon specification is valid'", ",", "specification", ".", "kind", ",", "'yellow'", ")", "if", "specification", ".", "is_group", ":", "experiments_def", "=", "specification", ".", "experiments_def", "click", ".", "echo", "(", "'This polyaxon specification has experiment group with the following definition:'", ")", "get_group_experiments_info", "(", "*", "*", "experiments_def", ")", "return", "specification" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
clean_outputs
Decorator for CLI with Sentry client handling. see https://github.com/getsentry/raven-python/issues/904 for more details.
polyaxon_cli/logger.py
def clean_outputs(fn): """Decorator for CLI with Sentry client handling. see https://github.com/getsentry/raven-python/issues/904 for more details. """ @wraps(fn) def clean_outputs_wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except SystemExit as e: sys.stdout = StringIO() sys.exit(e.code) # make sure we still exit with the proper code except Exception as e: sys.stdout = StringIO() raise e return clean_outputs_wrapper
def clean_outputs(fn): """Decorator for CLI with Sentry client handling. see https://github.com/getsentry/raven-python/issues/904 for more details. """ @wraps(fn) def clean_outputs_wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except SystemExit as e: sys.stdout = StringIO() sys.exit(e.code) # make sure we still exit with the proper code except Exception as e: sys.stdout = StringIO() raise e return clean_outputs_wrapper
[ "Decorator", "for", "CLI", "with", "Sentry", "client", "handling", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/logger.py#L41-L58
[ "def", "clean_outputs", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "clean_outputs_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "SystemExit", "as", "e", ":", "sys", ".", "stdout", "=", "StringIO", "(", ")", "sys", ".", "exit", "(", "e", ".", "code", ")", "# make sure we still exit with the proper code", "except", "Exception", "as", "e", ":", "sys", ".", "stdout", "=", "StringIO", "(", ")", "raise", "e", "return", "clean_outputs_wrapper" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
job
Commands for jobs.
polyaxon_cli/cli/job.py
def job(ctx, project, job): # pylint:disable=redefined-outer-name """Commands for jobs.""" ctx.obj = ctx.obj or {} ctx.obj['project'] = project ctx.obj['job'] = job
def job(ctx, project, job): # pylint:disable=redefined-outer-name """Commands for jobs.""" ctx.obj = ctx.obj or {} ctx.obj['project'] = project ctx.obj['job'] = job
[ "Commands", "for", "jobs", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L51-L55
[ "def", "job", "(", "ctx", ",", "project", ",", "job", ")", ":", "# pylint:disable=redefined-outer-name", "ctx", ".", "obj", "=", "ctx", ".", "obj", "or", "{", "}", "ctx", ".", "obj", "[", "'project'", "]", "=", "project", "ctx", ".", "obj", "[", "'job'", "]", "=", "job" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
get
Get job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 get ``` \b ```bash $ polyaxon job --job=1 --project=project_name get ```
polyaxon_cli/cli/job.py
def get(ctx): """Get job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 get ``` \b ```bash $ polyaxon job --job=1 --project=project_name get ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) try: response = PolyaxonClient().job.get_job(user, project_name, _job) cache.cache(config_manager=JobManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_job_details(response)
def get(ctx): """Get job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 get ``` \b ```bash $ polyaxon job --job=1 --project=project_name get ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) try: response = PolyaxonClient().job.get_job(user, project_name, _job) cache.cache(config_manager=JobManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_job_details(response)
[ "Get", "job", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L61-L87
[ "def", "get", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "get_job", "(", "user", ",", "project_name", ",", "_job", ")", "cache", ".", "cache", "(", "config_manager", "=", "JobManager", ",", "response", "=", "response", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not get job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_job_details", "(", "response", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
delete
Delete job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job delete ```
polyaxon_cli/cli/job.py
def delete(ctx): """Delete job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job delete ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) if not click.confirm("Are sure you want to delete job `{}`".format(_job)): click.echo('Existing without deleting job.') sys.exit(1) try: response = PolyaxonClient().job.delete_job( user, project_name, _job) # Purge caching JobManager.purge() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not delete job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Job `{}` was delete successfully".format(_job))
def delete(ctx): """Delete job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job delete ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) if not click.confirm("Are sure you want to delete job `{}`".format(_job)): click.echo('Existing without deleting job.') sys.exit(1) try: response = PolyaxonClient().job.delete_job( user, project_name, _job) # Purge caching JobManager.purge() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not delete job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Job `{}` was delete successfully".format(_job))
[ "Delete", "job", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L93-L121
[ "def", "delete", "(", "ctx", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "if", "not", "click", ".", "confirm", "(", "\"Are sure you want to delete job `{}`\"", ".", "format", "(", "_job", ")", ")", ":", "click", ".", "echo", "(", "'Existing without deleting job.'", ")", "sys", ".", "exit", "(", "1", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "delete_job", "(", "user", ",", "project_name", ",", "_job", ")", "# Purge caching", "JobManager", ".", "purge", "(", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not delete job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "if", "response", ".", "status_code", "==", "204", ":", "Printer", ".", "print_success", "(", "\"Job `{}` was delete successfully\"", ".", "format", "(", "_job", ")", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
update
Update job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job -j 2 update --description="new description for my job" ```
polyaxon_cli/cli/job.py
def update(ctx, name, description, tags): """Update job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job -j 2 update --description="new description for my job" ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) update_dict = {} if name: update_dict['name'] = name if description: update_dict['description'] = description tags = validate_tags(tags) if tags: update_dict['tags'] = tags if not update_dict: Printer.print_warning('No argument was provided to update the job.') sys.exit(0) try: response = PolyaxonClient().job.update_job( user, project_name, _job, update_dict) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not update job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Job updated.") get_job_details(response)
def update(ctx, name, description, tags): """Update job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job -j 2 update --description="new description for my job" ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) update_dict = {} if name: update_dict['name'] = name if description: update_dict['description'] = description tags = validate_tags(tags) if tags: update_dict['tags'] = tags if not update_dict: Printer.print_warning('No argument was provided to update the job.') sys.exit(0) try: response = PolyaxonClient().job.update_job( user, project_name, _job, update_dict) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not update job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Job updated.") get_job_details(response)
[ "Update", "job", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L131-L169
[ "def", "update", "(", "ctx", ",", "name", ",", "description", ",", "tags", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "update_dict", "=", "{", "}", "if", "name", ":", "update_dict", "[", "'name'", "]", "=", "name", "if", "description", ":", "update_dict", "[", "'description'", "]", "=", "description", "tags", "=", "validate_tags", "(", "tags", ")", "if", "tags", ":", "update_dict", "[", "'tags'", "]", "=", "tags", "if", "not", "update_dict", ":", "Printer", ".", "print_warning", "(", "'No argument was provided to update the job.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "update_job", "(", "user", ",", "project_name", ",", "_job", ",", "update_dict", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not update job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Job updated.\"", ")", "get_job_details", "(", "response", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
stop
Stop job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job stop ``` \b ```bash $ polyaxon job -xp 2 stop ```
polyaxon_cli/cli/job.py
def stop(ctx, yes): """Stop job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job stop ``` \b ```bash $ polyaxon job -xp 2 stop ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) if not yes and not click.confirm("Are sure you want to stop " "job `{}`".format(_job)): click.echo('Existing without stopping job.') sys.exit(0) try: PolyaxonClient().job.stop(user, project_name, _job) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not stop job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Job is being stopped.")
def stop(ctx, yes): """Stop job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job stop ``` \b ```bash $ polyaxon job -xp 2 stop ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) if not yes and not click.confirm("Are sure you want to stop " "job `{}`".format(_job)): click.echo('Existing without stopping job.') sys.exit(0) try: PolyaxonClient().job.stop(user, project_name, _job) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not stop job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Job is being stopped.")
[ "Stop", "job", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L178-L208
[ "def", "stop", "(", "ctx", ",", "yes", ")", ":", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "if", "not", "yes", "and", "not", "click", ".", "confirm", "(", "\"Are sure you want to stop \"", "\"job `{}`\"", ".", "format", "(", "_job", ")", ")", ":", "click", ".", "echo", "(", "'Existing without stopping job.'", ")", "sys", ".", "exit", "(", "0", ")", "try", ":", "PolyaxonClient", "(", ")", ".", "job", ".", "stop", "(", "user", ",", "project_name", ",", "_job", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not stop job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "Printer", ".", "print_success", "(", "\"Job is being stopped.\"", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449
valid
restart
Restart job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 restart ```
polyaxon_cli/cli/job.py
def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin """Restart job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 restart ``` """ config = None update_code = None if file: config = rhea.read(file) # Check if we need to upload if u: ctx.invoke(upload, sync=False) update_code = True user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) try: if copy: response = PolyaxonClient().job.copy( user, project_name, _job, config=config, update_code=update_code) else: response = PolyaxonClient().job.restart( user, project_name, _job, config=config, update_code=update_code) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not restart job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_job_details(response)
def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin """Restart job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 restart ``` """ config = None update_code = None if file: config = rhea.read(file) # Check if we need to upload if u: ctx.invoke(upload, sync=False) update_code = True user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) try: if copy: response = PolyaxonClient().job.copy( user, project_name, _job, config=config, update_code=update_code) else: response = PolyaxonClient().job.restart( user, project_name, _job, config=config, update_code=update_code) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not restart job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_job_details(response)
[ "Restart", "job", "." ]
polyaxon/polyaxon-cli
python
https://github.com/polyaxon/polyaxon-cli/blob/a7f5eed74d4d909cad79059f3c21c58606881449/polyaxon_cli/cli/job.py#L220-L255
[ "def", "restart", "(", "ctx", ",", "copy", ",", "file", ",", "u", ")", ":", "# pylint:disable=redefined-builtin", "config", "=", "None", "update_code", "=", "None", "if", "file", ":", "config", "=", "rhea", ".", "read", "(", "file", ")", "# Check if we need to upload", "if", "u", ":", "ctx", ".", "invoke", "(", "upload", ",", "sync", "=", "False", ")", "update_code", "=", "True", "user", ",", "project_name", ",", "_job", "=", "get_job_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'job'", ")", ")", "try", ":", "if", "copy", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "copy", "(", "user", ",", "project_name", ",", "_job", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "else", ":", "response", "=", "PolyaxonClient", "(", ")", ".", "job", ".", "restart", "(", "user", ",", "project_name", ",", "_job", ",", "config", "=", "config", ",", "update_code", "=", "update_code", ")", "except", "(", "PolyaxonHTTPError", ",", "PolyaxonShouldExitError", ",", "PolyaxonClientException", ")", "as", "e", ":", "Printer", ".", "print_error", "(", "'Could not restart job `{}`.'", ".", "format", "(", "_job", ")", ")", "Printer", ".", "print_error", "(", "'Error message `{}`.'", ".", "format", "(", "e", ")", ")", "sys", ".", "exit", "(", "1", ")", "get_job_details", "(", "response", ")" ]
a7f5eed74d4d909cad79059f3c21c58606881449