signature:
def encrypt ( self , text , appid ) :
    """对明文进行加密
 @ param text : 需要加密的明文
 @ return : 加密得到的字符串"""

implementation:
# 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


signature:
def decrypt ( self , text , appid ) :
    """对解密后的明文进行补位删除
 @ param text : 密文
 @ return : 删除填充补位后的明文"""

implementation:
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


signature:
def get_random_str ( self ) :
    """随机生成16位字符串
 @ return : 16位字符串"""

implementation:
rule = string . letters + string . digits
str = random . sample ( rule , 16 )
return "" . join ( str )


signature:
def deliveries ( self ) :
    """Get delivery log from Redis"""

implementation:
key = make_key ( event = self . object . event , owner_name = self . object . owner . username , identifier = self . object . identifier )
return redis . lrange ( key , 0 , 20 )


signature:
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"""

implementation:
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 ( )


signature:
def notify ( self , message ) :
    """TODO : Add code to lpush to redis stack
 rpop when stack hits size ' X '"""

implementation:
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 )


signature:
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 ."""

implementation:
# 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


signature:
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"""

implementation:
# 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 )


signature:
def checkTUN ( self ) :
    """Checks the TUN adapter for data and returns any that is found .
 Returns :
 packet : Data read from the TUN adapter"""

implementation:
packet = self . _TUN . _tun . read ( self . _TUN . _tun . mtu )
return ( packet )


signature:
def monitorTUN ( self ) :
    """Monitors the TUN adapter and sends data over serial port .
 Returns :
 ret : Number of bytes sent over serial port"""

implementation:
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" )


signature:
def checkSerial ( self ) :
    """Check the serial port for data to write to the TUN adapter ."""

implementation:
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 )


signature:
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 ."""

implementation:
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


signature:
def _create_formsets ( self , request , obj , change , index , is_template ) :
    "Helper function to generate formsets for add / change _ view ."

implementation:
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


signature:
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 ."""

implementation:
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


signature:
def value_from_datadict ( self , * args , ** kwargs ) :
    """Pass the submitted value through the sanitizer before returning it ."""

implementation:
value = super ( RichTextWidget , self ) . value_from_datadict ( * args , ** kwargs )
if value is not None :
    value = self . get_sanitizer ( ) ( value )
return value


signature:
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 ."""

implementation:
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


signature:
def heappop_max ( heap ) :
    """Maxheap version of a heappop ."""

implementation:
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


signature:
def heapreplace_max ( heap , item ) :
    """Maxheap version of a heappop followed by a heappush ."""

implementation:
returnitem = heap [ 0 ]
# raises appropriate IndexError if heap is empty
heap [ 0 ] = item
_siftup_max ( heap , 0 )
return returnitem


signature:
def heappush_max ( heap , item ) :
    """Push item onto heap , maintaining the heap invariant ."""

implementation:
heap . append ( item )
_siftdown_max ( heap , 0 , len ( heap ) - 1 )


signature:
def heappushpop_max ( heap , item ) :
    """Fast version of a heappush followed by a heappop ."""

implementation:
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


signature:
def validate_response ( expected_responses ) :
    """Decorator to validate responses from QTM"""

implementation:
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


signature:
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 `"""

implementation:
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 )


signature:
async def qtm_version ( self ) :
    """Get the QTM version ."""

implementation: return await asyncio . wait_for ( self . _protocol . send_command ( "qtmversion" ) , timeout = self . _timeout )


signature:
async def byte_order ( self ) :
    """Get the byte order used when communicating
 ( should only ever be little endian using this library ) ."""

implementation: return await asyncio . wait_for ( self . _protocol . send_command ( "byteorder" ) , timeout = self . _timeout )


signature:
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 `"""

implementation:
await self . _protocol . send_command ( "getstate" , callback = False )
return await self . _protocol . await_event ( )


signature:
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 `"""

implementation: return await self . _protocol . await_event ( event , timeout = timeout )


signature:
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 ."""

implementation:
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 )


signature:
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"""

implementation:
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 )


signature:
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"""

implementation:
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 )


signature:
async def stream_frames_stop ( self ) :
    """Stop streaming frames ."""

implementation:
self . _protocol . set_on_packet ( None )
cmd = "streamframes stop"
await self . _protocol . send_command ( cmd , callback = False )


signature:
async def take_control ( self , password ) :
    """Take control of QTM .
 : param password : Password as entered in QTM ."""

implementation:
cmd = "takecontrol %s" % password
return await asyncio . wait_for ( self . _protocol . send_command ( cmd ) , timeout = self . _timeout )


signature:
async def release_control ( self ) :
    """Release control of QTM ."""

implementation:
cmd = "releasecontrol"
return await asyncio . wait_for ( self . _protocol . send_command ( cmd ) , timeout = self . _timeout )


signature:
async def start ( self , rtfromfile = False ) :
    """Start RT from file . You need to be in control of QTM to be able to do this ."""

implementation:
cmd = "start" + ( " rtfromfile" if rtfromfile else "" )
return await asyncio . wait_for ( self . _protocol . send_command ( cmd ) , timeout = self . _timeout )


signature:
async def load ( self , filename ) :
    """Load a measurement .
 : param filename : Path to measurement you want to load ."""

implementation:
cmd = "load %s" % filename
return await asyncio . wait_for ( self . _protocol . send_command ( cmd ) , timeout = self . _timeout )


signature:
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 ."""

