idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
18,500 | def parse_encoding ( value = None ) : if value is None : return ca_settings . CA_DEFAULT_ENCODING elif isinstance ( value , Encoding ) : return value elif isinstance ( value , six . string_types ) : if value == 'ASN1' : value = 'DER' try : return getattr ( Encoding , value ) except AttributeError : raise ValueError ( 'Unknown encoding: %s' % value ) else : raise ValueError ( 'Unknown type passed: %s' % type ( value ) . __name__ ) | Parse a value to a valid encoding . |
18,501 | def parse_key_curve ( value = None ) : if isinstance ( value , ec . EllipticCurve ) : return value if value is None : return ca_settings . CA_DEFAULT_ECC_CURVE curve = getattr ( ec , value . strip ( ) , type ) if not issubclass ( curve , ec . EllipticCurve ) : raise ValueError ( '%s: Not a known Eliptic Curve' % value ) return curve ( ) | Parse an elliptic curve value . |
18,502 | def get_cert_builder ( expires ) : now = datetime . utcnow ( ) . replace ( second = 0 , microsecond = 0 ) if expires is None : expires = get_expires ( expires , now = now ) expires = expires . replace ( second = 0 , microsecond = 0 ) builder = x509 . CertificateBuilder ( ) builder = builder . not_valid_before ( now ) builder = builder . not_valid_after ( expires ) builder = builder . serial_number ( x509 . random_serial_number ( ) ) return builder | Get a basic X509 cert builder object . |
18,503 | def wrap_file_exceptions ( ) : try : yield except ( PermissionError , FileNotFoundError ) : raise except ( IOError , OSError ) as e : if e . errno == errno . EACCES : raise PermissionError ( str ( e ) ) elif e . errno == errno . ENOENT : raise FileNotFoundError ( str ( e ) ) raise | Contextmanager to wrap file exceptions into identicaly exceptions in py2 and py3 . |
18,504 | def read_file ( path ) : if os . path . isabs ( path ) : with wrap_file_exceptions ( ) : with open ( path , 'rb' ) as stream : return stream . read ( ) with wrap_file_exceptions ( ) : stream = ca_storage . open ( path ) try : return stream . read ( ) finally : stream . close ( ) | Read the file from the given path . |
18,505 | def get_extension_name ( ext ) : if ext . oid == ExtensionOID . PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS : return 'SignedCertificateTimestampList' elif ca_settings . CRYPTOGRAPHY_HAS_PRECERT_POISON : if ext . oid == ExtensionOID . PRECERT_POISON : return 'PrecertPoison' return re . sub ( '^([a-z])' , lambda x : x . groups ( ) [ 0 ] . upper ( ) , ext . oid . _name ) | Function to get the name of an extension . |
18,506 | def shlex_split ( s , sep ) : lex = shlex . shlex ( s , posix = True ) lex . whitespace = sep lex . whitespace_split = True return [ l for l in lex ] | Split a character on the given set of characters . |
18,507 | def get_revocation_reason ( self ) : if self . revoked is False : return if self . revoked_reason == '' or self . revoked_reason is None : return x509 . ReasonFlags . unspecified else : return getattr ( x509 . ReasonFlags , self . revoked_reason ) | Get the revocation reason of this certificate . |
18,508 | def get_revocation_time ( self ) : if self . revoked is False : return if timezone . is_aware ( self . revoked_date ) : return timezone . make_naive ( self . revoked_date , pytz . utc ) return self . revoked_date | Get the revocation time as naive datetime . |
18,509 | def get_authority_key_identifier ( self ) : try : ski = self . x509 . extensions . get_extension_for_class ( x509 . SubjectKeyIdentifier ) except x509 . ExtensionNotFound : return x509 . AuthorityKeyIdentifier . from_issuer_public_key ( self . x509 . public_key ( ) ) else : return x509 . AuthorityKeyIdentifier . from_issuer_subject_key_identifier ( ski ) | Return the AuthorityKeyIdentifier extension used in certificates signed by this CA . |
18,510 | def max_pathlen ( self ) : pathlen = self . pathlen if self . parent is None : return pathlen max_parent = self . parent . max_pathlen if max_parent is None : return pathlen elif pathlen is None : return max_parent - 1 else : return min ( self . pathlen , max_parent - 1 ) | The maximum pathlen for any intermediate CAs signed by this CA . |
18,511 | def bundle ( self ) : ca = self bundle = [ ca ] while ca . parent is not None : bundle . append ( ca . parent ) ca = ca . parent return bundle | A list of any parent CAs including this CA . |
18,512 | def valid ( self ) : now = timezone . now ( ) return self . filter ( revoked = False , expires__gt = now , valid_from__lt = now ) | Return valid certificates . |
18,513 | def _release_version ( ) : with io . open ( os . path . join ( SETUP_DIRNAME , 'saltpylint' , 'version.py' ) , encoding = 'utf-8' ) as fh_ : exec_locals = { } exec_globals = { } contents = fh_ . read ( ) if not isinstance ( contents , str ) : contents = contents . encode ( 'utf-8' ) exec ( contents , exec_globals , exec_locals ) return exec_locals [ '__version__' ] | Returns release version |
18,514 | def get_versions ( source ) : tree = compiler . parse ( source ) checker = compiler . walk ( tree , NodeChecker ( ) ) return checker . vers | Return information about the Python versions required for specific features . |
18,515 | def process_non_raw_string_token ( self , prefix , string_body , start_row ) : if 'u' in prefix : if string_body . find ( '\\0' ) != - 1 : self . add_message ( 'null-byte-unicode-literal' , line = start_row ) | check for bad escapes in a non - raw string . |
18,516 | def register ( linter ) : linter . register_checker ( ResourceLeakageChecker ( linter ) ) linter . register_checker ( BlacklistedImportsChecker ( linter ) ) linter . register_checker ( MovedTestCaseClassChecker ( linter ) ) linter . register_checker ( BlacklistedLoaderModulesUsageChecker ( linter ) ) linter . register_checker ( BlacklistedFunctionsChecker ( linter ) ) | Required method to auto register this checker |
18,517 | def register ( linter ) : try : MANAGER . register_transform ( nodes . Class , rootlogger_transform ) except AttributeError : MANAGER . register_transform ( nodes . ClassDef , rootlogger_transform ) | Register the transformation functions . |
18,518 | def get_xblock_settings ( self , default = None ) : settings_service = self . runtime . service ( self , "settings" ) if settings_service : return settings_service . get_settings_bucket ( self , default = default ) return default | Gets XBlock - specific settigns for current XBlock |
18,519 | def include_theme_files ( self , fragment ) : theme = self . get_theme ( ) if not theme or 'package' not in theme : return theme_package , theme_files = theme . get ( 'package' , None ) , theme . get ( 'locations' , [ ] ) resource_loader = ResourceLoader ( theme_package ) for theme_file in theme_files : fragment . add_css ( resource_loader . load_unicode ( theme_file ) ) | Gets theme configuration and renders theme css into fragment |
18,520 | def load_unicode ( self , resource_path ) : resource_content = pkg_resources . resource_string ( self . module_name , resource_path ) return resource_content . decode ( 'utf-8' ) | Gets the content of a resource |
18,521 | def render_django_template ( self , template_path , context = None , i18n_service = None ) : context = context or { } context [ '_i18n_service' ] = i18n_service libraries = { 'i18n' : 'xblockutils.templatetags.i18n' , } _libraries = None if django . VERSION [ 0 ] == 1 and django . VERSION [ 1 ] == 8 : _libraries = TemplateBase . libraries . copy ( ) for library_name in libraries : library = TemplateBase . import_library ( libraries [ library_name ] ) if library : TemplateBase . libraries [ library_name ] = library engine = Engine ( ) else : from django . template . backends . django import get_installed_libraries installed_libraries = get_installed_libraries ( ) installed_libraries . update ( libraries ) engine = Engine ( libraries = installed_libraries ) template_str = self . load_unicode ( template_path ) template = Template ( template_str , engine = engine ) rendered = template . render ( Context ( context ) ) if _libraries is not None : TemplateBase . libraries = _libraries return rendered | Evaluate a django template by resource path applying the provided context . |
18,522 | def render_mako_template ( self , template_path , context = None ) : context = context or { } template_str = self . load_unicode ( template_path ) lookup = MakoTemplateLookup ( directories = [ pkg_resources . resource_filename ( self . module_name , '' ) ] ) template = MakoTemplate ( template_str , lookup = lookup ) return template . render ( ** context ) | Evaluate a mako template by resource path applying the provided context |
18,523 | def render_template ( self , template_path , context = None ) : warnings . warn ( "ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_template" ) return self . render_django_template ( template_path , context ) | This function has been deprecated . It calls render_django_template to support backwards compatibility . |
18,524 | def render_js_template ( self , template_path , element_id , context = None ) : context = context or { } return u"<script type='text/template' id='{}'>\n{}\n</script>" . format ( element_id , self . render_template ( template_path , context ) ) | Render a js template . |
18,525 | def merge_translation ( self , context ) : language = get_language ( ) i18n_service = context . get ( '_i18n_service' , None ) if i18n_service : if language not in self . _translations : self . _translations [ language ] = trans_real . DjangoTranslation ( language ) translation = trans_real . translation ( language ) translation . merge ( i18n_service ) yield if language in self . _translations : trans_real . _translations [ language ] = self . _translations [ language ] trans_real . activate ( language ) | Context wrapper which modifies the given language s translation catalog using the i18n service if found . |
18,526 | def render ( self , context ) : with self . merge_translation ( context ) : django_translated = self . do_translate . render ( context ) return django_translated | Renders the translated text using the XBlock i18n service if available . |
18,527 | def studio_view ( self , context ) : fragment = Fragment ( ) context = { 'fields' : [ ] } for field_name in self . editable_fields : field = self . fields [ field_name ] assert field . scope in ( Scope . content , Scope . settings ) , ( "Only Scope.content or Scope.settings fields can be used with " "StudioEditableXBlockMixin. Other scopes are for user-specific data and are " "not generally created/configured by content authors in Studio." ) field_info = self . _make_field_info ( field_name , field ) if field_info is not None : context [ "fields" ] . append ( field_info ) fragment . content = loader . render_template ( 'templates/studio_edit.html' , context ) fragment . add_javascript ( loader . load_unicode ( 'public/studio_edit.js' ) ) fragment . initialize_js ( 'StudioEditableXBlockMixin' ) return fragment | Render a form for editing this XBlock |
18,528 | def validate ( self ) : validation = super ( StudioEditableXBlockMixin , self ) . validate ( ) self . validate_field_data ( validation , self ) return validation | Validates the state of this XBlock . |
18,529 | def render_children ( self , context , fragment , can_reorder = True , can_add = False ) : contents = [ ] child_context = { 'reorderable_items' : set ( ) } if context : child_context . update ( context ) for child_id in self . children : child = self . runtime . get_block ( child_id ) if can_reorder : child_context [ 'reorderable_items' ] . add ( child . scope_ids . usage_id ) view_to_render = 'author_view' if hasattr ( child , 'author_view' ) else 'student_view' rendered_child = child . render ( view_to_render , child_context ) fragment . add_frag_resources ( rendered_child ) contents . append ( { 'id' : text_type ( child . scope_ids . usage_id ) , 'content' : rendered_child . content } ) fragment . add_content ( self . runtime . render_template ( "studio_render_children_view.html" , { 'items' : contents , 'xblock_context' : context , 'can_add' : can_add , 'can_reorder' : can_reorder , } ) ) | Renders the children of the module with HTML appropriate for Studio . If can_reorder is True then the children will be rendered to support drag and drop . |
18,530 | def author_view ( self , context ) : root_xblock = context . get ( 'root_xblock' ) if root_xblock and root_xblock . location == self . location : return self . author_edit_view ( context ) return self . author_preview_view ( context ) | Display a the studio editor when the user has clicked View to see the container view otherwise just show the normal author_preview_view or student_view preview . |
18,531 | def author_edit_view ( self , context ) : fragment = Fragment ( ) self . render_children ( context , fragment , can_reorder = True , can_add = False ) return fragment | Child blocks can override this to control the view shown to authors in Studio when editing this block s children . |
18,532 | def preview_view ( self , context ) : view_to_render = 'author_view' if hasattr ( self , 'author_view' ) else 'student_view' renderer = getattr ( self , view_to_render ) return renderer ( context ) | Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context . Default implementation uses author_view if available otherwise falls back to student_view Child classes can override this method to control their presentation in preview context |
18,533 | def get_nested_blocks_spec ( self ) : return [ block_spec if isinstance ( block_spec , NestedXBlockSpec ) else NestedXBlockSpec ( block_spec ) for block_spec in self . allowed_nested_blocks ] | Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface |
18,534 | def author_preview_view ( self , context ) : children_contents = [ ] fragment = Fragment ( ) for child_id in self . children : child = self . runtime . get_block ( child_id ) child_fragment = self . _render_child_fragment ( child , context , 'preview_view' ) fragment . add_frag_resources ( child_fragment ) children_contents . append ( child_fragment . content ) render_context = { 'block' : self , 'children_contents' : children_contents } render_context . update ( context ) fragment . add_content ( self . loader . render_template ( self . CHILD_PREVIEW_TEMPLATE , render_context ) ) return fragment | View for previewing contents in studio . |
18,535 | def _render_child_fragment ( self , child , context , view = 'student_view' ) : try : child_fragment = child . render ( view , context ) except NoSuchViewError : if child . scope_ids . block_type == 'html' and getattr ( self . runtime , 'is_author_mode' , False ) : child_fragment = Fragment ( child . data ) else : child_fragment = child . render ( 'student_view' , context ) return child_fragment | Helper method to overcome html block rendering quirks |
18,536 | def package_data ( pkg , root_list ) : data = [ ] for root in root_list : for dirname , _ , files in os . walk ( os . path . join ( pkg , root ) ) : for fname in files : data . append ( os . path . relpath ( os . path . join ( dirname , fname ) , pkg ) ) return { pkg : data } | Generic function to find package_data for pkg under root . |
18,537 | def load_requirements ( * requirements_paths ) : requirements = set ( ) for path in requirements_paths : requirements . update ( line . split ( '#' ) [ 0 ] . strip ( ) for line in open ( path ) . readlines ( ) if is_requirement ( line . strip ( ) ) ) return list ( requirements ) | Load all requirements from the specified requirements files . Returns a list of requirement strings . |
18,538 | def is_requirement ( line ) : return not ( line == '' or line . startswith ( '-r' ) or line . startswith ( '#' ) or line . startswith ( '-e' ) or line . startswith ( 'git+' ) ) | Return True if the requirement line is a package requirement ; that is it is not blank a comment a URL or an included file . |
18,539 | def publish_event ( self , data , suffix = '' ) : try : event_type = data . pop ( 'event_type' ) except KeyError : return { 'result' : 'error' , 'message' : 'Missing event_type in JSON data' } return self . publish_event_from_dict ( event_type , data ) | AJAX handler to allow client - side code to publish a server - side event |
18,540 | def publish_event_from_dict ( self , event_type , data ) : for key , value in self . additional_publish_event_data . items ( ) : if key in data : return { 'result' : 'error' , 'message' : 'Key should not be in publish_event data: {}' . format ( key ) } data [ key ] = value self . runtime . publish ( self , event_type , data ) return { 'result' : 'success' } | Combine data with self . additional_publish_event_data and publish an event |
18,541 | def child_isinstance ( block , child_id , block_class_or_mixin ) : def_id = block . runtime . id_reader . get_definition_id ( child_id ) type_name = block . runtime . id_reader . get_block_type ( def_id ) child_class = block . runtime . load_block_type ( type_name ) return issubclass ( child_class , block_class_or_mixin ) | Efficiently check if a child of an XBlock is an instance of the given class . |
18,542 | def attr ( self , * args , ** kwargs ) : kwargs . update ( { k : bool for k in args } ) for key , value in kwargs . items ( ) : if key == "klass" : self . attrs [ "klass" ] . update ( value . split ( ) ) elif key == "style" : if isinstance ( value , str ) : splitted = iter ( re . split ( ";|:" , value ) ) value = dict ( zip ( splitted , splitted ) ) self . attrs [ "style" ] . update ( value ) else : self . attrs [ key ] = value self . _stable = False return self | Add an attribute to the element |
18,543 | def remove_attr ( self , attr ) : self . _stable = False self . attrs . pop ( attr , None ) return self | Removes an attribute . |
18,544 | def render_attrs ( self ) : ret = [ ] for k , v in self . attrs . items ( ) : if v : if v is bool : ret . append ( " %s" % self . _SPECIAL_ATTRS . get ( k , k ) ) else : fnc = self . _FORMAT_ATTRS . get ( k , None ) val = fnc ( v ) if fnc else v ret . append ( ' %s="%s"' % ( self . _SPECIAL_ATTRS . get ( k , k ) , val ) ) return "" . join ( ret ) | Renders the tag s attributes using the formats and performing special attributes name substitution . |
18,545 | def toggle_class ( self , csscl ) : self . _stable = False action = ( "add" , "remove" ) [ self . has_class ( csscl ) ] return getattr ( self . attrs [ "klass" ] , action ) ( csscl ) | Same as jQuery s toggleClass function . It toggles the css class on this element . |
18,546 | def add_class ( self , cssclass ) : if self . has_class ( cssclass ) : return self return self . toggle_class ( cssclass ) | Adds a css class to this element . |
18,547 | def remove_class ( self , cssclass ) : if not self . has_class ( cssclass ) : return self return self . toggle_class ( cssclass ) | Removes the given class from this element . |
18,548 | def css ( self , * props , ** kwprops ) : self . _stable = False styles = { } if props : if len ( props ) == 1 and isinstance ( props [ 0 ] , Mapping ) : styles = props [ 0 ] else : raise WrongContentError ( self , props , "Arguments not valid" ) elif kwprops : styles = kwprops else : raise WrongContentError ( self , None , "args OR wkargs are needed" ) return self . attr ( style = styles ) | Adds css properties to this element . |
18,549 | def show ( self , display = None ) : self . _stable = False if not display : self . attrs [ "style" ] . pop ( "display" ) else : self . attrs [ "style" ] [ "display" ] = display return self | Removes the display style attribute . If a display type is provided |
18,550 | def toggle ( self ) : self . _stable = False return self . show ( ) if self . attrs [ "style" ] [ "display" ] == "none" else self . hide ( ) | Same as jQuery s toggle toggles the display attribute of this element . |
18,551 | def text ( self ) : texts = [ ] for child in self . childs : if isinstance ( child , Tag ) : texts . append ( child . text ( ) ) elif isinstance ( child , Content ) : texts . append ( child . render ( ) ) else : texts . append ( child ) return " " . join ( texts ) | Renders the contents inside this element without html tags . |
18,552 | def render ( self , * args , ** kwargs ) : pretty = kwargs . pop ( "pretty" , False ) if pretty and self . _stable != "pretty" : self . _stable = False for arg in args : self . _stable = False if isinstance ( arg , dict ) : self . inject ( arg ) if kwargs : self . _stable = False self . inject ( kwargs ) if self . _stable and self . _render : return self . _render pretty_pre = pretty_inner = "" if pretty : pretty_pre = "\n" + ( "\t" * self . _depth ) if pretty else "" pretty_inner = "\n" + ( "\t" * self . _depth ) if len ( self . childs ) > 1 else "" inner = self . render_childs ( pretty ) if not self . _void else "" tag_data = ( pretty_pre , self . _get__tag ( ) , self . render_attrs ( ) , inner , pretty_inner , self . _get__tag ( ) ) [ : 6 - [ 0 , 3 ] [ self . _void ] ] self . _render = self . _template % tag_data self . _stable = "pretty" if pretty else True return self . _render | Renders the element and all his childrens . |
18,553 | def _make_tempy_tag ( self , tag , attrs , void ) : tempy_tag_cls = getattr ( self . tempy_tags , tag . title ( ) , None ) if not tempy_tag_cls : unknow_maker = [ self . unknown_tag_maker , self . unknown_tag_maker . Void ] [ void ] tempy_tag_cls = unknow_maker [ tag ] attrs = { Tag . _TO_SPECIALS . get ( k , k ) : v or True for k , v in attrs } tempy_tag = tempy_tag_cls ( ** attrs ) if not self . current_tag : self . result . append ( tempy_tag ) if not void : self . current_tag = tempy_tag else : if not tempy_tag . _void : self . current_tag ( tempy_tag ) self . current_tag = self . current_tag . childs [ - 1 ] | Searches in tempy . tags for the correct tag to use if does not exists uses the TempyFactory to create a custom tag . |
18,554 | def from_string ( self , html_string ) : self . _html_parser . _reset ( ) . feed ( html_string ) return self . _html_parser . result | Parses an html string and returns a list of Tempy trees . |
18,555 | def dump ( self , tempy_tree_list , filename , pretty = False ) : if not filename : raise ValueError ( '"filename" argument should not be none.' ) if len ( filename . split ( "." ) ) > 1 and not filename . endswith ( ".py" ) : raise ValueError ( '"filename" argument should have a .py extension, if given.' ) if not filename . endswith ( ".py" ) : filename += ".py" with open ( filename , "w" ) as f : f . write ( "# -*- coding: utf-8 -*-\nfrom tempy import T\nfrom tempy.tags import *\n" ) for tempy_tree in tempy_tree_list : f . write ( tempy_tree . to_code ( pretty = pretty ) ) return filename | Dumps a Tempy object to a python file |
18,556 | def _filter_classes ( cls_list , cls_type ) : for cls in cls_list : if isinstance ( cls , type ) and issubclass ( cls , cls_type ) : if cls_type == TempyPlace and cls . _base_place : pass else : yield cls | Filters a list of classes and yields TempyREPR subclasses |
18,557 | def _evaluate_tempyREPR ( self , child , repr_cls ) : score = 0 if repr_cls . __name__ == self . __class__ . __name__ : score += 1 elif repr_cls . __name__ == self . root . __class__ . __name__ : score += 1 for parent_cls in _filter_classes ( repr_cls . __mro__ [ 1 : ] , TempyPlace ) : for scorer in ( method for method in dir ( parent_cls ) if method . startswith ( "_reprscore" ) ) : score += getattr ( parent_cls , scorer , lambda * args : 0 ) ( parent_cls , self , child ) return score | Assign a score ito a TempyRepr class . The scores depends on the current scope and position of the object in which the TempyREPR is found . |
18,558 | def _search_for_view ( self , obj ) : evaluator = partial ( self . _evaluate_tempyREPR , obj ) sorted_reprs = sorted ( _filter_classes ( obj . __class__ . __dict__ . values ( ) , TempyREPR ) , key = evaluator , reverse = True , ) if sorted_reprs : return sorted_reprs [ 0 ] return None | Searches for TempyREPR class declarations in the child s class . If at least one TempyREPR is found it uses the best one to make a Tempy object . Otherwise the original object is returned . |
18,559 | def add_row ( self , row_data , resize_x = True ) : if not resize_x : self . _check_row_size ( row_data ) self . body ( Tr ( ) ( Td ( ) ( cell ) for cell in row_data ) ) return self | Adds a row at the end of the table |
18,560 | def pop_row ( self , idr = None , tags = False ) : idr = idr if idr is not None else len ( self . body ) - 1 row = self . body . pop ( idr ) return row if tags else [ cell . childs [ 0 ] for cell in row ] | Pops a row default the last |
18,561 | def pop_cell ( self , idy = None , idx = None , tags = False ) : idy = idy if idy is not None else len ( self . body ) - 1 idx = idx if idx is not None else len ( self . body [ idy ] ) - 1 cell = self . body [ idy ] . pop ( idx ) return cell if tags else cell . childs [ 0 ] | Pops a cell default the last of the last row |
18,562 | def render ( self , * args , ** kwargs ) : return self . doctype . render ( ) + super ( ) . render ( * args , ** kwargs ) | Override so each html page served have a doctype |
18,563 | def _find_content ( self , cont_name ) : try : a = self . content_data [ cont_name ] return a except KeyError : if self . parent : return self . parent . _find_content ( cont_name ) else : return "" | Search for a content_name in the content data if not found the parent is searched . |
18,564 | def _get_non_tempy_contents ( self ) : for thing in filter ( lambda x : not issubclass ( x . __class__ , DOMElement ) , self . childs ) : yield thing | Returns rendered Contents and non - DOMElement stuff inside this Tag . |
18,565 | def siblings ( self ) : return list ( filter ( lambda x : id ( x ) != id ( self ) , self . parent . childs ) ) | Returns all the siblings of this element as a list . |
18,566 | def bft ( self ) : queue = deque ( [ self ] ) while queue : node = queue . pop ( ) yield node if hasattr ( node , "childs" ) : queue . extendleft ( node . childs ) | Generator that returns each element of the tree in Breadth - first order |
18,567 | def _insert ( self , dom_group , idx = None , prepend = False , name = None ) : if idx and idx < 0 : idx = 0 if prepend : idx = 0 else : idx = idx if idx is not None else len ( self . childs ) if dom_group is not None : if not isinstance ( dom_group , Iterable ) or isinstance ( dom_group , ( DOMElement , str ) ) : dom_group = [ dom_group ] for i_group , elem in enumerate ( dom_group ) : if elem is not None : self . childs . insert ( idx + i_group , elem ) if issubclass ( elem . __class__ , DOMElement ) : elem . parent = self if name : setattr ( self , name , elem ) | Inserts a DOMGroup inside this element . If provided at the given index if prepend at the start of the childs list by default at the end . If the child is a DOMElement correctly links the child . If the DOMGroup have a name an attribute containing the child is created in this instance . |
18,568 | def after ( self , i , sibling , name = None ) : self . parent . _insert ( sibling , idx = self . _own_index + 1 + i , name = name ) return self | Adds siblings after the current tag . |
18,569 | def prepend ( self , _ , child , name = None ) : self . _insert ( child , prepend = True , name = name ) return self | Adds childs to this tag starting from the first position . |
18,570 | def append ( self , _ , child , name = None ) : self . _insert ( child , name = name ) return self | Adds childs to this tag after the current existing childs . |
18,571 | def wrap ( self , other ) : if other . childs : raise TagError ( self , "Wrapping in a non empty Tag is forbidden." ) if self . parent : self . before ( other ) self . parent . pop ( self . _own_index ) other . append ( self ) return self | Wraps this element inside another empty tag . |
18,572 | def replace_with ( self , other ) : self . after ( other ) self . parent . pop ( self . _own_index ) return other | Replace this element with the given DOMElement . |
18,573 | def remove ( self ) : if self . _own_index is not None and self . parent : self . parent . pop ( self . _own_index ) return self | Detach this element from his father . |
18,574 | def _detach_childs ( self , idx_from = None , idx_to = None ) : idx_from = idx_from or 0 idx_to = idx_to or len ( self . childs ) removed = self . childs [ idx_from : idx_to ] for child in removed : if issubclass ( child . __class__ , DOMElement ) : child . parent = None self . childs [ idx_from : idx_to ] = [ ] return removed | Moves all the childs to a new father |
18,575 | def move ( self , new_father , idx = None , prepend = None , name = None ) : self . parent . pop ( self . _own_index ) new_father . _insert ( self , idx = idx , prepend = prepend , name = name ) new_father . _stable = False return self | Moves this element from his father to the given one . |
18,576 | def run ( target , target_type , tags = None , ruleset_name = None , ruleset_file = None , ruleset = None , logging_level = logging . WARNING , checks_paths = None , pull = None , insecure = False , skips = None , timeout = None , ) : _set_logging ( level = logging_level ) logger . debug ( "Checking started." ) target = Target . get_instance ( target = target , logging_level = logging_level , pull = pull , target_type = target_type , insecure = insecure , ) checks_to_run = _get_checks ( target_type = target . __class__ , tags = tags , ruleset_name = ruleset_name , ruleset_file = ruleset_file , ruleset = ruleset , checks_paths = checks_paths , skips = skips , ) result = go_through_checks ( target = target , checks = checks_to_run , timeout = timeout ) return result | Runs the sanity checks for the target . |
18,577 | def get_checks ( target_type = None , tags = None , ruleset_name = None , ruleset_file = None , ruleset = None , logging_level = logging . WARNING , checks_paths = None , skips = None , ) : _set_logging ( level = logging_level ) logger . debug ( "Finding checks started." ) return _get_checks ( target_type = target_type , tags = tags , ruleset_name = ruleset_name , ruleset_file = ruleset_file , ruleset = ruleset , checks_paths = checks_paths , skips = skips , ) | Get the sanity checks for the target . |
18,578 | def _set_logging ( logger_name = "colin" , level = logging . INFO , handler_class = logging . StreamHandler , handler_kwargs = None , format = '%(asctime)s.%(msecs).03d %(filename)-17s %(levelname)-6s %(message)s' , date_format = '%H:%M:%S' ) : if level != logging . NOTSET : logger = logging . getLogger ( logger_name ) logger . setLevel ( level ) if not [ x for x in logger . handlers if isinstance ( x , handler_class ) ] : handler_kwargs = handler_kwargs or { } handler = handler_class ( ** handler_kwargs ) handler . setLevel ( level ) formatter = logging . Formatter ( format , date_format ) handler . setFormatter ( formatter ) logger . addHandler ( handler ) | Set personal logger for this library . |
18,579 | def check_label ( labels , required , value_regex , target_labels ) : present = target_labels is not None and not set ( labels ) . isdisjoint ( set ( target_labels ) ) if present : if required and not value_regex : return True elif value_regex : pattern = re . compile ( value_regex ) present_labels = set ( labels ) & set ( target_labels ) for l in present_labels : if not bool ( pattern . search ( target_labels [ l ] ) ) : return False return True else : return False else : return not required | Check if the label is required and match the regex |
18,580 | def json ( self ) : return { 'name' : self . name , 'message' : self . message , 'description' : self . description , 'reference_url' : self . reference_url , 'tags' : self . tags , } | Get json representation of the check |
18,581 | def get_checks_paths ( checks_paths = None ) : p = os . path . join ( __file__ , os . pardir , os . pardir , os . pardir , "checks" ) p = os . path . abspath ( p ) if checks_paths : p += [ os . path . abspath ( x ) for x in checks_paths ] return [ p ] | Get path to checks . |
18,582 | def get_ruleset_file ( ruleset = None ) : ruleset = ruleset or "default" ruleset_dirs = get_ruleset_dirs ( ) for ruleset_directory in ruleset_dirs : possible_ruleset_files = [ os . path . join ( ruleset_directory , ruleset + ext ) for ext in EXTS ] for ruleset_file in possible_ruleset_files : if os . path . isfile ( ruleset_file ) : logger . debug ( "Ruleset file '{}' found." . format ( ruleset_file ) ) return ruleset_file logger . warning ( "Ruleset with the name '{}' cannot be found at '{}'." . format ( ruleset , ruleset_dirs ) ) raise ColinRulesetException ( "Ruleset with the name '{}' cannot be found." . format ( ruleset ) ) | Get the ruleset file from name |
18,583 | def get_rulesets ( ) : rulesets_dirs = get_ruleset_dirs ( ) ruleset_files = [ ] for rulesets_dir in rulesets_dirs : for f in os . listdir ( rulesets_dir ) : for ext in EXTS : file_path = os . path . join ( rulesets_dir , f ) if os . path . isfile ( file_path ) and f . lower ( ) . endswith ( ext ) : ruleset_files . append ( ( f [ : - len ( ext ) ] , file_path ) ) return ruleset_files | Get available rulesets . |
18,584 | def get_rpm_version ( package_name ) : version_result = subprocess . run ( [ "rpm" , "-q" , package_name ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) if version_result . returncode == 0 : return version_result . stdout . decode ( ) . rstrip ( ) else : return None | Get a version of the package with rpm - q command . |
18,585 | def is_rpm_installed ( ) : try : version_result = subprocess . run ( [ "rpm" , "--usage" ] , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) rpm_installed = not version_result . returncode except FileNotFoundError : rpm_installed = False return rpm_installed | Tests if the rpm command is present . |
18,586 | def exit_after ( s ) : def outer ( fn ) : def inner ( * args , ** kwargs ) : timer = threading . Timer ( s , thread . interrupt_main ) timer . start ( ) try : result = fn ( * args , ** kwargs ) except KeyboardInterrupt : raise TimeoutError ( "Function '{}' hit the timeout ({}s)." . format ( fn . __name__ , s ) ) finally : timer . cancel ( ) return result return inner return outer | Use as decorator to exit process if function takes longer than s seconds . |
18,587 | def retry ( retry_count = 5 , delay = 2 ) : if retry_count <= 0 : raise ValueError ( "retry_count have to be positive" ) def decorator ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : for i in range ( retry_count , 0 , - 1 ) : try : return f ( * args , ** kwargs ) except Exception : if i <= 1 : raise time . sleep ( delay ) return wrapper return decorator | Use as decorator to retry functions few times with delays |
18,588 | def parse ( cls , image_name ) : result = cls ( ) s = image_name . split ( '/' , 2 ) if len ( s ) == 2 : if '.' in s [ 0 ] or ':' in s [ 0 ] : result . registry = s [ 0 ] else : result . namespace = s [ 0 ] elif len ( s ) == 3 : result . registry = s [ 0 ] result . namespace = s [ 1 ] result . repository = s [ - 1 ] try : result . repository , result . digest = result . repository . rsplit ( "@" , 1 ) except ValueError : try : result . repository , result . tag = result . repository . rsplit ( ":" , 1 ) except ValueError : result . tag = "latest" return result | Get the instance of ImageName from the string representation . |
18,589 | def other_attributes ( self ) : return { k : v for k , v in self . c . items ( ) if k not in [ "name" , "names" , "tags" , "additional_tags" , "usable_targets" ] } | return dict with all other data except for the described above |
18,590 | def should_we_load ( kls ) : if kls . __name__ . endswith ( "AbstractCheck" ) : return False if not kls . __name__ . endswith ( "Check" ) : return False mro = kls . __mro__ for m in mro : if m . __name__ == "AbstractCheck" : return True return False | should we load this class as a check? |
18,591 | def obtain_check_classes ( self ) : check_classes = set ( ) for path in self . paths : for root , _ , files in os . walk ( path ) : for fi in files : if not fi . endswith ( ".py" ) : continue path = os . path . join ( root , fi ) check_classes = check_classes . union ( set ( load_check_classes_from_file ( path ) ) ) return list ( check_classes ) | find children of AbstractCheck class and return them as a list |
18,592 | def import_class ( self , import_name ) : module_name , class_name = import_name . rsplit ( "." , 1 ) mod = import_module ( module_name ) check_class = getattr ( mod , class_name ) self . mapping [ check_class . name ] = check_class logger . info ( "successfully loaded class %s" , check_class ) return check_class | import selected class |
18,593 | def _dict_of_results ( self ) : result_json = { } result_list = [ ] for r in self . results : result_list . append ( { 'name' : r . check_name , 'ok' : r . ok , 'status' : r . status , 'description' : r . description , 'message' : r . message , 'reference_url' : r . reference_url , 'logs' : r . logs , } ) result_json [ "checks" ] = result_list return result_json | Get the dictionary representation of results |
18,594 | def statistics ( self ) : result = { } for r in self . results : result . setdefault ( r . status , 0 ) result [ r . status ] += 1 return result | Get the dictionary with the count of the check - statuses |
18,595 | def generate_pretty_output ( self , stat , verbose , output_function , logs = True ) : has_check = False for r in self . results : has_check = True if stat : output_function ( OUTPUT_CHARS [ r . status ] , fg = COLOURS [ r . status ] , nl = False ) else : output_function ( str ( r ) , fg = COLOURS [ r . status ] ) if verbose : output_function ( " -> {}\n" " -> {}" . format ( r . description , r . reference_url ) , fg = COLOURS [ r . status ] ) if logs and r . logs : output_function ( " -> logs:" , fg = COLOURS [ r . status ] ) for l in r . logs : output_function ( " -> {}" . format ( l ) , fg = COLOURS [ r . status ] ) if not has_check : output_function ( "No check found." ) elif stat and not verbose : output_function ( "" ) else : output_function ( "" ) for status , count in six . iteritems ( self . statistics ) : output_function ( "{}:{} " . format ( status , count ) , nl = False ) output_function ( "" ) | Send the formated to the provided function |
18,596 | def get_pretty_string ( self , stat , verbose ) : pretty_output = _PrettyOutputToStr ( ) self . generate_pretty_output ( stat = stat , verbose = verbose , output_function = pretty_output . save_output ) return pretty_output . result | Pretty string representation of the results |
18,597 | def receive_fmf_metadata ( name , path , object_list = False ) : output = { } fmf_tree = ExtendedTree ( path ) logger . debug ( "get FMF metadata for test (path:%s name=%s)" , path , name ) items = [ x for x in fmf_tree . climb ( ) if x . name . endswith ( "/" + name ) and "@" not in x . name ] if object_list : return items if len ( items ) == 1 : output = items [ 0 ] elif len ( items ) > 1 : raise Exception ( "There is more FMF test metadata for item by name:{}({}) {}" . format ( name , len ( items ) , [ x . name for x in items ] ) ) elif not items : raise Exception ( "Unable to get FMF metadata for: {}" . format ( name ) ) return output | search node identified by name fmfpath |
18,598 | def list_checks ( ruleset , ruleset_file , debug , json , skip , tag , verbose , checks_paths ) : if ruleset and ruleset_file : raise click . BadOptionUsage ( "Options '--ruleset' and '--file-ruleset' cannot be used together." ) try : if not debug : logging . basicConfig ( stream = six . StringIO ( ) ) log_level = _get_log_level ( debug = debug , verbose = verbose ) checks = get_checks ( ruleset_name = ruleset , ruleset_file = ruleset_file , logging_level = log_level , tags = tag , checks_paths = checks_paths , skips = skip ) _print_checks ( checks = checks ) if json : AbstractCheck . save_checks_to_json ( file = json , checks = checks ) except ColinException as ex : logger . error ( "An error occurred: %r" , ex ) if debug : raise else : raise click . ClickException ( str ( ex ) ) except Exception as ex : logger . error ( "An error occurred: %r" , ex ) if debug : raise else : raise click . ClickException ( str ( ex ) ) | Print the checks . |
18,599 | def list_rulesets ( debug ) : try : rulesets = get_rulesets ( ) max_len = max ( [ len ( r [ 0 ] ) for r in rulesets ] ) for r in rulesets : click . echo ( '{0: <{1}} ({2})' . format ( r [ 0 ] , max_len , r [ 1 ] ) ) except Exception as ex : logger . error ( "An error occurred: %r" , ex ) if debug : raise else : raise click . ClickException ( str ( ex ) ) | List available rulesets . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.