idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
44,300
def brain ( self ) : if self . _brain is None : logger . debug ( "SuperModel::brain: *Fetch catalog brain*" ) self . _brain = self . get_brain_by_uid ( self . uid ) return self . _brain
Catalog brain of the wrapped object
44,301
def catalog ( self ) : if self . _catalog is None : logger . debug ( "SuperModel::catalog: *Fetch catalog*" ) self . _catalog = self . get_catalog_for ( self . brain ) return self . _catalog
Primary registered catalog for the wrapped portal type
44,302
def get_catalog_for ( self , brain_or_object ) : if not api . is_object ( brain_or_object ) : raise TypeError ( "Invalid object type %r" % brain_or_object ) catalogs = api . get_catalogs_for ( brain_or_object , default = "uid_catalog" ) return catalogs [ 0 ]
Return the primary catalog for the given brain or object
44,303
def get_brain_by_uid ( self , uid ) : if uid == "0" : return api . get_portal ( ) if self . _catalog is None : uid_catalog = api . get_tool ( "uid_catalog" ) results = uid_catalog ( { "UID" : uid } ) if len ( results ) != 1 : raise ValueError ( "No object found for UID '{}'" . format ( uid ) ) brain = results [ 0 ] self . _catalog = self . get_catalog_for ( brain ) results = self . catalog ( { "UID" : uid } ) if not results : raise ValueError ( "No results found for UID '{}'" . format ( uid ) ) if len ( results ) != 1 : raise ValueError ( "Found more than one object for UID '{}'" . format ( uid ) ) return results [ 0 ]
Lookup brain from the right catalog
44,304
def to_super_model ( self , thing ) : if api . is_uid ( thing ) : return SuperModel ( thing ) if not api . is_object ( thing ) : raise TypeError ( "Expected a portal object, got '{}'" . format ( type ( thing ) ) ) return thing
Wraps an object into a Super Model
44,305
def stringify ( self , value ) : if ISuperModel . providedBy ( value ) : return str ( value ) elif isinstance ( value , ( DateTime ) ) : return value . ISO8601 ( ) elif safe_hasattr ( value , "filename" ) : return value . filename elif isinstance ( value , dict ) : return { k : self . stringify ( v ) for k , v in value . iteritems ( ) } if isinstance ( value , ( list , tuple , LazyMap ) ) : return map ( self . stringify , value ) elif safe_callable ( value ) : return self . stringify ( value ( ) ) elif isinstance ( value , unicode ) : value = value . encode ( "utf8" ) try : return str ( value ) except ( AttributeError , TypeError , ValueError ) : logger . warn ( "Could not convert {} to string" . format ( repr ( value ) ) ) return None
Convert value to string
44,306
def to_dict ( self , converter = None ) : if converter is None : converter = self . stringify out = dict ( ) for k , v in self . iteritems ( ) : out [ k ] = converter ( v ) return out
Returns a copy dict of the current object
44,307
def get_parser ( self , prog_name ) : parser = argparse . ArgumentParser ( description = self . get_description ( ) , prog = prog_name , add_help = False ) return parser
Override to add command options .
44,308
def validate_pluginid ( value ) : valid = string . ascii_letters + string . digits + '.' return all ( c in valid for c in value )
Returns True if the provided value is a valid pluglin id
44,309
def get_valid_value ( prompt , validator , default = None ) : ans = get_value ( prompt , default ) while not validator ( ans ) : try : print validator . error_message except AttributeError : print 'Invalid value.' ans = get_value ( prompt , default ) return ans
Displays the provided prompt and gets input from the user . This behavior loops indefinitely until the provided validator returns True for the user input . If a default value is provided it will be used only if the user hits Enter and does not provide a value .
44,310
def get_value ( prompt , default = None , hidden = False ) : _prompt = '%s : ' % prompt if default : _prompt = '%s [%s]: ' % ( prompt , default ) if hidden : ans = getpass ( _prompt ) else : ans = raw_input ( _prompt ) if not ans and default : ans = default return ans
Displays the provided prompt and returns the input from the user . If the user hits Enter and there is a default value provided the default is returned .
44,311
def create_new_project ( ) : readline . parse_and_bind ( 'tab: complete' ) print print 'I\'m going to ask you a few questions to get this project' ' started.' opts = { } opts [ 'plugin_name' ] = get_valid_value ( 'What is your plugin name?' , validate_nonblank ) opts [ 'plugin_id' ] = get_valid_value ( 'Enter your plugin id.' , validate_pluginid , 'plugin.video.%s' % ( opts [ 'plugin_name' ] . lower ( ) . replace ( ' ' , '' ) ) ) opts [ 'parent_dir' ] = get_valid_value ( 'Enter parent folder (where to create project)' , validate_isfolder , getcwd ( ) ) opts [ 'plugin_dir' ] = os . path . join ( opts [ 'parent_dir' ] , opts [ 'plugin_id' ] ) assert not os . path . isdir ( opts [ 'plugin_dir' ] ) , 'A folder named %s already exists in %s.' % ( opts [ 'plugin_id' ] , opts [ 'parent_dir' ] ) opts [ 'provider_name' ] = get_valid_value ( 'Enter provider name' , validate_nonblank , ) copytree ( SKEL , opts [ 'plugin_dir' ] , ignore = ignore_patterns ( '*.pyc' ) ) for root , dirs , files in os . walk ( opts [ 'plugin_dir' ] ) : for filename in files : update_file ( os . path . join ( root , filename ) , opts ) print 'Projects successfully created in %s.' % opts [ 'plugin_dir' ] print 'Done.'
Creates a new XBMC Addon directory based on user input
44,312
def get_objects ( self , subject = None , predicate = None ) : for triple in self . triples : if ( ( subject and triple [ 'subject' ] != subject ) or ( predicate and triple [ 'predicate' ] != predicate ) ) : continue yield triple [ 'object' ]
Returns a generator of objects that correspond to the specified subjects and predicates .
44,313
def get_triples ( self , subject = None , predicate = None , object_ = None ) : for triple in self . triples : if subject is not None and triple [ 'subject' ] != subject : continue if predicate is not None and triple [ 'predicate' ] != predicate : continue if object_ is not None and triple [ 'object' ] != object_ : continue yield triple
Returns triples that correspond to the specified subject predicates and objects .
44,314
def get_applicable_overlays ( self , error_bundle ) : content_paths = self . get_triples ( subject = 'content' ) if not content_paths : return set ( ) chrome_path = '' content_root_path = '/' for path in content_paths : chrome_name = path [ 'predicate' ] if not path [ 'object' ] : continue path_location = path [ 'object' ] . strip ( ) . split ( ) [ 0 ] if path_location . startswith ( 'jar:' ) : if not error_bundle . is_nested_package : continue split_jar_url = path_location [ 4 : ] . split ( '!' , 2 ) if len ( split_jar_url ) != 2 : continue jar_path , package_path = split_jar_url if jar_path != error_bundle . package_stack [ 0 ] : continue chrome_path = self . _url_chunk_join ( chrome_name , package_path ) break else : if error_bundle . is_nested_package : continue chrome_path = self . _url_chunk_join ( chrome_name , 'content' ) content_root_path = '/%s/' % path_location . strip ( '/' ) break if not chrome_path : return set ( ) applicable_overlays = set ( ) chrome_path = 'chrome://%s' % self . _url_chunk_join ( chrome_path + '/' ) for overlay in self . get_triples ( subject = 'overlay' ) : if not overlay [ 'object' ] : error_bundle . error ( err_id = ( 'chromemanifest' , 'get_applicable_overalys' , 'object' ) , error = 'Overlay instruction missing a property.' , description = 'When overlays are registered in a chrome ' 'manifest file, they require a namespace and ' 'a chrome URL at minimum.' , filename = overlay [ 'filename' ] , line = overlay [ 'line' ] , context = self . context ) continue overlay_url = overlay [ 'object' ] . split ( ) [ 0 ] if overlay_url . startswith ( chrome_path ) : overlay_relative_path = overlay_url [ len ( chrome_path ) : ] applicable_overlays . add ( '/%s' % self . _url_chunk_join ( content_root_path , overlay_relative_path ) ) return applicable_overlays
Given an error bundle a list of overlays that are present in the current package or subpackage are returned .
44,315
def reverse_lookup ( self , state , path ) : if not path . startswith ( '/' ) : path = '/%s' % path if not isinstance ( state , list ) : state = state . package_stack content_paths = self . get_triples ( subject = 'content' ) for content_path in content_paths : chrome_name = content_path [ 'predicate' ] if not content_path [ 'object' ] : continue path_location = content_path [ 'object' ] . split ( ) [ 0 ] if path_location . startswith ( 'jar:' ) : if not state : continue split_jar_url = path_location [ 4 : ] . split ( '!' , 2 ) if len ( split_jar_url ) != 2 : continue jar_path , package_path = split_jar_url if jar_path != state [ 0 ] : continue return 'chrome://%s' % self . _url_chunk_join ( chrome_name , package_path , path ) else : if state : continue path_location = '/%s/' % path_location . strip ( '/' ) rel_path = os . path . relpath ( path , path_location ) if rel_path . startswith ( '../' ) or rel_path == '..' : continue return 'chrome://%s' % self . _url_chunk_join ( chrome_name , rel_path ) return None
Returns a chrome URL for a given path given the current package depth in an error bundle .
44,316
def _url_chunk_join ( self , * args ) : pathlets = map ( lambda s : s . strip ( '/' ) , args ) pathlets = filter ( None , pathlets ) url = '/' . join ( pathlets ) if args [ - 1 ] . endswith ( '/' ) : url = '%s/' % url return url
Join the arguments together to form a predictable URL chunk .
44,317
def uri ( self , element , namespace = None ) : 'Returns a URIRef object for use with the RDF document.' if namespace is None : namespace = self . namespace return URIRef ( '%s#%s' % ( namespace , element ) )
Returns a URIRef object for use with the RDF document .
44,318
def get_root_subject ( self ) : 'Returns the BNode which describes the topmost subject of the graph.' manifest = URIRef ( self . manifest ) if list ( self . rdf . triples ( ( manifest , None , None ) ) ) : return manifest else : return self . rdf . subjects ( None , self . manifest ) . next ( )
Returns the BNode which describes the topmost subject of the graph .
44,319
def get_objects ( self , subject = None , predicate = None ) : results = self . rdf . objects ( subject , predicate ) return list ( results )
Same as get_object except returns a list of objects which satisfy the query rather than a single result .
44,320
def add_context_menu_items ( self , items , replace_items = False ) : for label , action in items : assert isinstance ( label , basestring ) assert isinstance ( action , basestring ) if replace_items : self . _context_menu_items = [ ] self . _context_menu_items . extend ( items ) self . _listitem . addContextMenuItems ( items , replace_items )
Adds context menu items . If replace_items is True all previous context menu items will be removed .
44,321
def set_icon ( self , icon ) : self . _icon = icon return self . _listitem . setIconImage ( icon )
Sets the listitem s icon image
44,322
def set_thumbnail ( self , thumbnail ) : self . _thumbnail = thumbnail return self . _listitem . setThumbnailImage ( thumbnail )
Sets the listitem s thumbnail image
44,323
def set_path ( self , path ) : self . _path = path return self . _listitem . setPath ( path )
Sets the listitem s path
44,324
def set_is_playable ( self , is_playable ) : value = 'false' if is_playable : value = 'true' self . set_property ( 'isPlayable' , value ) self . is_folder = not is_playable
Sets the listitem s playable flag
44,325
def get_storage ( self , name = 'main' , file_format = 'pickle' , TTL = None ) : if not hasattr ( self , '_unsynced_storages' ) : self . _unsynced_storages = { } filename = os . path . join ( self . storage_path , name ) try : storage = self . _unsynced_storages [ filename ] log . debug ( 'Loaded storage "%s" from memory' , name ) except KeyError : if TTL : TTL = timedelta ( minutes = TTL ) try : storage = TimedStorage ( filename , file_format , TTL ) except ValueError : choices = [ 'Clear storage' , 'Cancel' ] ret = xbmcgui . Dialog ( ) . select ( 'A storage file is corrupted. It' ' is recommended to clear it.' , choices ) if ret == 0 : os . remove ( filename ) storage = TimedStorage ( filename , file_format , TTL ) else : raise Exception ( 'Corrupted storage file at %s' % filename ) self . _unsynced_storages [ filename ] = storage log . debug ( 'Loaded storage "%s" from disk' , name ) return storage
Returns a storage for the given name . The returned storage is a fully functioning python dictionary and is designed to be used that way . It is usually not necessary for the caller to load or save the storage manually . If the storage does not already exist it will be created .
44,326
def get_string ( self , stringid ) : stringid = int ( stringid ) if not hasattr ( self , '_strings' ) : self . _strings = { } if not stringid in self . _strings : self . _strings [ stringid ] = self . addon . getLocalizedString ( stringid ) return self . _strings [ stringid ]
Returns the localized string from strings . xml for the given stringid .
44,327
def get_view_mode_id ( self , view_mode ) : view_mode_ids = VIEW_MODES . get ( view_mode . lower ( ) ) if view_mode_ids : return view_mode_ids . get ( xbmc . getSkinDir ( ) ) return None
Attempts to return a view_mode_id for a given view_mode taking into account the current skin . If not view_mode_id can be found None is returned . thumbnail is currently the only suppported view_mode .
44,328
def keyboard ( self , default = None , heading = None , hidden = False ) : if heading is None : heading = self . addon . getAddonInfo ( 'name' ) if default is None : default = '' keyboard = xbmc . Keyboard ( default , heading , hidden ) keyboard . doModal ( ) if keyboard . isConfirmed ( ) : return keyboard . getText ( )
Displays the keyboard input window to the user . If the user does not cancel the modal the value entered by the user will be returned .
44,329
def notify ( self , msg = '' , title = None , delay = 5000 , image = '' ) : if not msg : log . warning ( 'Empty message for notification dialog' ) if title is None : title = self . addon . getAddonInfo ( 'name' ) xbmc . executebuiltin ( 'XBMC.Notification("%s", "%s", "%s", "%s")' % ( msg , title , delay , image ) )
Displays a temporary notification message to the user . If title is not provided the plugin name will be used . To have a blank title pass for the title argument . The delay argument is in milliseconds .
44,330
def _listitemify ( self , item ) : info_type = self . info_type if hasattr ( self , 'info_type' ) else 'video' if not hasattr ( item , 'as_tuple' ) : if 'info_type' not in item . keys ( ) : item [ 'info_type' ] = info_type item = xbmcswift2 . ListItem . from_dict ( ** item ) return item
Creates an xbmcswift2 . ListItem if the provided value for item is a dict . If item is already a valid xbmcswift2 . ListItem the item is returned unmodified .
44,331
def _add_subtitles ( self , subtitles ) : player = xbmc . Player ( ) for _ in xrange ( 30 ) : if player . isPlaying ( ) : break time . sleep ( 1 ) else : raise Exception ( 'No video playing. Aborted after 30 seconds.' ) player . setSubtitles ( subtitles )
Adds subtitles to playing video .
44,332
def set_resolved_url ( self , item = None , subtitles = None ) : if self . _end_of_directory : raise Exception ( 'Current XBMC handle has been removed. Either ' 'set_resolved_url(), end_of_directory(), or ' 'finish() has already been called.' ) self . _end_of_directory = True succeeded = True if item is None : item = { } succeeded = False if isinstance ( item , basestring ) : item = { 'path' : item } item = self . _listitemify ( item ) item . set_played ( True ) xbmcplugin . setResolvedUrl ( self . handle , succeeded , item . as_xbmc_listitem ( ) ) if subtitles : self . _add_subtitles ( subtitles ) return [ item ]
Takes a url or a listitem to be played . Used in conjunction with a playable list item with a path that calls back into your addon .
44,333
def add_items ( self , items ) : _items = [ self . _listitemify ( item ) for item in items ] tuples = [ item . as_tuple ( ) for item in _items ] xbmcplugin . addDirectoryItems ( self . handle , tuples , len ( tuples ) ) self . added_items . extend ( _items ) return _items
Adds ListItems to the XBMC interface . Each item in the provided list should either be instances of xbmcswift2 . ListItem or regular dictionaries that will be passed to xbmcswift2 . ListItem . from_dict . Returns the list of ListItems .
44,334
def end_of_directory ( self , succeeded = True , update_listing = False , cache_to_disc = True ) : self . _update_listing = update_listing if not self . _end_of_directory : self . _end_of_directory = True return xbmcplugin . endOfDirectory ( self . handle , succeeded , update_listing , cache_to_disc ) assert False , 'Already called endOfDirectory.'
Wrapper for xbmcplugin . endOfDirectory . Records state in self . _end_of_directory .
44,335
def finish ( self , items = None , sort_methods = None , succeeded = True , update_listing = False , cache_to_disc = True , view_mode = None ) : if items : self . add_items ( items ) if sort_methods : for sort_method in sort_methods : if not isinstance ( sort_method , basestring ) and hasattr ( sort_method , '__len__' ) : self . add_sort_method ( * sort_method ) else : self . add_sort_method ( sort_method ) if view_mode is not None : try : view_mode_id = int ( view_mode ) except ValueError : view_mode_id = self . get_view_mode_id ( view_mode ) if view_mode_id is not None : self . set_view_mode ( view_mode_id ) self . end_of_directory ( succeeded , update_listing , cache_to_disc ) return self . added_items
Adds the provided items to the XBMC interface .
44,336
def match ( self , path ) : m = self . _regex . search ( path ) if not m : raise NotFoundException items = dict ( ( key , unquote_plus ( val ) ) for key , val in m . groupdict ( ) . items ( ) ) items = unpickle_dict ( items ) [ items . setdefault ( key , val ) for key , val in self . _options . items ( ) ] return self . _view_func , items
Attempts to match a url to the given path . If successful a tuple is returned . The first item is the matchd function and the second item is a dictionary containing items to be passed to the function parsed from the provided path .
44,337
def _make_path ( self , items ) : for key , val in items . items ( ) : if not isinstance ( val , basestring ) : raise TypeError , ( 'Value "%s" for key "%s" must be an instance' ' of basestring' % ( val , key ) ) items [ key ] = quote_plus ( val ) try : path = self . _url_format . format ( ** items ) except AttributeError : path = self . _url_format for key , val in items . items ( ) : path = path . replace ( '{%s}' % key , val ) return path
Returns a relative path for the given dictionary of items .
44,338
def make_path_qs ( self , items ) : for key , val in items . items ( ) : if isinstance ( val , ( int , long ) ) : items [ key ] = str ( val ) url_items = dict ( ( key , val ) for key , val in self . _options . items ( ) if key in self . _keywords ) url_items . update ( ( key , val ) for key , val in items . items ( ) if key in self . _keywords ) path = self . _make_path ( url_items ) qs_items = dict ( ( key , val ) for key , val in items . items ( ) if key not in self . _keywords ) qs = self . _make_qs ( qs_items ) if qs : return '?' . join ( [ path , qs ] ) return path
Returns a relative path complete with query string for the given dictionary of items .
44,339
def sync ( self ) : if self . flag == 'r' : return filename = self . filename tempname = filename + '.tmp' fileobj = open ( tempname , 'wb' if self . file_format == 'pickle' else 'w' ) try : self . dump ( fileobj ) except Exception : os . remove ( tempname ) raise finally : fileobj . close ( ) shutil . move ( tempname , self . filename ) if self . mode is not None : os . chmod ( self . filename , self . mode )
Write the dict to disk
44,340
def dump ( self , fileobj ) : if self . file_format == 'csv' : csv . writer ( fileobj ) . writerows ( self . raw_dict ( ) . items ( ) ) elif self . file_format == 'json' : json . dump ( self . raw_dict ( ) , fileobj , separators = ( ',' , ':' ) ) elif self . file_format == 'pickle' : pickle . dump ( dict ( self . raw_dict ( ) ) , fileobj , 2 ) else : raise NotImplementedError ( 'Unknown format: ' + repr ( self . file_format ) )
Handles the writing of the dict to the file object
44,341
def load ( self , fileobj ) : for loader in ( pickle . load , json . load , csv . reader ) : fileobj . seek ( 0 ) try : return self . initial_update ( loader ( fileobj ) ) except Exception as e : pass raise ValueError ( 'File not in a supported format' )
Load the dict from the file object
44,342
def initial_update ( self , mapping ) : for key , val in mapping . items ( ) : _ , timestamp = val if not self . TTL or ( datetime . utcnow ( ) - datetime . utcfromtimestamp ( timestamp ) < self . TTL ) : self . __setitem__ ( key , val , raw = True )
Initially fills the underlying dictionary with keys values and timestamps .
44,343
def setup_log ( name ) : _log = logging . getLogger ( name ) _log . setLevel ( GLOBAL_LOG_LEVEL ) handler = logging . StreamHandler ( ) formatter = logging . Formatter ( '%(asctime)s - %(levelname)s - [%(name)s] %(message)s' ) handler . setFormatter ( formatter ) _log . addHandler ( handler ) _log . addFilter ( XBMCFilter ( '[%s] ' % name ) ) return _log
Returns a logging instance for the provided name . The returned object is an instance of logging . Logger . Logged messages will be printed to stderr when running in the CLI or forwarded to XBMC s log when running in XBMC mode .
44,344
def filter ( self , record ) : if CLI_MODE : return True else : from xbmcswift2 import xbmc xbmc_level = XBMCFilter . xbmc_levels . get ( XBMCFilter . python_to_xbmc . get ( record . levelname ) ) xbmc . log ( '%s%s' % ( self . prefix , record . getMessage ( ) ) , xbmc_level ) return False
Returns True for all records if running in the CLI else returns True .
44,345
def validate_name ( err , value , source ) : 'Tests a manifest name value for trademarks.' ff_pattern = re . compile ( '(mozilla|firefox)' , re . I ) err . metadata [ 'name' ] = value if ff_pattern . search ( value ) : err . warning ( ( 'metadata_helpers' , '_test_name' , 'trademark' ) , 'Add-on has potentially illegal name.' , 'Add-on names cannot contain the Mozilla or Firefox ' 'trademarks. These names should not be contained in add-on ' 'names if at all possible.' , source )
Tests a manifest name value for trademarks .
44,346
def validate_id ( err , value , source ) : 'Tests a manifest UUID value' field_name = '<em:id>' if source == 'install.rdf' else 'id' id_pattern = re . compile ( '(' '\{[0-9a-f]{8}-([0-9a-f]{4}-){3}[0-9a-f]{12}\}' '|' '[a-z0-9-\.\+_]*\@[a-z0-9-\._]+' ')' , re . I ) err . metadata [ 'id' ] = value if not id_pattern . match ( value ) : err . error ( ( 'metadata_helpers' , '_test_id' , 'invalid' ) , 'The value of {name} is invalid' . format ( name = field_name ) , [ 'The values supplied for {name} in the {source} file is not a ' 'valid UUID string or email address.' . format ( name = field_name , source = source ) , 'For help, please consult: ' 'https://developer.mozilla.org/en/install_manifests#id' ] , source )
Tests a manifest UUID value
44,347
def validate_version ( err , value , source ) : 'Tests a manifest version number' field_name = '<em:version>' if source == 'install.rdf' else 'version' err . metadata [ 'version' ] = value if len ( value ) > 32 : err . error ( ( 'metadata_helpers' , '_test_version' , 'too_long' ) , 'The value of {name} is too long' . format ( name = field_name ) , 'Values supplied for {name} in the {source} file must be 32 ' 'characters or less.' . format ( name = field_name , source = source ) , source ) if not VERSION_PATTERN . match ( value ) : err . error ( ( 'metadata_helpers' , '_test_version' , 'invalid_format' ) , 'The value of {name} is invalid' . format ( name = field_name ) , 'The values supplied for version in the {source} file is not a ' 'valid version string. It can only contain letters, numbers, and ' 'the symbols +*.-_.' . format ( name = field_name , source = source ) , source )
Tests a manifest version number
44,348
def get_status ( self ) : url = self . base_url + '/status' try : r = requests . get ( url , timeout = 10 ) return r . json ( ) except RequestException as err : raise Client . ClientError ( err )
Query the device status . Returns JSON of the device internal state
44,349
def put_device ( self , pin , state , momentary = None , times = None , pause = None ) : url = self . base_url + '/device' payload = { "pin" : pin , "state" : state } if momentary is not None : payload [ "momentary" ] = momentary if times is not None : payload [ "times" ] = times if pause is not None : payload [ "pause" ] = pause try : r = requests . put ( url , json = payload , timeout = 10 ) return r . json ( ) except RequestException as err : raise Client . ClientError ( err )
Actuate a device pin
44,350
def put_settings ( self , sensors = [ ] , actuators = [ ] , auth_token = None , endpoint = None , blink = None , discovery = None , dht_sensors = [ ] , ds18b20_sensors = [ ] ) : url = self . base_url + '/settings' payload = { "sensors" : sensors , "actuators" : actuators , "dht_sensors" : dht_sensors , "ds18b20_sensors" : ds18b20_sensors , "token" : auth_token , "apiUrl" : endpoint } if blink is not None : payload [ 'blink' ] = blink if discovery is not None : payload [ 'discovery' ] = discovery try : r = requests . put ( url , json = payload , timeout = 10 ) return r . ok except RequestException as err : raise Client . ClientError ( err )
Sync settings to the Konnected device
44,351
def parse_mime_type ( mime_type ) : full_type , params = cgi . parse_header ( mime_type ) if full_type == '*' : full_type = '*/*' type_parts = full_type . split ( '/' ) if '/' in full_type else None if not type_parts or len ( type_parts ) > 2 : raise MimeTypeParseException ( "Can't parse type \"{}\"" . format ( full_type ) ) ( type , subtype ) = type_parts return ( type . strip ( ) , subtype . strip ( ) , params )
Parses a mime - type into its component parts .
44,352
def parse_media_range ( range ) : ( type , subtype , params ) = parse_mime_type ( range ) params . setdefault ( 'q' , params . pop ( 'Q' , None ) ) try : if not params [ 'q' ] or not 0 <= float ( params [ 'q' ] ) <= 1 : params [ 'q' ] = '1' except ValueError : params [ 'q' ] = '1' return ( type , subtype , params )
Parse a media - range into its component parts .
44,353
def quality_and_fitness_parsed ( mime_type , parsed_ranges ) : best_fitness = - 1 best_fit_q = 0 ( target_type , target_subtype , target_params ) = parse_media_range ( mime_type ) for ( type , subtype , params ) in parsed_ranges : type_match = ( type in ( target_type , '*' ) or target_type == '*' ) subtype_match = ( subtype in ( target_subtype , '*' ) or target_subtype == '*' ) if type_match and subtype_match : fitness = type == target_type and 100 or 0 fitness += subtype == target_subtype and 10 or 0 param_matches = sum ( [ 1 for ( key , value ) in target_params . items ( ) if key != 'q' and key in params and value == params [ key ] ] ) fitness += param_matches fitness += float ( target_params . get ( 'q' , 1 ) ) if fitness > best_fitness : best_fitness = fitness best_fit_q = params [ 'q' ] return float ( best_fit_q ) , best_fitness
Find the best match for a mime - type amongst parsed media - ranges .
44,354
def from_dict ( cls , d : dict , force_snake_case : bool = True , force_cast : bool = False , restrict : bool = True ) -> T : if isinstance ( d , cls ) : return d instance : T = cls ( ) d = util . replace_keys ( d , { "self" : "_self" } , force_snake_case ) properties = cls . __annotations__ . items ( ) if restrict : assert_extra ( properties , d , cls ) for n , t in properties : f = cls . _methods_dict . get ( f'_{cls.__name__} {n}' ) arg_v = f ( d . get ( n ) ) if f else d . get ( n ) def_v = getattr ( instance , n , None ) setattr ( instance , n , traverse ( type_ = t , name = n , value = def_v if arg_v is None else arg_v , cls = cls , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict ) ) return instance
From dict to instance
44,355
def from_optional_dict ( cls , d : Optional [ dict ] , force_snake_case : bool = True , force_cast : bool = False , restrict : bool = True ) -> TOption [ T ] : return TOption ( cls . from_dict ( d , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict ) if d is not None else None )
From dict to optional instance .
44,356
def from_dicts ( cls , ds : List [ dict ] , force_snake_case : bool = True , force_cast : bool = False , restrict : bool = True ) -> TList [ T ] : return TList ( [ cls . from_dict ( d , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict ) for d in ds ] )
From list of dict to list of instance
44,357
def from_optional_dicts ( cls , ds : Optional [ List [ dict ] ] , force_snake_case : bool = True , force_cast : bool = False , restrict : bool = True ) -> TOption [ TList [ T ] ] : return TOption ( cls . from_dicts ( ds , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict ) if ds is not None else None )
From list of dict to optional list of instance .
44,358
def from_dicts_by_key ( cls , ds : dict , force_snake_case : bool = True , force_cast : bool = False , restrict : bool = True ) -> TDict [ T ] : return TDict ( { k : cls . from_dict ( v , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict ) for k , v in ds . items ( ) } )
From dict of dict to dict of instance
44,359
def from_optional_dicts_by_key ( cls , ds : Optional [ dict ] , force_snake_case = True , force_cast : bool = False , restrict : bool = True ) -> TOption [ TDict [ T ] ] : return TOption ( cls . from_dicts_by_key ( ds , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict ) if ds is not None else None )
From dict of dict to optional dict of instance .
44,360
def from_json ( cls , data : str , force_snake_case = True , force_cast : bool = False , restrict : bool = False ) -> T : return cls . from_dict ( util . load_json ( data ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From json string to instance
44,361
def from_jsonf ( cls , fpath : str , encoding : str = 'utf8' , force_snake_case = True , force_cast : bool = False , restrict : bool = False ) -> T : return cls . from_dict ( util . load_jsonf ( fpath , encoding ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From json file path to instance
44,362
def from_json_to_list ( cls , data : str , force_snake_case = True , force_cast : bool = False , restrict : bool = False ) -> TList [ T ] : return cls . from_dicts ( util . load_json ( data ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From json string to list of instance
44,363
def from_jsonf_to_list ( cls , fpath : str , encoding : str = 'utf8' , force_snake_case = True , force_cast : bool = False , restrict : bool = False ) -> TList [ T ] : return cls . from_dicts ( util . load_jsonf ( fpath , encoding ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From json file path to list of instance
44,364
def from_yaml ( cls , data : str , force_snake_case = True , force_cast : bool = False , restrict : bool = True ) -> T : return cls . from_dict ( util . load_yaml ( data ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From yaml string to instance
44,365
def from_yamlf ( cls , fpath : str , encoding : str = 'utf8' , force_snake_case = True , force_cast : bool = False , restrict : bool = True ) -> T : return cls . from_dict ( util . load_yamlf ( fpath , encoding ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From yaml file path to instance
44,366
def from_yaml_to_list ( cls , data : str , force_snake_case = True , force_cast : bool = False , restrict : bool = True ) -> TList [ T ] : return cls . from_dicts ( util . load_yaml ( data ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From yaml string to list of instance
44,367
def from_yamlf_to_list ( cls , fpath : str , encoding : str = 'utf8' , force_snake_case = True , force_cast : bool = False , restrict : bool = True ) -> TList [ T ] : return cls . from_dicts ( util . load_yamlf ( fpath , encoding ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From yaml file path to list of instance
44,368
def from_csvf ( cls , fpath : str , fieldnames : Optional [ Sequence [ str ] ] = None , encoding : str = 'utf8' , force_snake_case : bool = True , restrict : bool = True ) -> TList [ T ] : return cls . from_dicts ( util . load_csvf ( fpath , fieldnames , encoding ) , force_snake_case = force_snake_case , force_cast = True , restrict = restrict )
From csv file path to list of instance
44,369
def from_json_url ( cls , url : str , force_snake_case = True , force_cast : bool = False , restrict : bool = False ) -> T : return cls . from_dict ( util . load_json_url ( url ) , force_snake_case = force_snake_case , force_cast = force_cast , restrict = restrict )
From url which returns json to instance
44,370
def endSections ( self , level = u'0' ) : iSectionsClosed = self . storeSectionState ( level ) self . document . append ( "</section>\n" * iSectionsClosed )
Closes all sections of level > = sectnum . Defaults to closing all open sections
44,371
def to_json ( self , indent : int = None , ignore_none : bool = True , ignore_empty : bool = False ) -> str : return util . dump_json ( traverse ( self , ignore_none , force_value = True , ignore_empty = ignore_empty ) , indent )
From instance to json string
44,372
def to_jsonf ( self , fpath : str , encoding : str = 'utf8' , indent : int = None , ignore_none : bool = True , ignore_empty : bool = False ) -> str : return util . save_jsonf ( traverse ( self , ignore_none , force_value = True , ignore_empty = ignore_empty ) , fpath , encoding , indent )
From instance to json file
44,373
def to_pretty_json ( self , ignore_none : bool = True , ignore_empty : bool = False ) -> str : return self . to_json ( 4 , ignore_none , ignore_empty )
From instance to pretty json string
44,374
def to_yaml ( self , ignore_none : bool = True , ignore_empty : bool = False ) -> str : return util . dump_yaml ( traverse ( self , ignore_none , force_value = True , ignore_empty = ignore_empty ) )
From instance to yaml string
44,375
def _pre_tidy ( html ) : tree = etree . fromstring ( html , etree . HTMLParser ( ) ) for el in tree . xpath ( '//u' ) : el . tag = 'em' c = el . attrib . get ( 'class' , '' ) . split ( ) if 'underline' not in c : c . append ( 'underline' ) el . attrib [ 'class' ] = ' ' . join ( c ) return tohtml ( tree )
This method transforms a few things before tidy runs . When we get rid of tidy this can go away .
44,376
def _post_tidy ( html ) : tree = etree . fromstring ( html ) ems = tree . xpath ( "//xh:em[@class='underline']|//xh:em[contains(@class, ' underline ')]" , namespaces = { 'xh' : 'http://www.w3.org/1999/xhtml' } ) for el in ems : c = el . attrib . get ( 'class' , '' ) . split ( ) c . remove ( 'underline' ) el . tag = '{http://www.w3.org/1999/xhtml}u' if c : el . attrib [ 'class' ] = ' ' . join ( c ) elif 'class' in el . attrib : del ( el . attrib [ 'class' ] ) return tree
This method transforms post tidy . Will go away when tidy goes away .
44,377
def _transform ( xsl_filename , xml , ** kwargs ) : xslt = _make_xsl ( xsl_filename ) xml = xslt ( xml , ** kwargs ) return xml
Transforms the xml using the specifiec xsl file .
44,378
def _unescape_math ( xml ) : xpath_math_script = etree . XPath ( '//x:script[@type="math/mml"]' , namespaces = { 'x' : 'http://www.w3.org/1999/xhtml' } ) math_script_list = xpath_math_script ( xml ) for mathscript in math_script_list : math = mathscript . text math = unescape ( unescape ( math ) ) mathscript . clear ( ) mathscript . set ( 'type' , 'math/mml' ) new_math = etree . fromstring ( math ) mathscript . append ( new_math ) return xml
Unescapes Math from Mathjax to MathML .
44,379
def cnxml_to_html ( cnxml_source ) : source = _string2io ( cnxml_source ) xml = etree . parse ( source ) xml = _transform ( 'cnxml-to-html5.xsl' , xml , version = '"{}"' . format ( version ) ) xml = XHTML_MODULE_BODY_XPATH ( xml ) return etree . tostring ( xml [ 0 ] )
Transform the CNXML source to HTML
44,380
def aloha_to_etree ( html_source ) : xml = _tidy2xhtml5 ( html_source ) for i , transform in enumerate ( ALOHA2HTML_TRANSFORM_PIPELINE ) : xml = transform ( xml ) return xml
Converts HTML5 from Aloha editor output to a lxml etree .
44,381
def aloha_to_html ( html_source ) : xml = aloha_to_etree ( html_source ) return etree . tostring ( xml , pretty_print = True )
Converts HTML5 from Aloha to a more structured HTML5
44,382
def html_to_cnxml ( html_source , cnxml_source ) : source = _string2io ( html_source ) xml = etree . parse ( source ) cnxml = etree . parse ( _string2io ( cnxml_source ) ) xml = _transform ( 'html5-to-cnxml.xsl' , xml ) namespaces = { 'c' : 'http://cnx.rice.edu/cnxml' } xpath = etree . XPath ( '//c:content' , namespaces = namespaces ) replaceable_node = xpath ( cnxml ) [ 0 ] replaceable_node . getparent ( ) . replace ( replaceable_node , xml . getroot ( ) ) return etree . tostring ( cnxml )
Transform the HTML to CNXML . We need the original CNXML content in order to preserve the metadata in the CNXML document .
44,383
def replace ( text ) : for hex , value in UNICODE_DICTIONARY . items ( ) : num = int ( hex [ 3 : - 1 ] , 16 ) decimal = '&#' + str ( num ) + ';' for key in [ hex , decimal ] : text = text . replace ( key , value ) return text
Replace both the hex and decimal versions of symbols in an XML string
44,384
def writeXMLFile ( filename , content ) : xmlfile = open ( filename , 'w' ) content = etree . tostring ( content , pretty_print = True ) xmlfile . write ( content ) xmlfile . close ( )
Used only for debugging to write out intermediate files
44,385
def auto_thaw ( vault_client , opt ) : icefile = opt . thaw_from if not os . path . exists ( icefile ) : raise aomi . exceptions . IceFile ( "%s missing" % icefile ) thaw ( vault_client , icefile , opt ) return opt
Will thaw into a temporary location
44,386
def seed ( vault_client , opt ) : if opt . thaw_from : opt . secrets = tempfile . mkdtemp ( 'aomi-thaw' ) auto_thaw ( vault_client , opt ) Context . load ( get_secretfile ( opt ) , opt ) . fetch ( vault_client ) . sync ( vault_client , opt ) if opt . thaw_from : rmtree ( opt . secrets )
Will provision vault based on the definition within a Secretfile
44,387
def render ( directory , opt ) : if not os . path . exists ( directory ) and not os . path . isdir ( directory ) : os . mkdir ( directory ) a_secretfile = render_secretfile ( opt ) s_path = "%s/Secretfile" % directory LOG . debug ( "writing Secretfile to %s" , s_path ) open ( s_path , 'w' ) . write ( a_secretfile ) ctx = Context . load ( yaml . safe_load ( a_secretfile ) , opt ) for resource in ctx . resources ( ) : if not resource . present : continue if issubclass ( type ( resource ) , Policy ) : if not os . path . isdir ( "%s/policy" % directory ) : os . mkdir ( "%s/policy" % directory ) filename = "%s/policy/%s" % ( directory , resource . path ) open ( filename , 'w' ) . write ( resource . obj ( ) ) LOG . debug ( "writing %s to %s" , resource , filename ) elif issubclass ( type ( resource ) , AWSRole ) : if not os . path . isdir ( "%s/aws" % directory ) : os . mkdir ( "%s/aws" % directory ) if 'policy' in resource . obj ( ) : filename = "%s/aws/%s" % ( directory , os . path . basename ( resource . path ) ) r_obj = resource . obj ( ) if 'policy' in r_obj : LOG . debug ( "writing %s to %s" , resource , filename ) open ( filename , 'w' ) . write ( r_obj [ 'policy' ] )
Render any provided template . This includes the Secretfile Vault policies and inline AWS roles
44,388
def export ( vault_client , opt ) : ctx = Context . load ( get_secretfile ( opt ) , opt ) . fetch ( vault_client ) for resource in ctx . resources ( ) : resource . export ( opt . directory )
Export contents of a Secretfile from the Vault server into a specified directory .
44,389
def maybe_colored ( msg , color , opt ) : if opt . monochrome : return msg return colored ( msg , color )
Maybe it will render in color maybe it will not!
44,390
def details_dict ( obj , existing , ignore_missing , opt ) : existing = dict_unicodeize ( existing ) obj = dict_unicodeize ( obj ) for ex_k , ex_v in iteritems ( existing ) : new_value = normalize_val ( obj . get ( ex_k ) ) og_value = normalize_val ( ex_v ) if ex_k in obj and og_value != new_value : print ( maybe_colored ( "-- %s: %s" % ( ex_k , og_value ) , 'red' , opt ) ) print ( maybe_colored ( "++ %s: %s" % ( ex_k , new_value ) , 'green' , opt ) ) if ( not ignore_missing ) and ( ex_k not in obj ) : print ( maybe_colored ( "-- %s: %s" % ( ex_k , og_value ) , 'red' , opt ) ) for ob_k , ob_v in iteritems ( obj ) : val = normalize_val ( ob_v ) if ob_k not in existing : print ( maybe_colored ( "++ %s: %s" % ( ob_k , val ) , 'green' , opt ) ) return
Output the changes if any for a dict
44,391
def maybe_details ( resource , opt ) : if opt . verbose == 0 : return if not resource . present : return obj = None existing = None if isinstance ( resource , Resource ) : obj = resource . obj ( ) existing = resource . existing elif isinstance ( resource , VaultBackend ) : obj = resource . config existing = resource . existing if not obj : return if is_unicode ( existing ) and is_unicode ( obj ) : a_diff = difflib . unified_diff ( existing . splitlines ( ) , obj . splitlines ( ) , lineterm = '' ) for line in a_diff : if line . startswith ( '+++' ) or line . startswith ( '---' ) : continue if line [ 0 ] == '+' : print ( maybe_colored ( "++ %s" % line [ 1 : ] , 'green' , opt ) ) elif line [ 0 ] == '-' : print ( maybe_colored ( "-- %s" % line [ 1 : ] , 'red' , opt ) ) else : print ( line ) elif isinstance ( existing , dict ) : ignore_missing = isinstance ( resource , VaultBackend ) details_dict ( obj , existing , ignore_missing , opt )
At the first level of verbosity this will print out detailed change information on for the specified Vault resource
44,392
def diff_a_thing ( thing , opt ) : changed = thing . diff ( ) if changed == ADD : print ( "%s %s" % ( maybe_colored ( "+" , "green" , opt ) , str ( thing ) ) ) elif changed == DEL : print ( "%s %s" % ( maybe_colored ( "-" , "red" , opt ) , str ( thing ) ) ) elif changed == CHANGED : print ( "%s %s" % ( maybe_colored ( "~" , "yellow" , opt ) , str ( thing ) ) ) elif changed == OVERWRITE : print ( "%s %s" % ( maybe_colored ( "+" , "yellow" , opt ) , str ( thing ) ) ) elif changed == CONFLICT : print ( "%s %s" % ( maybe_colored ( "!" , "red" , opt ) , str ( thing ) ) ) if changed != OVERWRITE and changed != NOOP : maybe_details ( thing , opt )
Handle the diff action for a single thing . It may be a Vault backend implementation or it may be a Vault data resource
44,393
def diff ( vault_client , opt ) : if opt . thaw_from : opt . secrets = tempfile . mkdtemp ( 'aomi-thaw' ) auto_thaw ( vault_client , opt ) ctx = Context . load ( get_secretfile ( opt ) , opt ) . fetch ( vault_client ) for backend in ctx . mounts ( ) : diff_a_thing ( backend , opt ) for resource in ctx . resources ( ) : diff_a_thing ( resource , opt ) if opt . thaw_from : rmtree ( opt . secrets )
Derive a comparison between what is represented in the Secretfile and what is actually live on a Vault instance
44,394
def help_me ( parser , opt ) : print ( "aomi v%s" % version ) print ( 'Get started with aomi' ' https://autodesk.github.io/aomi/quickstart' ) if opt . verbose == 2 : tf_str = 'Token File,' if token_file ( ) else '' app_str = 'AppID File,' if appid_file ( ) else '' approle_str = 'Approle File,' if approle_file ( ) else '' tfe_str = 'Token Env,' if 'VAULT_TOKEN' in os . environ else '' appre_str = 'App Role Env,' if 'VAULT_ROLE_ID' in os . environ and 'VAULT_SECRET_ID' in os . environ else '' appe_str = 'AppID Env,' if 'VAULT_USER_ID' in os . environ and 'VAULT_APP_ID' in os . environ else '' LOG . info ( ( "Auth Hints Present : %s%s%s%s%s%s" % ( tf_str , app_str , approle_str , tfe_str , appre_str , appe_str ) ) [ : - 1 ] ) LOG . info ( "Vault Server %s" % os . environ [ 'VAULT_ADDR' ] if 'VAULT_ADDR' in os . environ else '??' ) parser . print_help ( ) sys . exit ( 0 )
Handle display of help and whatever diagnostics
44,395
def extract_file_args ( subparsers ) : extract_parser = subparsers . add_parser ( 'extract_file' , help = 'Extract a single secret from' 'Vault to a local file' ) extract_parser . add_argument ( 'vault_path' , help = 'Full path (including key) to secret' ) extract_parser . add_argument ( 'destination' , help = 'Location of destination file' ) base_args ( extract_parser )
Add the command line options for the extract_file operation
44,396
def mapping_args ( parser ) : parser . add_argument ( '--add-prefix' , dest = 'add_prefix' , help = 'Specify a prefix to use when ' 'generating secret key names' ) parser . add_argument ( '--add-suffix' , dest = 'add_suffix' , help = 'Specify a suffix to use when ' 'generating secret key names' ) parser . add_argument ( '--merge-path' , dest = 'merge_path' , action = 'store_true' , default = True , help = 'merge vault path and key name' ) parser . add_argument ( '--no-merge-path' , dest = 'merge_path' , action = 'store_false' , default = True , help = 'do not merge vault path and key name' ) parser . add_argument ( '--key-map' , dest = 'key_map' , action = 'append' , type = str , default = [ ] )
Add various variable mapping command line options to the parser
44,397
def aws_env_args ( subparsers ) : env_parser = subparsers . add_parser ( 'aws_environment' ) env_parser . add_argument ( 'vault_path' , help = 'Full path(s) to the AWS secret' ) export_arg ( env_parser ) base_args ( env_parser )
Add command line options for the aws_environment operation
44,398
def environment_args ( subparsers ) : env_parser = subparsers . add_parser ( 'environment' ) env_parser . add_argument ( 'vault_paths' , help = 'Full path(s) to secret' , nargs = '+' ) env_parser . add_argument ( '--prefix' , dest = 'prefix' , help = 'Old style prefix to use when' 'generating secret key names' ) export_arg ( env_parser ) mapping_args ( env_parser ) base_args ( env_parser )
Add command line options for the environment operation
44,399
def template_args ( subparsers ) : template_parser = subparsers . add_parser ( 'template' ) template_parser . add_argument ( 'template' , help = 'Template source' , nargs = '?' ) template_parser . add_argument ( 'destination' , help = 'Path to write rendered template' , nargs = '?' ) template_parser . add_argument ( 'vault_paths' , help = 'Full path(s) to secret' , nargs = '*' ) template_parser . add_argument ( '--builtin-list' , dest = 'builtin_list' , help = 'Display a list of builtin templates' , action = 'store_true' , default = False ) template_parser . add_argument ( '--builtin-info' , dest = 'builtin_info' , help = 'Display information on a ' 'particular builtin template' ) vars_args ( template_parser ) mapping_args ( template_parser ) base_args ( template_parser )
Add command line options for the template operation