implementation:
cmd = "save %s%s" % ( filename , " overwrite" if overwrite else "" )
return await asyncio . wait_for ( self . _protocol . send_command ( cmd ) , timeout = self . _timeout )


signature:
async def load_project ( self , project_path ) :
    """Load a project .
 : param project _ path : Path to project you want to load ."""

implementation:
cmd = "loadproject %s" % project_path
return await asyncio . wait_for ( self . _protocol . send_command ( cmd ) , timeout = self . _timeout )


signature:
async def set_qtm_event ( self , event = None ) :
    """Set event in QTM ."""

implementation:
cmd = "event%s" % ( "" if event is None else " " + event )
return await asyncio . wait_for ( self . _protocol . send_command ( cmd ) , timeout = self . _timeout )


signature:
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 ."""

implementation: return await asyncio . wait_for ( self . _protocol . send_command ( xml , command_type = QRTPacketType . PacketXML ) , timeout = self . _timeout , )


signature:
def data_received ( self , data ) :
    """Received from QTM and route accordingly"""

implementation:
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


signature:
def get_analog ( self , component_info = None , data = None , component_position = None ) :
    """Get analog data ."""

implementation:
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


signature:
def get_analog_single ( self , component_info = None , data = None , component_position = None ) :
    """Get a single analog data channel ."""

implementation:
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


signature:
def get_force ( self , component_info = None , data = None , component_position = None ) :
    """Get force data ."""

implementation:
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


signature:
def get_force_single ( self , component_info = None , data = None , component_position = None ) :
    """Get a single force data channel ."""

implementation:
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


signature:
def get_6d ( self , component_info = None , data = None , component_position = None ) :
    """Get 6D data ."""

implementation:
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


signature:
def get_6d_euler ( self , component_info = None , data = None , component_position = None ) :
    """Get 6D data with euler rotations ."""

implementation:
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


signature:
def get_image ( self , component_info = None , data = None , component_position = None ) :
    """Get image ."""

implementation:
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


signature:
def get_3d_markers ( self , component_info = None , data = None , component_position = None ) :
    """Get 3D markers ."""

implementation: return self . _get_3d_markers ( RT3DMarkerPosition , component_info , data , component_position )


signature:
def get_3d_markers_residual ( self , component_info = None , data = None , component_position = None ) :
    """Get 3D markers with residual ."""

implementation: return self . _get_3d_markers ( RT3DMarkerPositionResidual , component_info , data , component_position )


signature:
def get_3d_markers_no_label ( self , component_info = None , data = None , component_position = None ) :
    """Get 3D markers without label ."""

implementation: return self . _get_3d_markers ( RT3DMarkerPositionNoLabel , component_info , data , component_position )


signature:
def get_3d_markers_no_label_residual ( self , component_info = None , data = None , component_position = None ) :
    """Get 3D markers without label with residual ."""

implementation: return self . _get_3d_markers ( RT3DMarkerPositionNoLabelResidual , component_info , data , component_position )


signature:
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 ."""

implementation: return self . _get_2d_markers ( data , component_info , component_position , index = index )


