idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
18,400
def search_by_release ( self , release_id , limit = 0 , order_by = None , sort_order = None , filter = None ) : url = "%s/release/series?release_id=%d" % ( self . root_url , release_id ) info = self . __get_search_results ( url , limit , order_by , sort_order , filter ) if info is None : raise ValueError ( 'No series exists for release id: ' + str ( release_id ) ) return info
Search for series that belongs to a release id . Returns information about matching series in a DataFrame .
115
20
18,401
def search_by_category ( self , category_id , limit = 0 , order_by = None , sort_order = None , filter = None ) : url = "%s/category/series?category_id=%d&" % ( self . root_url , category_id ) info = self . __get_search_results ( url , limit , order_by , sort_order , filter ) if info is None : raise ValueError ( 'No series exists for category id: ' + str ( category_id ) ) return info
Search for series that belongs to a category id . Returns information about matching series in a DataFrame .
116
20
18,402
def init ( self , ca , csr , * * kwargs ) : c = self . model ( ca = ca ) c . x509 , csr = self . sign_cert ( ca , csr , * * kwargs ) c . csr = csr . public_bytes ( Encoding . PEM ) . decode ( 'utf-8' ) c . save ( ) post_issue_cert . send ( sender = self . model , cert = c ) return c
Create a signed certificate from a CSR and store it to the database .
104
15
18,403
def download_bundle_view ( self , request , pk ) : return self . _download_response ( request , pk , bundle = True )
A view that allows the user to download a certificate bundle in PEM format .
33
16
18,404
def get_actions ( self , request ) : actions = super ( CertificateMixin , self ) . get_actions ( request ) actions . pop ( 'delete_selected' , '' ) return actions
Disable the delete selected admin action .
41
7
18,405
def get_cert_profile_kwargs ( name = None ) : if name is None : name = ca_settings . CA_DEFAULT_PROFILE profile = deepcopy ( ca_settings . CA_PROFILES [ name ] ) kwargs = { 'cn_in_san' : profile [ 'cn_in_san' ] , 'subject' : get_default_subject ( name = name ) , } key_usage = profile . get ( 'keyUsage' ) if key_usage and key_usage . get ( 'value' ) : kwargs [ 'key_usage' ] = KeyUsage ( key_usage ) ext_key_usage = profile . get ( 'extendedKeyUsage' ) if ext_key_usage and ext_key_usage . get ( 'value' ) : kwargs [ 'extended_key_usage' ] = ExtendedKeyUsage ( ext_key_usage ) tls_feature = profile . get ( 'TLSFeature' ) if tls_feature and tls_feature . get ( 'value' ) : kwargs [ 'tls_feature' ] = TLSFeature ( tls_feature ) if profile . get ( 'ocsp_no_check' ) : kwargs [ 'ocsp_no_check' ] = profile [ 'ocsp_no_check' ] return kwargs
Get kwargs suitable for get_cert X509 keyword arguments from the given profile .
297
18
18,406
def format_name ( subject ) : if isinstance ( subject , x509 . Name ) : subject = [ ( OID_NAME_MAPPINGS [ s . oid ] , s . value ) for s in subject ] return '/%s' % ( '/' . join ( [ '%s=%s' % ( force_text ( k ) , force_text ( v ) ) for k , v in subject ] ) )
Convert a subject into the canonical form for distinguished names .
93
12
18,407
def format_general_name ( name ) : if isinstance ( name , x509 . DirectoryName ) : value = format_name ( name . value ) else : value = name . value return '%s:%s' % ( SAN_NAME_MAPPINGS [ type ( name ) ] , value )
Format a single general name .
66
6
18,408
def add_colons ( s ) : return ':' . join ( [ s [ i : i + 2 ] for i in range ( 0 , len ( s ) , 2 ) ] )
Add colons after every second digit .
40
8
18,409
def int_to_hex ( i ) : s = hex ( i ) [ 2 : ] . upper ( ) if six . PY2 is True and isinstance ( i , long ) : # pragma: only py2 # NOQA # Strip the "L" suffix, since hex(1L) -> 0x1L. # NOTE: Do not convert to int earlier. int(<very-large-long>) is still long s = s [ : - 1 ] return add_colons ( s )
Create a hex - representation of the given serial .
110
10
18,410
def parse_name ( name ) : name = name . strip ( ) if not name : # empty subjects are ok return [ ] try : items = [ ( NAME_CASE_MAPPINGS [ t [ 0 ] . upper ( ) ] , force_text ( t [ 2 ] ) ) for t in NAME_RE . findall ( name ) ] except KeyError as e : raise ValueError ( 'Unknown x509 name field: %s' % e . args [ 0 ] ) # Check that no OIDs not in MULTIPLE_OIDS occur more then once for key , oid in NAME_OID_MAPPINGS . items ( ) : if sum ( 1 for t in items if t [ 0 ] == key ) > 1 and oid not in MULTIPLE_OIDS : raise ValueError ( 'Subject contains multiple "%s" fields' % key ) return sort_name ( items )
Parses a subject string as used in OpenSSLs command line utilities .
195
16
18,411
def parse_general_name ( name ) : name = force_text ( name ) typ = None match = GENERAL_NAME_RE . match ( name ) if match is not None : typ , name = match . groups ( ) typ = typ . lower ( ) if typ is None : if re . match ( '[a-z0-9]{2,}://' , name ) : # Looks like a URI try : return x509 . UniformResourceIdentifier ( name ) except Exception : # pragma: no cover - this really accepts anything pass if '@' in name : # Looks like an Email address try : return x509 . RFC822Name ( validate_email ( name ) ) except Exception : pass if name . strip ( ) . startswith ( '/' ) : # maybe it's a dirname? return x509 . DirectoryName ( x509_name ( name ) ) # Try to parse this as IPAddress/Network try : return x509 . IPAddress ( ip_address ( name ) ) except ValueError : pass try : return x509 . IPAddress ( ip_network ( name ) ) except ValueError : pass # Try to encode as domain name. DNSName() does not validate the domain name, but this check will fail. if name . startswith ( '*.' ) : idna . encode ( name [ 2 : ] ) elif name . startswith ( '.' ) : idna . encode ( name [ 1 : ] ) else : idna . encode ( name ) # Almost anything passes as DNS name, so this is our default fallback return x509 . DNSName ( name ) if typ == 'uri' : return x509 . UniformResourceIdentifier ( name ) elif typ == 'email' : return x509 . RFC822Name ( validate_email ( name ) ) elif typ == 'ip' : try : return x509 . IPAddress ( ip_address ( name ) ) except ValueError : pass try : return x509 . IPAddress ( ip_network ( name ) ) except ValueError : pass raise ValueError ( 'Could not parse IP address.' ) elif typ == 'rid' : return x509 . RegisteredID ( x509 . ObjectIdentifier ( name ) ) elif typ == 'othername' : regex = "(.*);(.*):(.*)" if re . match ( regex , name ) is not None : oid , asn_typ , val = re . match ( regex , name ) . groups ( ) oid = x509 . ObjectIdentifier ( oid ) if asn_typ == 'UTF8' : val = val . encode ( 'utf-8' ) elif asn_typ == 'OctetString' : val = bytes ( bytearray . fromhex ( val ) ) val = OctetString ( val ) . dump ( ) else : raise ValueError ( 'Unsupported ASN type in otherName: %s' % asn_typ ) val = force_bytes ( val ) return x509 . OtherName ( oid , val ) else : raise ValueError ( 'Incorrect otherName format: %s' % name ) elif typ == 'dirname' : return x509 . DirectoryName ( x509_name ( name ) ) else : # Try to encode the domain name. DNSName() does not validate the domain name, but this # check will fail. if name . startswith ( '*.' ) : idna . encode ( name [ 2 : ] ) elif name . startswith ( '.' ) : idna . encode ( name [ 1 : ] ) else : idna . encode ( name ) return x509 . DNSName ( name )
Parse a general name from user input .
788
9
18,412
def parse_hash_algorithm ( value = None ) : if value is None : return ca_settings . CA_DIGEST_ALGORITHM elif isinstance ( value , type ) and issubclass ( value , hashes . HashAlgorithm ) : return value ( ) elif isinstance ( value , hashes . HashAlgorithm ) : return value elif isinstance ( value , six . string_types ) : try : return getattr ( hashes , value . strip ( ) ) ( ) except AttributeError : raise ValueError ( 'Unknown hash algorithm: %s' % value ) else : raise ValueError ( 'Unknown type passed: %s' % type ( value ) . __name__ )
Parse a hash algorithm value .
151
7
18,413
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 .
124
9
18,414
def parse_key_curve ( value = None ) : if isinstance ( value , ec . EllipticCurve ) : return value # name was already parsed 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 .
111
8
18,415
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 .
119
9
18,416
def wrap_file_exceptions ( ) : try : yield except ( PermissionError , FileNotFoundError ) : # pragma: only py3 # In py3, we want to raise Exception unchanged, so there would be no need for this block. # BUT (IOError, OSError) - see below - also matches, so we capture it here raise except ( IOError , OSError ) as e : # pragma: only py2 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 .
147
17
18,417
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 .
82
8
18,418
def get_extension_name ( ext ) : # In cryptography 2.2, SCTs return "Unknown OID" if ext . oid == ExtensionOID . PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS : return 'SignedCertificateTimestampList' # Until at least cryptography 2.6.1, PrecertPoison has no name # https://github.com/pyca/cryptography/issues/4817 elif ca_settings . CRYPTOGRAPHY_HAS_PRECERT_POISON : # pragma: no branch, pragma: only cryptography>=2.4 if ext . oid == ExtensionOID . PRECERT_POISON : return 'PrecertPoison' # uppercase the FIRST letter only ("keyUsage" -> "KeyUsage") return re . sub ( '^([a-z])' , lambda x : x . groups ( ) [ 0 ] . upper ( ) , ext . oid . _name )
Function to get the name of an extension .
219
9
18,419
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 .
48
10
18,420
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 .
62
8
18,421
def get_revocation_time ( self ) : if self . revoked is False : return if timezone . is_aware ( self . revoked_date ) : # convert datetime object to UTC and make it naive return timezone . make_naive ( self . revoked_date , pytz . utc ) return self . revoked_date
Get the revocation time as naive datetime .
72
9
18,422
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 .
104
15
18,423
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 .
77
14
18,424
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 .
37
11
18,425
def valid ( self ) : now = timezone . now ( ) return self . filter ( revoked = False , expires__gt = now , valid_from__lt = now )
Return valid certificates .
37
4
18,426
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 ) # pylint: disable=exec-used return exec_locals [ '__version__' ]
Returns release version
136
3
18,427
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 .
36
11
18,428
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 .
71
11
18,429
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
105
8
18,430
def register ( linter ) : try : MANAGER . register_transform ( nodes . Class , rootlogger_transform ) except AttributeError : MANAGER . register_transform ( nodes . ClassDef , rootlogger_transform )
Register the transformation functions .
51
5
18,431
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
56
13
18,432
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
104
11
18,433
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
49
7
18,434
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' , } # For django 1.8, we have to load the libraries manually, and restore them once the template is rendered. _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 : # Django>1.8 Engine can load the extra templatetag libraries itself # but we have to override the default installed libraries. 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 ) ) # Restore the original TemplateBase.libraries if _libraries is not None : TemplateBase . libraries = _libraries return rendered
Evaluate a django template by resource path applying the provided context .
330
15
18,435
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
93
14
18,436
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 .
60
19
18,437
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 .
72
5
18,438
def merge_translation ( self , context ) : language = get_language ( ) i18n_service = context . get ( '_i18n_service' , None ) if i18n_service : # Cache the original translation object to reduce overhead if language not in self . _translations : self . _translations [ language ] = trans_real . DjangoTranslation ( language ) translation = trans_real . translation ( language ) translation . merge ( i18n_service ) yield # Revert to original translation object if language in self . _translations : trans_real . _translations [ language ] = self . _translations [ language ] # Re-activate the current language to reset translation caches trans_real . activate ( language )
Context wrapper which modifies the given language s translation catalog using the i18n service if found .
157
20
18,439
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 .
41
16
18,440
def studio_view ( self , context ) : fragment = Fragment ( ) context = { 'fields' : [ ] } # Build a list of all the fields that can be edited: 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
234
8
18,441
def validate ( self ) : validation = super ( StudioEditableXBlockMixin , self ) . validate ( ) self . validate_field_data ( validation , self ) return validation
Validates the state of this XBlock .
38
9
18,442
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 .
274
32
18,443
def author_view ( self , context ) : root_xblock = context . get ( 'root_xblock' ) if root_xblock and root_xblock . location == self . location : # User has clicked the "View" link. Show an editable preview of this block's children 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 .
86
33
18,444
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 .
43
21
18,445
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
59
51
18,446
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
57
19
18,447
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 .
172
8
18,448
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 ) : # html block doesn't support preview_view, and if we use student_view Studio will wrap # it in HTML that we don't want in the preview. So just render its HTML directly: child_fragment = Fragment ( child . data ) else : child_fragment = child . render ( 'student_view' , context ) return child_fragment
Helper method to overcome html block rendering quirks
159
8
18,449
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 .
90
13
18,450
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 .
75
16
18,451
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 .
63
26
18,452
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
75
17
18,453
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
106
18
18,454
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 .
102
19
18,455
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
152
6
18,456
def remove_attr ( self , attr ) : self . _stable = False self . attrs . pop ( attr , None ) return self
Removes an attribute .
31
5
18,457
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 .
134
16
18,458
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 .
63
19
18,459
def add_class ( self , cssclass ) : if self . has_class ( cssclass ) : return self return self . toggle_class ( cssclass )
Adds a css class to this element .
37
9
18,460
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 .
38
9
18,461
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 .
118
8
18,462
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
56
13
18,463
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 .
43
14
18,464
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 .
73
11
18,465
def render ( self , * args , * * kwargs ) : # args kwargs API provided for last minute content injection # self._reverse_mro_func('pre_render') 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 the tag or his contents are not changed and we already have rendered it # with the same attrs we skip all the work 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 "" # We declare the tag is stable and have an official render: 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 .
345
10
18,466
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 .
218
29
18,467
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 .
39
15
18,468
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
184
10
18,469
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
73
14
18,470
def _evaluate_tempyREPR ( self , child , repr_cls ) : score = 0 if repr_cls . __name__ == self . __class__ . __name__ : # One point if the REPR have the same name of the container score += 1 elif repr_cls . __name__ == self . root . __class__ . __name__ : # One point if the REPR have the same name of the Tempy tree root score += 1 # Add points defined in scorers methods of used TempyPlaces 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 .
206
35
18,471
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 : # If we find some TempyREPR, we return the one with the best score. 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 .
112
45
18,472
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
62
9
18,473
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
66
7
18,474
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
93
11
18,475
def render ( self , * args , * * kwargs ) : return self . doctype . render ( ) + super ( ) . render ( * args , * * kwargs )
Override so each html page served have a doctype
40
10
18,476
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 : # Fallback for no content (Raise NoContent?) return ""
Search for a content_name in the content data if not found the parent is searched .
68
18
18,477
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 .
47
14
18,478
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 .
32
11
18,479
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
50
15
18,480
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 : # Element insertion in this DOMElement childs self . childs . insert ( idx + i_group , elem ) # Managing child attributes if needed 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 .
205
63
18,481
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 .
43
7
18,482
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 .
33
12
18,483
def append ( self , _ , child , name = None ) : self . _insert ( child , name = name ) return self
Adds childs to this tag after the current existing childs .
27
13
18,484
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 .
64
9
18,485
def replace_with ( self , other ) : self . after ( other ) self . parent . pop ( self . _own_index ) return other
Replace this element with the given DOMElement .
31
11
18,486
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 .
36
8
18,487
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
116
10
18,488
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 .
72
12
18,489
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 .
219
9
18,490
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 .
139
8
18,491
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 ) # do not readd handlers if they are already present 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 .
215
7
18,492
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
137
10
18,493
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
53
6
18,494
def get_checks_paths ( checks_paths = None ) : p = os . path . join ( __file__ , os . pardir , os . pardir , os . pardir , "checks" ) p = os . path . abspath ( p ) # let's utilize the default upstream checks always if checks_paths : p += [ os . path . abspath ( x ) for x in checks_paths ] return [ p ]
Get path to checks .
97
5
18,495
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
197
7
18,496
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 .
133
5
18,497
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 .
86
12
18,498
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 .
78
9
18,499
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 .
111
15