idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
31,200
def has_content_in ( page , language ) : if page is None : return False return Content . objects . filter ( page = page , language = language ) . count ( ) > 0
Fitler that return True if the page has any content in a particular language .
31,201
def pages_menu ( context , page , url = '/' ) : lang = context . get ( 'lang' , pages_settings . PAGE_DEFAULT_LANGUAGE ) page = get_page_from_string_or_id ( page , lang ) if page : children = page . get_children_for_frontend ( ) context . update ( { 'children' : children , 'page' : page } ) return context
Render a nested list of all the descendents of the given page including this page .
31,202
def pages_sub_menu ( context , page , url = '/' ) : lang = context . get ( 'lang' , pages_settings . PAGE_DEFAULT_LANGUAGE ) page = get_page_from_string_or_id ( page , lang ) if page : root = page . get_root ( ) children = root . get_children_for_frontend ( ) context . update ( { 'children' : children , 'page' : page }...
Get the root page of the given page and render a nested list of all root s children pages . Good for rendering a secondary menu .
31,203
def show_content ( context , page , content_type , lang = None , fallback = True ) : return { 'content' : _get_content ( context , page , content_type , lang , fallback ) }
Display a content type from a page .
31,204
def show_absolute_url ( context , page , lang = None ) : if not lang : lang = context . get ( 'lang' , pages_settings . PAGE_DEFAULT_LANGUAGE ) page = get_page_from_string_or_id ( page , lang ) if not page : return { 'content' : '' } url = page . get_url_path ( language = lang ) if url : return { 'content' : url } retu...
Show the url of a page in the right language
31,205
def pages_dynamic_tree_menu ( context , page , url = '/' ) : lang = context . get ( 'lang' , pages_settings . PAGE_DEFAULT_LANGUAGE ) page = get_page_from_string_or_id ( page , lang ) children = None if page and 'current_page' in context : current_page = context [ 'current_page' ] if ( page . tree_id == current_page . ...
Render a dynamic tree menu with all nodes expanded which are either ancestors or the current page itself .
31,206
def pages_breadcrumb ( context , page , url = '/' ) : lang = context . get ( 'lang' , pages_settings . PAGE_DEFAULT_LANGUAGE ) page = get_page_from_string_or_id ( page , lang ) pages_navigation = None if page : pages_navigation = page . get_ancestors ( ) context . update ( { 'pages_navigation' : pages_navigation , 'pag...
Render a breadcrumb like menu .
31,207
def do_get_page ( parser , token ) : bits = token . split_contents ( ) if 4 != len ( bits ) : raise TemplateSyntaxError ( '%r expects 4 arguments' % bits [ 0 ] ) if bits [ - 2 ] != 'as' : raise TemplateSyntaxError ( '%r expects "as" as the second argument' % bits [ 0 ] ) page_filter = parser . compile_filter ( bits [ 1...
Retrieve a page and insert into the template s context .
31,208
def do_get_content ( parser , token ) : bits = token . split_contents ( ) if not 5 <= len ( bits ) <= 6 : raise TemplateSyntaxError ( '%r expects 4 or 5 arguments' % bits [ 0 ] ) if bits [ - 2 ] != 'as' : raise TemplateSyntaxError ( '%r expects "as" as the second last argument' % bits [ 0 ] ) page = parser . compile_fi...
Retrieve a Content object and insert it into the template s context .
31,209
def do_placeholder ( parser , token ) : name , params = parse_placeholder ( parser , token ) return PlaceholderNode ( name , ** params )
Method that parse the placeholder template tag .
31,210
def do_markdownlaceholder ( parser , token ) : name , params = parse_placeholder ( parser , token ) return MarkdownPlaceholderNode ( name , ** params )
Method that parse the markdownplaceholder template tag .
31,211
def do_fileplaceholder ( parser , token ) : name , params = parse_placeholder ( parser , token ) return FilePlaceholderNode ( name , ** params )
Method that parse the fileplaceholder template tag .
31,212
def do_page_has_content ( parser , token ) : nodelist = parser . parse ( ( 'end_page_has_content' , ) ) parser . delete_first_token ( ) args = token . split_contents ( ) try : content_type = unescape_string_literal ( args [ 1 ] ) except IndexError : raise template . TemplateSyntaxError ( "%r tag requires the argument c...
Conditional tag that only renders its nodes if the page has content for a particular content type . By default the current page is used .
31,213
def get_request_mock ( ) : from django . test . client import RequestFactory from django . core . handlers . base import BaseHandler factory = RequestFactory ( ) request = factory . get ( '/' ) class FakeUser ( ) : is_authenticated = False is_staff = False request . user = FakeUser ( ) request . session = { } return re...
Build a request mock up for tests
31,214
def remove_slug ( path ) : if path . endswith ( '/' ) : path = path [ : - 1 ] if path . startswith ( '/' ) : path = path [ 1 : ] if "/" not in path or not path : return None parts = path . split ( "/" ) [ : - 1 ] return "/" . join ( parts )
Return the remainin part of the path
31,215
def get_language_from_request ( request ) : language = request . GET . get ( 'language' , None ) if language : return language if hasattr ( request , 'LANGUAGE_CODE' ) : lang = settings . PAGE_LANGUAGE_MAPPING ( str ( request . LANGUAGE_CODE ) ) if lang not in LANGUAGE_KEYS : return settings . PAGE_DEFAULT_LANGUAGE els...
Return the most obvious language according the request .
31,216
def get_content ( self , page , language , ctype , language_fallback = False ) : if page is None : page = fake_page if " " in ctype : raise ValueError ( "Ctype cannot contain spaces." ) if not language : language = settings . PAGE_DEFAULT_LANGUAGE frozen = int ( bool ( page . freeze_date ) ) key = self . PAGE_CONTENT_D...
Gets the latest content string for a particular page language and placeholder .
31,217
def get_page_ids_by_slug ( self , slug ) : ids = self . filter ( type = 'slug' , body = slug ) . values ( 'page_id' ) . annotate ( max_creation_date = Max ( 'creation_date' ) ) return [ content [ 'page_id' ] for content in ids ]
Return all page s id matching the given slug . This function also returns pages that have an old slug that match .
31,218
def resolve_page ( self , request , context , is_staff ) : path = context [ 'path' ] lang = context [ 'lang' ] page = Page . objects . from_path ( path , lang , exclude_drafts = ( not is_staff ) ) if page : return page if not settings . PAGE_USE_STRICT_URL : path = remove_slug ( path ) while path is not None : page = P...
Return the appropriate page according to the path .
31,219
def resolve_redirection ( self , request , context ) : current_page = context [ 'current_page' ] lang = context [ 'lang' ] if current_page . redirect_to_url : return HttpResponsePermanentRedirect ( current_page . redirect_to_url ) if current_page . redirect_to : return HttpResponsePermanentRedirect ( current_page . red...
Check for redirections .
31,220
def choose_language ( self , lang , request ) : if not lang : lang = get_language_from_request ( request ) if lang not in [ key for ( key , value ) in settings . PAGE_LANGUAGES ] : raise Http404 if lang and translation . check_for_language ( lang ) : translation . activate ( lang ) return lang
Deal with the multiple corner case of choosing the language .
31,221
def extra_context ( self , request , context ) : if settings . PAGE_EXTRA_CONTEXT : context . update ( settings . PAGE_EXTRA_CONTEXT ( ) )
Call the PAGE_EXTRA_CONTEXT function if there is one .
31,222
def get_children ( self ) : key = self . CHILDREN_KEY % self . pk children = super ( Page , self ) . get_children ( ) return children
Cache superclass result
31,223
def move_to ( self , target , position = 'first-child' ) : self . invalidate ( ) target . invalidate ( ) super ( Page , self ) . move_to ( target , position = position )
Invalidate cache when moving
31,224
def get_content ( self , language , ctype , language_fallback = False ) : return Content . objects . get_content ( self , language , ctype , language_fallback )
Shortcut method for retrieving a piece of page content
31,225
def get_url_path ( self , language = None ) : if self . is_first_root ( ) : try : return reverse ( 'pages-root' ) except Exception : pass url = self . get_complete_slug ( language ) if not language : language = settings . PAGE_DEFAULT_LANGUAGE if settings . PAGE_USE_LANGUAGE_PREFIX : return reverse ( 'pages-details-by-...
Return the URL s path component . Add the language prefix if PAGE_USE_LANGUAGE_PREFIX setting is set to True .
31,226
def slug_with_level ( self , language = None ) : level = '' if self . level : for n in range ( 0 , self . level ) : level += '&nbsp;&nbsp;&nbsp;' return mark_safe ( level + self . slug ( language ) )
Display the slug of the page prepended with insecable spaces to simluate the level of page in the hierarchy .
31,227
def title ( self , language = None , fallback = True ) : if not language : language = settings . PAGE_DEFAULT_LANGUAGE return self . get_content ( language , 'title' , language_fallback = fallback )
Return the title of the page depending on the given language .
31,228
def unique_slug_required ( form , slug ) : if hasattr ( form , 'instance' ) and form . instance . id : if Content . objects . exclude ( page = form . instance ) . filter ( body = slug , type = "slug" ) . count ( ) : raise forms . ValidationError ( error_dict [ 'another_page_error' ] ) elif Content . objects . filter ( ...
Enforce a unique slug accross all pages and websistes .
31,229
def intersect_sites_method ( form ) : if settings . PAGE_USE_SITE_ID : if settings . PAGE_HIDE_SITES : site_ids = [ global_settings . SITE_ID ] else : site_ids = [ int ( x ) for x in form . data . getlist ( 'sites' ) ] def intersects_sites ( sibling ) : return sibling . sites . filter ( id__in = site_ids ) . count ( ) ...
Return a method to intersect sites .
31,230
def _has_changed ( self , initial , data ) : if data == initial : return False return bool ( initial ) != bool ( data )
Need to be reimplemented to be correct .
31,231
def update_redirect_to_from_json ( page , redirect_to_complete_slugs ) : messages = [ ] s = '' for lang , s in list ( redirect_to_complete_slugs . items ( ) ) : r = Page . objects . from_path ( s , lang , exclude_drafts = False ) if r : page . redirect_to = r page . save ( ) break else : messages . append ( _ ( "Could ...
The second pass of create_and_update_from_json_data used to update the redirect_to field .
31,232
def get_filename ( page , content_type , data ) : avoid_collision = uuid . uuid4 ( ) . hex [ : 8 ] name_parts = data . name . split ( '.' ) if len ( name_parts ) > 1 : name = slugify ( '.' . join ( name_parts [ : - 1 ] ) , allow_unicode = True ) ext = slugify ( name_parts [ - 1 ] ) name = name + '.' + ext else : name =...
Generate a stable filename using the original filename of the type .
31,233
def get_field ( self , page , language , initial = None ) : if self . parsed : help_text = _ ( 'Note: This field is evaluated as template code.' ) else : help_text = '' widget = self . get_widget ( page , language ) return self . field ( widget = widget , initial = initial , help_text = help_text , required = False )
The field that will be shown within the admin .
31,234
def render ( self , context ) : content = self . get_render_content ( context ) request = context . get ( 'request' ) render_edit_tag = False if request and request . user . is_staff and request . COOKIES . get ( 'enable_edit_mode' ) : render_edit_tag = True if not content : if not render_edit_tag : return '' return se...
Output the content of the PlaceholdeNode as a template .
31,235
def render ( self , context ) : import markdown content = self . get_content_from_context ( context ) return markdown . markdown ( content )
Render markdown .
31,236
def handle ( self , user , ** options ) : monkeypatch_remove_pages_site_restrictions ( ) user_model = get_user_model ( ) for match in ( 'username' , 'pk' , 'email' ) : try : u = user_model . objects . get ( ** { match : user } ) break except ( user_model . DoesNotExist , ValueError ) : continue else : raise CommandErro...
Import pages in JSON format . When creating a page and the original author does not exist use user as the new author . User may be specified by username id or email address .
31,237
def prepare ( value , should_escape ) : if value is None : return u'' type_ = type ( value ) if type_ is not strlist : if type_ is not str_class : if type_ is bool : value = u'true' if value else u'false' else : value = str_class ( value ) if should_escape : value = escape ( value ) return value
Prepares a value to be added to the result
31,238
def grow ( self , thing ) : if type ( thing ) == str_class : self . append ( thing ) elif type ( thing ) == str : self . append ( unicode ( thing ) ) else : for element in thing : self . grow ( element )
Make the list longer appending for unicode extending otherwise .
31,239
def _extract_word ( self , source , position ) : boundry = re . search ( '{{|{|\s|$' , source [ : position ] [ : : - 1 ] ) start_offset = boundry . end ( ) if boundry . group ( 0 ) . startswith ( '{' ) else boundry . start ( ) boundry = re . search ( '}}|}|\s|$' , source [ position : ] ) end_offset = boundry . end ( ) ...
Extracts the word that falls at or around a specific position
31,240
def compile ( self , source , path = None ) : container = self . _generate_code ( source ) def make_module_name ( name , suffix = None ) : output = 'pybars._templates.%s' % name if suffix : output += '_%s' % suffix return output if not path : path = '_template' generate_name = True else : path = path . replace ( '\\' ,...
Compile source to a ready to run template .
31,241
def clean_whitespace ( self , tree ) : pointer = 0 end = len ( tree ) while pointer < end : piece = tree [ pointer ] if piece [ 0 ] == 'block' : child_tree = piece [ 3 ] open_pre_whitespace = False open_pre_content = True if pointer > 1 and tree [ pointer - 1 ] [ 0 ] == 'whitespace' and ( tree [ pointer - 2 ] [ 0 ] == ...
Cleans up whitespace around block open and close tags if they are the only thing on the line
31,242
def _default_conflict_solver ( match , conflicting_match ) : if len ( conflicting_match . initiator ) < len ( match . initiator ) : return conflicting_match if len ( match . initiator ) < len ( conflicting_match . initiator ) : return match return None
Default conflict solver for matches shorter matches if they conflicts with longer ones
31,243
def call ( function , * args , ** kwargs ) : func = constructor_args if inspect . isclass ( function ) else function_args call_args , call_kwargs = func ( function , * args , ** kwargs ) return function ( * call_args , ** call_kwargs )
Call a function or constructor with given args and kwargs after removing args and kwargs that doesn t match function or constructor signature
31,244
def ensure_dict ( param , default_value , default_key = None ) : if not param : param = default_value if not isinstance ( param , dict ) : if param : default_value = param return { default_key : param } , default_value return param , default_value
Retrieves a dict and a default value from given parameter .
31,245
def filter_index ( collection , predicate = None , index = None ) : if index is None and isinstance ( predicate , int ) : index = predicate predicate = None if predicate : collection = collection . __class__ ( filter ( predicate , collection ) ) if index is not None : try : collection = collection [ index ] except Inde...
Filter collection with predicate function and index .
31,246
def load ( self , * rules ) : for rule in rules : if inspect . ismodule ( rule ) : self . load_module ( rule ) elif inspect . isclass ( rule ) : self . load_class ( rule ) else : self . append ( rule )
Load rules from a Rule module class or instance
31,247
def load_module ( self , module ) : for name , obj in inspect . getmembers ( module , lambda member : hasattr ( member , '__module__' ) and member . __module__ == module . __name__ and inspect . isclass ) : self . load_class ( obj )
Load a rules module
31,248
def execute_all_rules ( self , matches , context ) : ret = [ ] for priority , priority_rules in groupby ( sorted ( self ) , lambda rule : rule . priority ) : sorted_rules = toposort_rules ( list ( priority_rules ) ) for rules_group in sorted_rules : rules_group = list ( sorted ( rules_group , key = self . index ) ) gro...
Execute all rules from this rules list . All when condition with same priority will be performed before calling then actions .
31,249
def at_match ( self , match , predicate = None , index = None ) : return self . at_span ( match . span , predicate , index )
Retrieves a list of matches from given match .
31,250
def at_index ( self , pos , predicate = None , index = None ) : return filter_index ( self . _index_dict [ pos ] , predicate , index )
Retrieves a list of matches from given position
31,251
def children ( self ) : if self . _children is None : self . _children = Matches ( None , self . input_string ) return self . _children
Children matches .
31,252
def filter_match_kwargs ( kwargs , children = False ) : kwargs = kwargs . copy ( ) for key in ( 'pattern' , 'start' , 'end' , 'parent' , 'formatter' , 'value' ) : if key in kwargs : del kwargs [ key ] if children : for key in ( 'name' , ) : if key in kwargs : del kwargs [ key ] return kwargs
Filters out kwargs for Match construction
31,253
def chars_before ( chars , match ) : if match . start <= 0 : return True return match . input_string [ match . start - 1 ] in chars
Validate the match if left character is in a given sequence .
31,254
def chars_after ( chars , match ) : if match . end >= len ( match . input_string ) : return True return match . input_string [ match . end ] in chars
Validate the match if right character is in a given sequence .
31,255
def validators ( * chained_validators ) : def validator_chain ( match ) : for chained_validator in chained_validators : if not chained_validator ( match ) : return False return True return validator_chain
Creates a validator chain from several validator functions .
31,256
def build_re ( self , * pattern , ** kwargs ) : set_defaults ( self . _regex_defaults , kwargs ) set_defaults ( self . _defaults , kwargs ) return RePattern ( * pattern , ** kwargs )
Builds a new regular expression pattern
31,257
def build_string ( self , * pattern , ** kwargs ) : set_defaults ( self . _string_defaults , kwargs ) set_defaults ( self . _defaults , kwargs ) return StringPattern ( * pattern , ** kwargs )
Builds a new string pattern
31,258
def build_functional ( self , * pattern , ** kwargs ) : set_defaults ( self . _functional_defaults , kwargs ) set_defaults ( self . _defaults , kwargs ) return FunctionalPattern ( * pattern , ** kwargs )
Builds a new functional pattern
31,259
def chain ( self , ** kwargs ) : chain = self . build_chain ( ** kwargs ) self . _patterns . append ( chain ) return chain
Add patterns chain using configuration of this rebulk
31,260
def build_chain ( self , ** kwargs ) : set_defaults ( self . _chain_defaults , kwargs ) set_defaults ( self . _defaults , kwargs ) return Chain ( self , ** kwargs )
Builds a new patterns chain
31,261
def chain ( self ) : chain = self . rebulk . chain ( ** self . _kwargs ) chain . _defaults = dict ( self . _defaults ) chain . _regex_defaults = dict ( self . _regex_defaults ) chain . _functional_defaults = dict ( self . _functional_defaults ) chain . _string_defaults = dict ( self . _string_defaults ) return chain
Add patterns chain using configuration from this chain
31,262
def repeater ( self , value ) : try : value = int ( value ) self . repeater_start = value self . repeater_end = value return self except ValueError : pass if value == '+' : self . repeater_start = 1 self . repeater_end = None if value == '*' : self . repeater_start = 0 self . repeater_end = None elif value == '?' : sel...
Define the repeater of the current chain part .
31,263
def delete_attachment ( request , link_field = None , uri = None ) : if link_field is None : link_field = "record_uri" if uri is None : uri = record_uri ( request ) filters = [ Filter ( link_field , uri , core_utils . COMPARISON . EQ ) ] storage = request . registry . storage file_links , _ = storage . get_all ( "" , F...
Delete existing file and link .
31,264
def on_delete_record ( event ) : keep_old_files = asbool ( utils . setting_value ( event . request , 'keep_old_files' , default = False ) ) if keep_old_files : return resource_name = event . payload [ 'resource_name' ] filter_field = '%s_uri' % resource_name uri = event . payload [ 'uri' ] utils . delete_attachment ( e...
When a resource record is deleted delete all related attachments . When a bucket or collection is deleted it removes the attachments of every underlying records .
31,265
def preprocess_tree ( self , tree ) : visitor = RinohTreePreprocessor ( tree , self ) tree . walkabout ( visitor )
Transform internal refuri targets in reference nodes to refids and transform footnote rubrics so that they do not end up in the output
31,266
def _vertically_size_cells ( rendered_rows ) : for r , rendered_row in enumerate ( rendered_rows ) : for rendered_cell in rendered_row : if rendered_cell . rowspan > 1 : row_height = sum ( row . height for row in rendered_rows [ r : r + rendered_cell . rowspan ] ) extra_height_needed = rendered_cell . height - row_heig...
Grow row heights to cater for vertically spanned cells that do not fit in the available space .
31,267
def _place_rows_and_render_borders ( container , rendered_rows ) : def draw_cell_border ( rendered_cell , cell_height , container ) : cell_width = rendered_cell . width background = TableCellBackground ( ( 0 , 0 ) , cell_width , cell_height , parent = rendered_cell . cell ) background . render ( container ) for positio...
Place the rendered cells onto the page canvas and draw borders around them .
31,268
def get_rowspanned_columns ( self ) : spanned_columns = { } current_row_index = self . _index current_row_cols = sum ( cell . colspan for cell in self ) prev_rows = iter ( reversed ( self . section [ : current_row_index ] ) ) while current_row_cols < self . section . num_columns : row = next ( prev_rows ) min_rowspan =...
Return a dictionary mapping column indices to the number of columns spanned .
31,269
def romanize ( number ) : roman = [ ] for numeral , value in NUMERALS : times , number = divmod ( number , value ) roman . append ( times * numeral ) return '' . join ( roman )
Convert number to a Roman numeral .
31,270
def render ( self , type , rerender = False ) : for child in self . children : child . render ( type , rerender )
Render the contents of this container to its canvas .
31,271
def place ( self ) : self . place_children ( ) self . canvas . append ( self . parent . canvas , float ( self . left ) , float ( self . top ) )
Place this container s canvas onto the parent container s canvas .
31,272
def advance2 ( self , height , ignore_overflow = False ) : if height <= self . remaining_height : self . _self_cursor . grow ( height ) elif ignore_overflow : self . _self_cursor . grow ( float ( self . remaining_height ) ) else : return False return True
Advance the cursor by height . Returns True on success .
31,273
def render ( self , container , rerender = False ) : if rerender : container . clear ( ) if not self . _rerendering : self . _state = copy ( self . _fresh_page_state ) self . _rerendering = True try : self . done = False self . flowables . flow ( container , last_descender = None , state = self . _state ) if container ...
Flow the flowables into the containers that have been added to this chain .
31,274
def _get_default ( cls , attribute ) : try : for klass in cls . __mro__ : if attribute in klass . _attributes : return klass . _attributes [ attribute ] . default_value except AttributeError : raise KeyError ( "No attribute '{}' in {}" . format ( attribute , cls ) )
Return the default value for attribute .
31,275
def get_pygments_style ( style ) : if isinstance ( style , StyleMeta ) : return style if '.' in style : module , name = style . rsplit ( '.' , 1 ) return getattr ( __import__ ( module , None , None , [ '__name__' ] ) , name ) else : if style == 'sphinx' : from sphinx . pygments_styles import SphinxStyle return SphinxSt...
Retrieve a Pygments style by name by import path or if style is already Pygments style simply return it .
31,276
def flow ( self , container , last_descender , state = None , ** kwargs ) : top_to_baseline = 0 state = state or self . initial_state ( container ) if state . initial : space_above = self . get_style ( 'space_above' , container ) if not container . advance2 ( float ( space_above ) ) : raise EndOfContainer ( state ) top...
Flow this flowable into container and return the vertical space consumed .
31,277
def entry_point_name_to_identifier ( entry_point_name ) : try : entry_point_name . encode ( 'ascii' ) ascii_name = entry_point_name except UnicodeEncodeError : ascii_name = entry_point_name . encode ( 'punycode' ) . decode ( 'ascii' ) return '' . join ( char for char in ascii_name if char in string . ascii_lowercase + ...
Transform an entry point name into an identifier suitable for inclusion in a PyPI package name .
31,278
def render ( self , container , descender , state , space_below = 0 , first_line_only = False ) : indent_first = ( float ( self . get_style ( 'indent_first' , container ) ) if state . initial else 0 ) line_width = float ( container . width ) line_spacing = self . get_style ( 'line_spacing' , container ) text_align = se...
Typeset the paragraph
31,279
def typeset ( self , container , text_align , last_line = False ) : document = container . document while len ( self ) > 0 : last_span = self [ - 1 ] if last_span and last_span . ends_with_space : self . cursor -= last_span . space . width self . pop ( ) else : break else : return for glyph_span in self : glyph_span . ...
Typeset the line in container below its current cursor position . Advances the container s cursor to below the descender of this line .
31,280
def create_destination ( flowable , container , at_top_of_container = False ) : vertical_position = 0 if at_top_of_container else container . cursor ids = flowable . get_ids ( container . document ) destination = NamedDestination ( * ( str ( id ) for id in ids ) ) container . canvas . annotate ( destination , 0 , verti...
Create a destination anchor in the container to direct links to flowable to .
31,281
def source ( self ) : if self . _source is not None : return self . _source elif self . parent is not None : return self . parent . source else : return Location ( self )
The source element this document element was created from .
31,282
def prepare ( self , flowable_target ) : if self . get_id ( flowable_target . document , create = False ) : flowable_target . document . register_element ( self )
Determine number labels and register references with the document
31,283
def warn ( self , message , container = None ) : if self . source is not None : message = '[{}] ' . format ( self . source . location ) + message if container is not None : try : message += ' (page {})' . format ( container . page . formatted_number ) except AttributeError : pass warn ( message )
Present the warning message to the user adding information on the location of the related element in the input file .
31,284
def all_subclasses ( cls ) : for subcls in cls . __subclasses__ ( ) : yield subcls for subsubcls in all_subclasses ( subcls ) : yield subsubcls
Generator yielding all subclasses of cls recursively
31,285
def intersperse ( iterable , element ) : iterable = iter ( iterable ) yield next ( iterable ) while True : next_from_iterable = next ( iterable ) yield element yield next_from_iterable
Generator yielding all elements of iterable but with element inserted between each two consecutive elements
31,286
def unique ( iterable ) : seen = set ( ) for item in iterable : if item not in seen : seen . add ( item ) yield item
Filter out duplicate items from an iterable
31,287
def cached ( function ) : cache_variable = '_cached_' + function . __name__ @ wraps ( function ) def function_wrapper ( obj , * args , ** kwargs ) : try : cache = getattr ( obj , cache_variable ) except AttributeError : cache = { } setattr ( obj , cache_variable , cache ) args_kwargs = args + tuple ( kwargs . values ( ...
Method decorator caching a method s returned values .
31,288
def cached_generator ( function ) : cache_variable = '_cached_' + function . __name__ @ wraps ( function ) def function_wrapper ( obj , * args , ** kwargs ) : try : for item in getattr ( obj , cache_variable ) : yield item except AttributeError : setattr ( obj , cache_variable , [ ] ) cache = getattr ( obj , cache_vari...
Method decorator caching a generator s yielded items .
31,289
def timed ( function ) : @ wraps ( function ) def function_wrapper ( obj , * args , ** kwargs ) : name = obj . __class__ . __name__ + '.' + function . __name__ start = time . clock ( ) result = function ( obj , * args , ** kwargs ) print ( '{}: {:.4f} seconds' . format ( name , time . clock ( ) - start ) ) return resul...
Decorator timing the method call and printing the result to stdout
31,290
def positions ( self , word ) : right = len ( word ) - self . right return [ i for i in self . hd . positions ( word ) if self . left <= i <= right ]
Returns a list of positions where the word can be hyphenated . See also Hyph_dict . positions . The points that are too far to the left or right are removed .
31,291
def iterate ( self , word ) : for p in reversed ( self . positions ( word ) ) : if p . data : change , index , cut = p . data if word . isupper ( ) : change = change . upper ( ) c1 , c2 = change . split ( '=' ) yield word [ : p + index ] + c1 , c2 + word [ p + index + cut : ] else : yield word [ : p ] , word [ p : ]
Iterate over all hyphenation possibilities the longest first .
31,292
def wrap ( self , word , width , hyphen = '-' ) : width -= len ( hyphen ) for w1 , w2 in self . iterate ( word ) : if len ( w1 ) <= width : return w1 + hyphen , w2
Return the longest possible first part and the last part of the hyphenated word . The first part has the hyphen already attached . Returns None if there is no hyphenation point before width or if the word could not be hyphenated .
31,293
def inserted ( self , word , hyphen = '-' ) : l = list ( word ) for p in reversed ( self . positions ( word ) ) : if p . data : change , index , cut = p . data if word . isupper ( ) : change = change . upper ( ) l [ p + index : p + index + cut ] = change . replace ( '=' , hyphen ) else : l . insert ( p , hyphen ) retur...
Returns the word as a string with all the possible hyphens inserted . E . g . for the dutch word lettergrepen this method returns the string let - ter - gre - pen . The hyphen string to use can be given as the second parameter that defaults to - .
31,294
def render ( self , filename_root = None , file = None ) : self . error = False filename_root = Path ( filename_root ) if filename_root else None if filename_root and file is None : extension = self . backend_document . extension filename = filename_root . with_suffix ( extension ) file = filename . open ( 'wb' ) elif ...
Render the document repeatedly until the output no longer changes due to cross - references that need some iterations to converge .
31,295
def create_outlines ( self ) : sections = parent = [ ] current_level = 1 stack = [ ] fake_container = FakeContainer ( self ) for section in self . _sections : if not section . show_in_toc ( fake_container ) : continue section_id = section . get_id ( self , create = False ) section_number = self . get_reference ( sectio...
Create an outline in the output file that allows for easy navigation of the document . The outline is a hierarchical tree of all the sections in the document .
31,296
def _render_pages ( self ) : self . style_log = StyleLog ( self . stylesheet ) self . floats = set ( ) self . placed_footnotes = set ( ) self . _start_time = time . time ( ) part_page_counts = { } part_page_count = PartPageCount ( ) last_number_format = None for part_template in self . part_templates : part = part_temp...
Render the complete document once and return the number of pages rendered .
31,297
def htmlhelp ( ) : build ( 'htmlhelp' , 'Now you can run HTML Help Workshop with the .hhp ' 'project file in {}.' ) print ( 'Running HTML Help Workshop...' ) builddir = os . path . join ( BUILDDIR , 'htmlhelp' ) rc = subprocess . call ( [ 'hhc' , os . path . join ( builddir , 'rinohtype.hhp' ) ] ) if rc != 1 : print ( ...
make HTML files and a HTML help project
31,298
def latexpdf ( ) : rc = latex ( ) print ( 'Running LaTeX files through pdflatex...' ) builddir = os . path . join ( BUILDDIR , 'latex' ) subprocess . call ( [ 'make' , '-C' , builddir , 'all-pdf' ] ) print ( 'pdflatex finished; the PDF files are in {}.' . format ( builddir ) )
make LaTeX files and run them through pdflatex
31,299
def info ( ) : rc = texinfo ( ) print ( 'Running Texinfo files through makeinfo...' ) builddir = os . path . join ( BUILDDIR , 'texinfo' ) subprocess . call ( [ 'make' , '-C' , builddir , 'info' ] ) print ( 'makeinfo finished; the Info files are in {}.' . format ( builddir ) )
make Texinfo files and run them through makeinfo