signature:
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 ."""


signature:
def get_skeletons ( self , component_info = None , data = None , component_position = None ) :
    """Get skeletons"""

implementation:
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


signature:
async def await_event ( self , event = None , timeout = None ) :
    """Wait for any or specified event"""

implementation:
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


signature:
def send_command ( self , command , callback = True , command_type = QRTPacketType . PacketCommand ) :
    """Sends commands to QTM"""

implementation:
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!" )


signature:
async def reboot ( ip_address ) :
    """async function to reboot QTM cameras"""

implementation:
_ , 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 ( )


signature:
def on_packet ( packet ) :
    """Callback function that is called everytime a data packet arrives from QTM"""

implementation:
print ( "Framenumber: {}" . format ( packet . framenumber ) )
header , markers = packet . get_3d_markers ( )
print ( "Component info: {}" . format ( header ) )
for marker in markers :
    print ( "\t" , marker )


signature:
async def setup ( ) :
    """Main function"""

implementation:
connection = await qtm . connect ( "127.0.0.1" )
if connection is None :
    return
await connection . stream_frames ( components = [ "3d" ] , on_packet = on_packet )


signature:
def connection_made ( self , transport ) :
    """On socket creation"""

implementation:
self . transport = transport
sock = transport . get_extra_info ( "socket" )
self . port = sock . getsockname ( ) [ 1 ]


signature:
def datagram_received ( self , datagram , address ) :
    """Parse response from QTM instances"""

implementation:
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 ) )


signature:
def send_discovery_packet ( self ) :
    """Send discovery packet for QTM to respond to"""

implementation:
if self . port is None :
    return
self . transport . sendto ( QRTDiscoveryP1 . pack ( QRTDiscoveryPacketSize , QRTPacketType . PacketDiscover . value ) + QRTDiscoveryP2 . pack ( self . port ) , ( "<broadcast>" , 22226 ) , )


signature:
async def packet_receiver ( queue ) :
    """Asynchronous function that processes queue until None is posted in queue"""

implementation:
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" )


signature:
async def choose_qtm_instance ( interface ) :
    """List running QTM instances , asks for input and return chosen QTM"""

implementation:
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


signature:
async def main ( interface = None ) :
    """Main function"""

implementation:
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 ( )


signature:
async def package_receiver ( queue ) :
    """Asynchronous function that processes queue until None is posted in queue"""

implementation:
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" )


signature:
async def setup ( ) :
    """main function"""

implementation:
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 ) )


signature:
def create_body_index ( xml_string ) :
    """Extract a name to index dictionary from 6dof settings xml"""

implementation:
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


signature:
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 ' ] ) .'''

implementation:
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


signature:
def find_x ( path1 ) :
    '''Return true if substring is in string for files
 in specified path'''

implementation:
libs = os . listdir ( path1 )
for lib_dir in libs :
    if "doublefann" in lib_dir :
        return True


signature:
def find_fann ( ) :
    '''Find doublefann library'''

implementation:
# 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!" )


signature:
def build_swig ( ) :
    '''Run SWIG with specified parameters'''

implementation:
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 ( )


signature:
def experiment ( ctx , project , experiment ) : # pylint : disable = redefined - outer - name
    """Commands for experiments ."""

implementation:
ctx . obj = ctx . obj or { }
ctx . obj [ 'project' ] = project
ctx . obj [ 'experiment' ] = experiment


signature:
def get ( ctx , job ) :
    """Get experiment or experiment job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples for getting an experiment :
 ` ` ` bash
 $ polyaxon experiment get # if experiment is cached
 ` ` ` bash
 $ polyaxon experiment - - experiment = 1 get
 ` ` ` bash
 $ polyaxon experiment - xp 1 - - project = cats - vs - dogs get
 ` ` ` bash
 $ polyaxon experiment - xp 1 - p alain / cats - vs - dogs get
 Examples for getting an experiment job :
 ` ` ` bash
 $ polyaxon experiment get - j 1 # if experiment is cached
 ` ` ` bash
 $ polyaxon experiment - - experiment = 1 get - - job = 10
 ` ` ` bash
 $ polyaxon experiment - xp 1 - - project = cats - vs - dogs get - j 2
 ` ` ` bash
 $ polyaxon experiment - xp 1 - p alain / cats - vs - dogs get - j 2"""

implementation:
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 ( )


signature:
def delete ( ctx ) :
    """Delete experiment .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon experiment delete"""

implementation:
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 ) )


signature:
def update ( ctx , name , description , tags ) :
    """Update experiment .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon experiment - xp 2 update - - description = " new description for my experiments "
 ` ` ` bash
 $ polyaxon experiment - xp 2 update - - tags = " foo , bar " - - name = " unique - name " """

implementation:
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 )


signature:
def stop ( ctx , yes ) :
    """Stop experiment .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon experiment stop
 ` ` ` bash
 $ polyaxon experiment - xp 2 stop"""

implementation:
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." )


signature:
def restart ( ctx , copy , file , u ) : # pylint : disable = redefined - builtin
    """Restart experiment .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon experiment - - experiment = 1 restart"""

implementation:
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 )


signature:
def statuses ( ctx , job , page ) :
    """Get experiment or experiment job statuses .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples getting experiment statuses :
 ` ` ` bash
 $ polyaxon experiment statuses
 ` ` ` bash
 $ polyaxon experiment - xp 1 statuses
 Examples getting experiment job statuses :
 ` ` ` bash
 $ polyaxon experiment statuses - j 3
 ` ` ` bash
 $ polyaxon experiment - xp 1 statuses - - job 1"""

implementation:
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 ( )


signature:
def resources ( ctx , job , gpu ) :
    """Get experiment or experiment job resources .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples for getting experiment resources :
 ` ` ` bash
 $ polyaxon experiment - xp 19 resources
 For GPU resources
 ` ` ` bash
 $ polyaxon experiment - xp 19 resources - - gpu
 Examples for getting experiment job resources :
 ` ` ` bash
 $ polyaxon experiment - xp 19 resources - j 1
 For GPU resources
 ` ` ` bash
 $ polyaxon experiment - xp 19 resources - j 1 - - gpu"""

implementation:
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 ( )


signature:
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 :
 ` ` ` bash
 $ polyaxon experiment logs
 ` ` ` bash
 $ polyaxon experiment - xp 10 - p mnist logs
 Examples for getting experiment job logs :
 ` ` ` bash
 $ polyaxon experiment - xp 1 - j 1 logs"""

implementation:
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 ( )


signature:
def unbookmark ( ctx ) :
    """Unbookmark experiment .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon experiment unbookmark
 ` ` ` bash
 $ polyaxon experiment - xp 2 unbookmark"""

implementation:
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." )


signature:
def upload ( sync = True ) : # pylint : disable = assign - to - new - keyword
    """Upload code of the current directory while respecting the . polyaxonignore file ."""

implementation:
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 )


signature:
def cluster ( node ) :
    """Get cluster and nodes info ."""

implementation:
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 )


signature:
def check ( file , # pylint : disable = redefined - builtin
version , definition ) :
    """Check a polyaxonfile ."""

implementation:
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


signature:
def clean_outputs ( fn ) :
    """Decorator for CLI with Sentry client handling .
 see https : / / github . com / getsentry / raven - python / issues / 904 for more details ."""

implementation:
@ 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


signature:
def job ( ctx , project , job ) : # pylint : disable = redefined - outer - name
    """Commands for jobs ."""

implementation:
ctx . obj = ctx . obj or { }
ctx . obj [ 'project' ] = project
ctx . obj [ 'job' ] = job


signature:
def get ( ctx ) :
    """Get job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon job - - job = 1 get
 ` ` ` bash
 $ polyaxon job - - job = 1 - - project = project _ name get"""

implementation:
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 )


signature:
def delete ( ctx ) :
    """Delete job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon job delete"""

implementation:
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 ) )


signature:
def update ( ctx , name , description , tags ) :
    """Update job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon job - j 2 update - - description = " new description for my job " """

implementation:
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 )


signature:
def stop ( ctx , yes ) :
    """Stop job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon job stop
 ` ` ` bash
 $ polyaxon job - xp 2 stop"""

implementation:
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." )


signature:
def restart ( ctx , copy , file , u ) : # pylint : disable = redefined - builtin
    """Restart job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon job - - job = 1 restart"""

implementation:
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 )


signature:
def statuses ( ctx , page ) :
    """Get job statuses .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon job - j 2 statuses"""

implementation:
user , project_name , _job = get_job_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'job' ) )
page = page or 1
try :
    response = PolyaxonClient ( ) . job . get_statuses ( user , project_name , _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 )


signature:
def resources ( ctx , gpu ) :
    """Get job resources .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon job - j 2 resources
 For GPU resources
 ` ` ` bash
 $ polyaxon job - j 2 resources - - gpu"""

implementation:
user , project_name , _job = get_job_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'job' ) )
try :
    message_handler = Printer . gpu_resources if gpu else Printer . resources
    PolyaxonClient ( ) . job . resources ( user , project_name , _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 )


signature:
def logs ( ctx , past , follow , hide_time ) :
    """Get job logs .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon job - j 2 logs
 ` ` ` bash
 $ polyaxon job logs"""

implementation:
user , project_name , _job = get_job_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'job' ) )
if past :
    try :
        response = PolyaxonClient ( ) . job . logs ( user , project_name , _job , stream = False )
        get_logs_handler ( handle_job_info = False , 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 job `{}`.' . format ( _job ) )
            Printer . print_error ( 'Error message `{}`.' . format ( e ) )
            sys . exit ( 1 )
try :
    PolyaxonClient ( ) . job . logs ( user , project_name , _job , message_handler = get_logs_handler ( handle_job_info = False , 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 )


signature:
def outputs ( ctx ) :
    """Download outputs for job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon job - j 1 outputs"""

implementation:
user , project_name , _job = get_job_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'job' ) )
try :
    PolyaxonClient ( ) . job . download_outputs ( user , project_name , _job )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not download outputs for job `{}`.' . format ( _job ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( 'Files downloaded.' )


signature:
def pprint ( value ) :
    """Prints as formatted JSON"""

implementation: click . echo ( json . dumps ( value , sort_keys = True , indent = 4 , separators = ( ',' , ': ' ) ) )


signature:
def login ( token , username , password ) :
    """Login to Polyaxon ."""

implementation:
auth_client = PolyaxonClient ( ) . auth
if username : # Use username / password login
    if not password :
        password = click . prompt ( 'Please enter your password' , type = str , hide_input = True )
        password = password . strip ( )
        if not password :
            logger . info ( 'You entered an empty string. ' 'Please make sure you enter your password correctly.' )
            sys . exit ( 1 )
    credentials = CredentialsConfig ( username = username , password = password )
    try :
        access_code = auth_client . login ( credentials = credentials )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not login.' )
        Printer . print_error ( 'Error Message `{}`.' . format ( e ) )
        sys . exit ( 1 )
    if not access_code :
        Printer . print_error ( "Failed to login" )
        return
else :
    if not token :
        token_url = "{}/app/token" . format ( auth_client . config . http_host )
        click . confirm ( 'Authentication token page will now open in your browser. Continue?' , abort = True , default = True )
        click . launch ( token_url )
        logger . info ( "Please copy and paste the authentication token." )
        token = click . prompt ( 'This is an invisible field. Paste token and press ENTER' , type = str , hide_input = True )
    if not token :
        logger . info ( "Empty token received. " "Make sure your shell is handling the token appropriately." )
        logger . info ( "See docs for help: http://docs.polyaxon.com/polyaxon_cli/commands/auth" )
        return
    access_code = token . strip ( " " )
# Set user
try :
    AuthConfigManager . purge ( )
    user = PolyaxonClient ( ) . auth . get_user ( token = access_code )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not load user info.' )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
access_token = AccessTokenConfig ( username = user . username , token = access_code )
AuthConfigManager . set_config ( access_token )
Printer . print_success ( "Login successful" )
# Reset current cli
server_version = get_server_version ( )
current_version = get_current_version ( )
log_handler = get_log_handler ( )
CliConfigManager . reset ( check_count = 0 , current_version = current_version , min_version = server_version . min_version , log_handler = log_handler )


signature:
def whoami ( ) :
    """Show current logged Polyaxon user ."""

implementation:
try :
    user = PolyaxonClient ( ) . auth . get_user ( )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not load user info.' )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
click . echo ( "\nUsername: {username}, Email: {email}\n" . format ( ** user . to_dict ( ) ) )


signature:
def build ( ctx , project , build ) : # pylint : disable = redefined - outer - name
    """Commands for build jobs ."""

implementation:
ctx . obj = ctx . obj or { }
ctx . obj [ 'project' ] = project
ctx . obj [ 'build' ] = build


signature:
def get ( ctx ) :
    """Get build job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon build - b 1 get
 ` ` ` bash
 $ polyaxon build - - build = 1 - - project = project _ name get"""

implementation:
user , project_name , _build = get_build_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'build' ) )
try :
    response = PolyaxonClient ( ) . build_job . get_build ( user , project_name , _build )
    cache . cache ( config_manager = BuildJobManager , response = response )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get build job `{}`.' . format ( _build ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
get_build_details ( response )


signature:
def delete ( ctx ) :
    """Delete build job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon build delete
 ` ` ` bash
 $ polyaxon build - b 2 delete"""

implementation:
user , project_name , _build = get_build_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'build' ) )
if not click . confirm ( "Are sure you want to delete build job `{}`" . format ( _build ) ) :
    click . echo ( 'Existing without deleting build job.' )
    sys . exit ( 1 )
try :
    response = PolyaxonClient ( ) . build_job . delete_build ( user , project_name , _build )
    # Purge caching
    BuildJobManager . purge ( )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not delete job `{}`.' . format ( _build ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
if response . status_code == 204 :
    Printer . print_success ( "Build job `{}` was deleted successfully" . format ( _build ) )


signature:
def update ( ctx , name , description , tags ) :
    """Update build .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon build - b 2 update - - description = " new description for my build " """

implementation:
user , project_name , _build = get_build_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'build' ) )
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 build.' )
    sys . exit ( 0 )
try :
    response = PolyaxonClient ( ) . build_job . update_build ( user , project_name , _build , update_dict )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not update build `{}`.' . format ( _build ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Build updated." )
get_build_details ( response )


signature:
def stop ( ctx , yes ) :
    """Stop build job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon build stop
 ` ` ` bash
 $ polyaxon build - b 2 stop"""

implementation:
user , project_name , _build = get_build_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'build' ) )
if not yes and not click . confirm ( "Are sure you want to stop " "job `{}`" . format ( _build ) ) :
    click . echo ( 'Existing without stopping build job.' )
    sys . exit ( 0 )
try :
    PolyaxonClient ( ) . build_job . stop ( user , project_name , _build )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not stop build job `{}`.' . format ( _build ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Build job is being stopped." )


signature:
def bookmark ( ctx ) :
    """Bookmark build job .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon build bookmark
 ` ` ` bash
 $ polyaxon build - b 2 bookmark"""

implementation:
user , project_name , _build = get_build_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'build' ) )
try :
    PolyaxonClient ( ) . build_job . bookmark ( user , project_name , _build )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not bookmark build job `{}`.' . format ( _build ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Build job bookmarked." )


signature:
def resources ( ctx , gpu ) :
    """Get build job resources .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon build - b 2 resources
 For GPU resources
 ` ` ` bash
 $ polyaxon build - b 2 resources - - gpu"""

implementation:
user , project_name , _build = get_build_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'build' ) )
try :
    message_handler = Printer . gpu_resources if gpu else Printer . resources
    PolyaxonClient ( ) . build_job . resources ( user , project_name , _build , message_handler = message_handler )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get resources for build job `{}`.' . format ( _build ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )


signature:
def init ( project , polyaxonfile ) :
    """Initialize a new polyaxonfile specification ."""

implementation:
user , project_name = get_project_or_local ( project )
try :
    project_config = PolyaxonClient ( ) . project . get_project ( user , project_name )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Make sure you have a project with this name `{}`' . format ( project ) )
    Printer . print_error ( 'You can a create new project with this command: ' 'polyaxon project create ' '--name={} [--description=...] [--tags=...]' . format ( project_name ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
init_project = False
if ProjectManager . is_initialized ( ) :
    local_project = ProjectManager . get_config ( )
    click . echo ( 'Warning! This project is already initialized with the following project:' )
    with clint . textui . indent ( 4 ) :
        clint . textui . puts ( 'User: {}' . format ( local_project . user ) )
        clint . textui . puts ( 'Project: {}' . format ( local_project . name ) )
    if click . confirm ( 'Would you like to override this current config?' , default = False ) :
        init_project = True
else :
    init_project = True
if init_project :
    ProjectManager . purge ( )
    ProjectManager . set_config ( project_config , init = True )
    Printer . print_success ( 'Project was initialized' )
else :
    Printer . print_header ( 'Project config was not changed.' )
init_ignore = False
if IgnoreManager . is_initialized ( ) :
    click . echo ( 'Warning! Found a .polyaxonignore file.' )
    if click . confirm ( 'Would you like to override it?' , default = False ) :
        init_ignore = True
else :
    init_ignore = True
if init_ignore :
    IgnoreManager . init_config ( )
    Printer . print_success ( 'New .polyaxonignore file was created.' )
else :
    Printer . print_header ( '.polyaxonignore file was not changed.' )
if polyaxonfile :
    create_polyaxonfile ( )


signature:
def run ( ctx , project , file , name , tags , description , ttl , u , l ) : # pylint : disable = redefined - builtin
    """Run polyaxonfile specification .
 Examples :
 ` ` ` bash
 $ polyaxon run - f file - f file _ override . . .
 Upload before running
 ` ` ` bash
 $ polyaxon run - f file - u
 Run and set description and tags for this run
 ` ` ` bash
 $ polyaxon run - f file - u - - description = " Description of the current run " - - tags = " foo , bar , moo "
 Run and set a unique name for this run
 ` ` ` bash
 polyaxon run - - name = foo
 Run for a specific project
 ` ` ` bash
 $ polyaxon run - p project1 - f file . yaml"""

implementation:
if not file :
    file = PolyaxonFile . check_default_path ( path = '.' )
if not file :
    file = ''
specification = check_polyaxonfile ( file , log = False ) . specification
spec_cond = ( specification . is_experiment or specification . is_group or specification . is_job or specification . is_build )
if not spec_cond :
    Printer . print_error ( 'This command expects an experiment, a group, a job, or a build specification,' 'received instead a `{}` specification' . format ( specification . kind ) )
    if specification . is_notebook :
        click . echo ( 'Please check "polyaxon notebook --help" to start a notebook.' )
    elif specification . is_tensorboard :
        click . echo ( 'Please check: "polyaxon tensorboard --help" to start a tensorboard.' )
    sys . exit ( 1 )
# Check if we need to upload
if u :
    if project :
        Printer . print_error ( 'Uploading is not supported when switching project context!' )
        click . echo ( 'Please, either omit the `-u` option or `-p` / `--project=` option.' )
        sys . exit ( 1 )
    ctx . invoke ( upload , sync = False )
user , project_name = get_project_or_local ( project )
project_client = PolyaxonClient ( ) . project
tags = validate_tags ( tags )
def run_experiment ( ) :
    click . echo ( 'Creating an independent experiment.' )
    experiment = ExperimentConfig ( name = name , description = description , tags = tags , config = specification . parsed_data , ttl = ttl )
    try :
        response = PolyaxonClient ( ) . project . create_experiment ( user , project_name , experiment )
        cache . cache ( config_manager = ExperimentManager , response = response )
        Printer . print_success ( 'Experiment `{}` was created' . format ( response . id ) )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not create experiment.' )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
def run_group ( ) :
    click . echo ( 'Creating an experiment group with the following definition:' )
    experiments_def = specification . experiments_def
    get_group_experiments_info ( ** experiments_def )
    experiment_group = ExperimentGroupConfig ( name = name , description = description , tags = tags , content = specification . _data )
    # pylint : disable = protected - access
    try :
        response = project_client . create_experiment_group ( user , project_name , experiment_group )
        cache . cache ( config_manager = GroupManager , response = response )
        Printer . print_success ( 'Experiment group {} was created' . format ( response . id ) )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not create experiment group.' )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
def run_job ( ) :
    click . echo ( 'Creating a job.' )
    job = JobConfig ( name = name , description = description , tags = tags , config = specification . parsed_data , ttl = ttl )
    try :
        response = project_client . create_job ( user , project_name , job )
        cache . cache ( config_manager = JobManager , response = response )
        Printer . print_success ( 'Job {} was created' . format ( response . id ) )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not create job.' )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
def run_build ( ) :
    click . echo ( 'Creating a build.' )
    job = JobConfig ( name = name , description = description , tags = tags , config = specification . parsed_data , ttl = ttl )
    try :
        response = project_client . create_build ( user , project_name , job )
        cache . cache ( config_manager = BuildJobManager , response = response )
        Printer . print_success ( 'Build {} was created' . format ( response . id ) )
    except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
        Printer . print_error ( 'Could not create build.' )
        Printer . print_error ( 'Error message `{}`.' . format ( e ) )
        sys . exit ( 1 )
logs = None
if specification . is_experiment :
    run_experiment ( )
    logs = experiment_logs
elif specification . is_group :
    run_group ( )
elif specification . is_job :
    run_job ( )
    logs = job_logs
elif specification . is_build :
    run_build ( )
    logs = build_logs
# Check if we need to invoke logs
if l and logs :
    ctx . obj = { 'project' : '{}/{}' . format ( user , project_name ) }
    ctx . invoke ( logs )


signature:
def bookmark ( ctx , username ) : # pylint : disable = redefined - outer - name
    """Commands for bookmarks ."""

implementation:
ctx . obj = ctx . obj or { }
ctx . obj [ 'username' ] = username


signature:
def projects ( ctx , page ) :
    """List bookmarked projects for user .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon bookmark projects
 ` ` ` bash
 $ polyaxon bookmark - u adam projects"""

implementation:
user = get_username_or_local ( ctx . obj . get ( 'username' ) )
page = page or 1
try :
    response = PolyaxonClient ( ) . bookmark . projects ( username = user , page = page )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get bookmarked projects for user `{}`.' . format ( user ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
meta = get_meta_response ( response )
if meta :
    Printer . print_header ( 'Bookmarked projects for user `{}`.' . format ( user ) )
    Printer . print_header ( 'Navigation:' )
    dict_tabulate ( meta )
else :
    Printer . print_header ( 'No bookmarked projects found for user `{}`.' . format ( user ) )
objects = [ Printer . add_status_color ( o . to_light_dict ( humanize_values = True ) ) for o in response [ 'results' ] ]
objects = list_dicts_to_tabulate ( objects )
if objects :
    Printer . print_header ( "Projects:" )
    dict_tabulate ( objects , is_list_dict = True )


signature:
def _remove_trailing_spaces ( line ) :
    """Remove trailing spaces unless they are quoted with a backslash ."""

implementation:
while line . endswith ( ' ' ) and not line . endswith ( '\\ ' ) :
    line = line [ : - 1 ]
return line . replace ( '\\ ' , ' ' )


signature:
def find_matching ( cls , path , patterns ) :
    """Yield all matching patterns for path ."""

implementation:
for pattern in patterns :
    if pattern . match ( path ) :
        yield pattern


signature:
def is_ignored ( cls , path , patterns ) :
    """Check whether a path is ignored . For directories , include a trailing slash ."""

implementation:
status = None
for pattern in cls . find_matching ( path , patterns ) :
    status = pattern . is_exclude
return status


signature:
def _matches_patterns ( path , patterns ) :
    """Given a list of patterns , returns a if a path matches any pattern ."""

implementation:
for glob in patterns :
    try :
        if PurePath ( path ) . match ( glob ) :
            return True
    except TypeError :
        pass
return False


signature:
def _ignore_path ( cls , path , ignore_list = None , white_list = None ) :
    """Returns a whether a path should be ignored or not ."""

implementation:
ignore_list = ignore_list or [ ]
white_list = white_list or [ ]
return ( cls . _matches_patterns ( path , ignore_list ) and not cls . _matches_patterns ( path , white_list ) )


signature:
def group ( ctx , project , group ) : # pylint : disable = redefined - outer - name
    """Commands for experiment groups ."""

implementation:
ctx . obj = ctx . obj or { }
ctx . obj [ 'project' ] = project
ctx . obj [ 'group' ] = group


signature:
def get ( ctx ) :
    """Get experiment group by uuid .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon group - g 13 get"""

implementation:
user , project_name , _group = get_project_group_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'group' ) )
try :
    response = PolyaxonClient ( ) . experiment_group . get_experiment_group ( user , project_name , _group )
    cache . cache ( config_manager = GroupManager , response = response )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not get experiment group `{}`.' . format ( _group ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
get_group_details ( response )


signature:
def delete ( ctx ) :
    """Delete experiment group .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )"""

implementation:
user , project_name , _group = get_project_group_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'group' ) )
if not click . confirm ( "Are sure you want to delete experiment group `{}`" . format ( _group ) ) :
    click . echo ( 'Existing without deleting experiment group.' )
    sys . exit ( 0 )
try :
    response = PolyaxonClient ( ) . experiment_group . delete_experiment_group ( user , project_name , _group )
    # Purge caching
    GroupManager . purge ( )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not delete experiment group `{}`.' . format ( _group ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
if response . status_code == 204 :
    Printer . print_success ( "Experiment group `{}` was delete successfully" . format ( _group ) )


signature:
def update ( ctx , name , description , tags ) :
    """Update experiment group .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Example :
 ` ` ` bash
 $ polyaxon group - g 2 update - - description = " new description for this group "
 ` ` ` bash
 $ polyaxon update - - tags = " foo , bar " """

implementation:
user , project_name , _group = get_project_group_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'group' ) )
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 group.' )
    sys . exit ( 0 )
try :
    response = PolyaxonClient ( ) . experiment_group . update_experiment_group ( user , project_name , _group , update_dict )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not update experiment group `{}`.' . format ( _group ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Experiment group updated." )
get_group_details ( response )


signature:
def stop ( ctx , yes , pending ) :
    """Stop experiments in the group .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples : stop only pending experiments
 ` ` ` bash
 $ polyaxon group stop - - pending
 Examples : stop all unfinished
 ` ` ` bash
 $ polyaxon group stop
 ` ` ` bash
 $ polyaxon group - g 2 stop"""

implementation:
user , project_name , _group = get_project_group_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'group' ) )
if not yes and not click . confirm ( "Are sure you want to stop experiments " "in group `{}`" . format ( _group ) ) :
    click . echo ( 'Existing without stopping experiments in group.' )
    sys . exit ( 0 )
try :
    PolyaxonClient ( ) . experiment_group . stop ( user , project_name , _group , pending = pending )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not stop experiments in group `{}`.' . format ( _group ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Experiments in group are being stopped." )


signature:
def bookmark ( ctx ) :
    """Bookmark group .
 Uses [ Caching ] ( / references / polyaxon - cli / # caching )
 Examples :
 ` ` ` bash
 $ polyaxon group bookmark
 ` ` ` bash
 $ polyaxon group - g 2 bookmark"""

implementation:
user , project_name , _group = get_project_group_or_local ( ctx . obj . get ( 'project' ) , ctx . obj . get ( 'group' ) )
try :
    PolyaxonClient ( ) . experiment_group . bookmark ( user , project_name , _group )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not bookmark group `{}`.' . format ( _group ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "Experiments group is bookmarked." )


signature:
def config ( list ) : # pylint : disable = redefined - builtin
    """Set and get the global configurations ."""

implementation:
if list :
    _config = GlobalConfigManager . get_config_or_default ( )
    Printer . print_header ( 'Current config:' )
    dict_tabulate ( _config . to_dict ( ) )


signature:
def get ( keys ) :
    """Get the global config values by keys .
 Example :
 ` ` ` bash
 $ polyaxon config get host http _ port"""

implementation:
_config = GlobalConfigManager . get_config_or_default ( )
if not keys :
    return
print_values = { }
for key in keys :
    if hasattr ( _config , key ) :
        print_values [ key ] = getattr ( _config , key )
    else :
        click . echo ( 'Key `{}` is not recognised.' . format ( key ) )
dict_tabulate ( print_values , )


signature:
def set ( verbose , # pylint : disable = redefined - builtin
host , http_port , ws_port , use_https , verify_ssl ) :
    """Set the global config values .
 Example :
 ` ` ` bash
 $ polyaxon config set - - hots = localhost http _ port = 80"""

implementation:
_config = GlobalConfigManager . get_config_or_default ( )
if verbose is not None :
    _config . verbose = verbose
if host is not None :
    _config . host = host
if http_port is not None :
    _config . http_port = http_port
if ws_port is not None :
    _config . ws_port = ws_port
if use_https is not None :
    _config . use_https = use_https
if verify_ssl is False :
    _config . verify_ssl = verify_ssl
GlobalConfigManager . set_config ( _config )
Printer . print_success ( 'Config was updated.' )
# Reset cli config
CliConfigManager . purge ( )


signature:
def activate ( username ) :
    """Activate a user .
 Example :
 ` ` ` bash
 $ polyaxon user activate david"""

implementation:
try :
    PolyaxonClient ( ) . user . activate_user ( username )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not activate user `{}`.' . format ( username ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "User `{}` was activated successfully." . format ( username ) )


signature:
def delete ( username ) :
    """Delete a user .
 Example :
 ` ` ` bash
 $ polyaxon user delete david"""

implementation:
try :
    PolyaxonClient ( ) . user . delete_user ( username )
except ( PolyaxonHTTPError , PolyaxonShouldExitError , PolyaxonClientException ) as e :
    Printer . print_error ( 'Could not delete user `{}`.' . format ( username ) )
    Printer . print_error ( 'Error message `{}`.' . format ( e ) )
    sys . exit ( 1 )
Printer . print_success ( "User `{}` was deleted successfully." . format ( username ) )


signature:
def deploy ( file , manager_path , check , dry_run ) : # pylint : disable = redefined - builtin
    """Deploy polyaxon ."""

implementation:
config = read_deployment_config ( file )
manager = DeployManager ( config = config , filepath = file , manager_path = manager_path , dry_run = dry_run )
exception = None
if check :
    manager . check ( )
    Printer . print_success ( 'Polyaxon deployment file is valid.' )
else :
    try :
        manager . install ( )
    except Exception as e :
        Printer . print_error ( 'Polyaxon could not be installed.' )
        exception = e
if exception :
    Printer . print_error ( 'Error message `{}`.' . format ( exception ) )


signature:
def teardown ( file ) : # pylint : disable = redefined - builtin
    """Teardown a polyaxon deployment given a config file ."""

implementation:
config = read_deployment_config ( file )
manager = DeployManager ( config = config , filepath = file )
exception = None
try :
    if click . confirm ( 'Would you like to execute pre-delete hooks?' , default = True ) :
        manager . teardown ( hooks = True )
    else :
        manager . teardown ( hooks = False )
except Exception as e :
    Printer . print_error ( 'Polyaxon could not teardown the deployment.' )
    exception = e
if exception :
    Printer . print_error ( 'Error message `{}`.' . format ( exception ) )


signature:
def create_tarfile ( files , project_name ) :
    """Create a tar file based on the list of files passed"""

implementation:
fd , filename = tempfile . mkstemp ( prefix = "polyaxon_{}" . format ( project_name ) , suffix = '.tar.gz' )
with tarfile . open ( filename , "w:gz" ) as tar :
    for f in files :
        tar . add ( f )
yield filename
# clear
os . close ( fd )
os . remove ( filename )