Returns a new Summary with the article at the given level, with
subsequent article shifted.

@param {Summary} summary
@param {Article} article
@param {String|Article} level: level to insert at
@return {Summary}
185774
function insertArticle(summary, article, level) {
    article = SummaryArticle(article);
    level = is.string(level)? level : level.getLevel();

    var parent = summary.getParent(level);
    if (!parent) {
        return summary;
    }

    // Find the index to insert at
    var articles = parent.getArticles();
    var index = getLeafIndex(level);

    // Insert the article at the right index
    articles = articles.insert(index, article);

    // Reindex the level from here
    parent = parent.set('articles', articles);
    parent = indexArticleLevels(parent);

    return mergeAtLevel(summary, parent.getLevel(), parent);
}
729156
def write_title(self, title, level=1, id=None):
        
        if id:
            self.write('<h{lv} id="{id}">{title}</h{lv}>',
                       title=title, lv=level, id=id)
        else:
            self.write('<h{lv}>{title}</h{lv}>',
                       title=title, lv=level)
484456
def add(level, id, text)
      if level == @min_level
        @items << GuideTocEntry.new(self)
        @items.last.label = "#{prefix} <a href='#!/guide/#{id}'>#{text}</a>\n"
      else
        if @items.empty?
          @items << GuideTocEntry.new(self)
        end
        @items.last.add(level-1, id, text)
      end
    end
34411
def process_summary(article):
    """"""

    summary = article.summary
    summary_parsed = BeautifulSoup(summary, 'html.parser')
    math = summary_parsed.find_all(class_='math')

    if len(math) > 0:
        last_math_text = math[-1].get_text()
        if len(last_math_text) > 3 and last_math_text[-3:] == '...':
            content_parsed = BeautifulSoup(article._content, 'html.parser')
            full_text = content_parsed.find_all(class_='math')[len(math)-1].get_text()
            math[-1].string = "%s ..." % full_text
            summary = summary_parsed.decode()

        # clear memoization cache
        import functools
        if isinstance(article.get_summary, functools.partial):
            memoize_instance = article.get_summary.func.__self__
            memoize_instance.cache.clear()

        article._summary = "%s<script type='text/javascript'>%s</script>" % (summary, process_summary.mathjax_script)
705665
function _populateArticleInfo (doc, jats, jatsImporter) {
  let articleEl = jats.find('article')
  let articleMetaEl = articleEl.find('front > article-meta')
  let metadata = doc.get('metadata')
  Object.assign(metadata, {
    articleType: articleEl.getAttribute('article-type') || '',
    elocationId: getText(articleMetaEl, 'elocation-id'),
    fpage: getText(articleMetaEl, 'fpage'),
    lpage: getText(articleMetaEl, 'lpage'),
    issue: getText(articleMetaEl, 'issue'),
    volume: getText(articleMetaEl, 'volume'),
    pageRange: getText(articleMetaEl, 'page-range')
  })
  let issueTitleEl = findChild(articleMetaEl, 'issue-title')
  if (issueTitleEl) {
    metadata['issueTitle'] = jatsImporter.annotatedText(issueTitleEl, ['metadata', 'issueTtle'])
  }
  // Import permission if present
  const permissionsEl = articleMetaEl.find('permissions')
  // An empty permission is already there, but will be replaced if <permission> element is there
  if (permissionsEl) {
    doc.delete(metadata.permission)
    let permission = jatsImporter.convertElement(permissionsEl)
    // ATTENTION: so that the document model is correct we need to use
    // the Document API  to set the permission id
    metadata.permission = permission.id
  }

  const articleDateEls = articleMetaEl.findAll('history > date, pub-date')
  if (articleDateEls.length > 0) {
    let dates = {}
    articleDateEls.forEach(dateEl => {
      const date = _extractDate(dateEl)
      dates[date.type] = date.value
    })
    Object.assign(metadata, dates)
  }
}
1209067
function getLevel(levelConfig) {
  const level = loadLevel(levelConfig);
  return JSON.parse(JSON.stringify(level));
}
1212890
function (level, x, y) {
            var url = null;
            if (level >= this.minLevel && level <= this.maxLevel) {
                url = this.levels[level].url;
            }
            return url;
        }
567594
def load_descendant_articles_for_section(
        context, section, featured_in_homepage=None, featured_in_section=None,
        featured_in_latest=None, count=5):
    
    request = context.get('request')
    locale = context.get('locale_code')
    page = section.get_main_language_page()
    settings = SiteSettings.for_site(request.site) \
        if request else None

    qs = ArticlePage.objects.descendant_of(page).filter(
        language__is_main_language=True)

    article_ordering = settings \
        and settings.article_ordering_within_section

    cms_ordering = article_ordering \
        and settings.article_ordering_within_section !=\
        ArticleOrderingChoices.CMS_DEFAULT_SORTING

    if article_ordering and cms_ordering:
        order_by = ArticleOrderingChoices.\
            get(settings.article_ordering_within_section).name.lower()

        order_by = order_by if order_by.find('_desc') == -1 \
            else '-{}'.format(order_by.replace('_desc', ''))
        qs = qs.order_by(order_by)

    if featured_in_homepage is not None:
        qs = qs.filter(featured_in_homepage=featured_in_homepage)\
            .order_by('-featured_in_homepage_start_date')

    if featured_in_latest is not None:
        qs = qs.filter(featured_in_latest=featured_in_latest)

    if featured_in_section is not None:
        qs = qs.filter(featured_in_section=featured_in_section)\
            .order_by('-featured_in_section_start_date')

    if not locale:
        return qs.live()[:count]

    return get_pages(context, qs, locale)[:count]
808104
function removePart(summary, index) {
    var parts = summary.getParts().remove(index);
    return indexLevels(summary.set('parts', parts));
}
1288493
function updateReport() {
				var nodeIndex = getNodeIndex({}, structureJson);
			
				var treeOptions = {
					"plugins" : [ "themes", "json_data", "ui", "cookies", "contextmenu" ],
          "core" : {
            "html_titles" : true
          },
					"cookies" : {
						"save_opened" : $report.attr("id")+"_opened"
					},
					"contextmenu" : {
						"select_node" : true,
						"items" : contextMenuHandler
					},
					"json_data" : {
						"progressive_render" : true,
						"progressive_unload" : true,
						"data" : dataHandler
          }
				};
				$report.jstree(treeOptions)
				.on("loaded.jstree", function(event, data) {
					$cukeTree.cukeTree().reportRendered($report);
				})
				.on("select_node.jstree", function(event, data) {
					var $node = $(data.args[0]);
					$cukeTree.cukeTree().reportNodeSelected({ $report : $report, selected : $node });
				});	
        
        function dataHandler(item, callback) {
          var data = null;
          if (item === -1) {
            data = [getTreeNode("group", structureJson)];
          } else {
            data = getTreeNodeChildren($(item).attr("id"));
          }
          callback(data);
        }
        
        function getTreeNodeChildren(id) {
          var data = [];
          var parent = nodeIndex[id];
          if (parent.children !== undefined) {
            for(var i=0; i<parent.children.length; i++) { data.push(getTreeNode("group", parent.children[i])); }
          }
          if (parent.features !== undefined) {
            for(var i=0; i<parent.features.length; i++) { data.push(getTreeNode("feature", parent.features[i])); }
          }
          if (parent.elements !== undefined) {
            for(var i=0; i<parent.elements.length; i++) { data.push(getTreeNode("scenario", parent.elements[i])); }
          }
          if (parent.steps !== undefined) {
            for(var i=0; i<parent.steps.length; i++) { data.push(getTreeNode("step", parent.steps[i])); }
          }
          return data;
        }
        
        function getTreeNode(type, reportEntry) {
          var cssClasses = "node-"+ reportEntry.result.status;
          cssClasses += " "+ type +" "+ type +"-"+ reportEntry.result.status;
          
          var title = reportEntry.name;
          switch(type) {
            case "group": 
              title += " ("+ getScenarioCount(type, reportEntry) +" scenario(s))"; 
              break;
            case "feature":
              var scenarioCount = reportEntry.elements !== undefined ? reportEntry.elements.length : 0;
              if (reportEntry.profile !== undefined) {
                title += " <span class='profile'>["+ reportEntry.profile +"]</span>";
              }
              title += " ("+ scenarioCount +" scenario(s))"
              break;
            case "scenario":
              for(var i=0; i < (reportEntry.tags !== undefined ? reportEntry.tags.length : 0); i++) {
                title += " <span class='scenario-tag'>"+ reportEntry.tags[i].name +"</span>";
              }
              break;
            case "step":
              title = '<span class="keyword">'+ reportEntry.keyword +'</span>'+ title;
              break;
          }
          
          var addingChildren = reportEntry.result && reportEntry.result.status == "failed";
                  
          var node = {
            attr : { 
              id : reportEntry.nodeId,
              "data-type" : type, 
              class : cssClasses
            },
            state : addingChildren && type !== "step" ? "open" : "closed",
            data : {
              attr : { 
                href : "javascript:;", 
                "data-path" : reportEntry.uri
              },
              title : title,
              icon : type
            }
          };
          
          if (addingChildren) {
            node.children = getTreeNodeChildren(reportEntry.nodeId);
          }
          
          if (reportEntry.result.error_message !== undefined) {
            node.attr["data-error"] = reportEntry.result.error_message;
          }
          
          if (reportEntry.embeddings !== undefined) {
            node.attr["data-embedding-mime-type"] = reportEntry.embeddings[0].mime_type;
            node.attr["data-embedding-data"] = reportEntry.embeddings[0].data;
          }
          
          return node;
        }
			}
676101
function insertPastedContent(node, content, overwrite) {
		var nodesWithPlaceholders = node.findAll(function(item) {
			return hasOutputPlaceholder(item);
		});
		
		if (hasOutputPlaceholder(node))
			nodesWithPlaceholders.unshift(node);
		
		if (nodesWithPlaceholders.length) {
			nodesWithPlaceholders.forEach(function(item) {
				item.content = replaceOutputPlaceholders(item.content, content);
				item._attributes.forEach(function(attr) {
					attr.value = replaceOutputPlaceholders(attr.value, content);
				});
			});
		} else {
			// on output placeholders in subtree, insert content in the deepest
			// child node
			var deepest = node.deepestChild() || node;
			if (overwrite) {
				deepest.content = content;
			} else {
				deepest.content = abbrUtils.insertChildContent(deepest.content, content);
			}
		}
	}
775441
function(item) {
        var geometry = this.createGeometryFromItem(item);
     
        /* Provide defaults for title and description */
        var title = this._getChildValue(item, "*", "title", this.featureTitle);
       
        /* First try RSS descriptions, then Atom summaries */
        var description = this._getChildValue(
            item, "*", "description",
            this._getChildValue(item, "*", "content",
                this._getChildValue(item, "*", "summary", this.featureDescription)));

        /* If no link URL is found in the first child node, try the
           href attribute */
        var link = this._getChildValue(item, "*", "link");
        if(!link) {
            try {
                link = this.getElementsByTagNameNS(item, "*", "link")[0].getAttribute("href");
            } catch(e) {
                link = null;
            }
        }

        var id = this._getChildValue(item, "*", "id", null);
        
        var data = {
            "title": title,
            "description": description,
            "link": link
        };
        var feature = new OpenLayers.Feature.Vector(geometry, data);
        feature.fid = id;
        return feature;
    }
1368174
function( element, level )
				{
					level = typeof level == 'number' ? level : 1;

					var	attrs = element.attributes,
						listStyleType;

					// All list items are of the same type.
					switch ( attrs.type )
					{
						case 'a' :
							listStyleType = 'lower-alpha';
							break;
						case '1' :
							listStyleType = 'decimal';
							break;
						// TODO: Support more list style type from MS-Word.
					}

					var children = element.children,
						child;

					for ( var i = 0; i < children.length; i++ )
					{
						child = children[ i ];

						if ( child.name in CKEDITOR.dtd.$listItem )
						{
							var attributes = child.attributes,
								listItemChildren = child.children,
								count = listItemChildren.length,
								last = listItemChildren[ count - 1 ];

							// Move out nested list.
							if ( last.name in CKEDITOR.dtd.$list )
							{
								element.add( last, i + 1 );

								// Remove the parent list item if it's just a holder.
								if ( !--listItemChildren.length )
									children.splice( i--, 1 );
							}

							child.name = 'cke:li';

							// Inherit numbering from list root on the first list item.
							attrs.start && !i && ( attributes.value = attrs.start );

							plugin.filters.stylesFilter(
								[
									[ 'tab-stops', null, function( val )
									{
										var margin = val.split( ' ' )[ 1 ].match( cssLengthRelativeUnit );
										margin && ( previousListItemMargin = CKEDITOR.tools.convertToPx( margin[ 0 ] ) );
									} ],
									( level == 1 ? [ 'mso-list', null, function( val )
									{
										val = val.split( ' ' );
										var listId = Number( val[ 0 ].match( /\d+/ ) );
										listId !== previousListId && ( attributes[ 'cke:reset' ] = 1 );
										previousListId = listId;
									 } ] : null )
								] )( attributes.style );

							attributes[ 'cke:indent' ] = level;
							attributes[ 'cke:listtype' ] = element.name;
							attributes[ 'cke:list-style-type' ] = listStyleType;
						}
						// Flatten sub list.
						else if ( child.name in CKEDITOR.dtd.$list )
						{
							// Absorb sub list children.
							arguments.callee.apply( this, [ child, level + 1 ] );
							children = children.slice( 0, i ).concat( child.children ).concat( children.slice( i + 1 ) );
							element.children = [];
							for ( var j = 0, num = children.length; j < num ; j++ )
								element.add( children[ j ] );
						}
					}

					delete element.name;

					// We're loosing tag name here, signalize this element as a list.
					attrs[ 'cke:list' ] = 1;
				}
579239
function editArticleInList(articles, level, newArticle) {
    return articles.map(function(article) {
        var articleLevel = article.getLevel();

        if (articleLevel === level) {
            // it is the article to edit
            return article.merge(newArticle);
        } else if (level.indexOf(articleLevel) === 0) {
            // it is a parent
            var articles = editArticleInList(article.getArticles(), level, newArticle);
            return article.set('articles', articles);
        } else {
            // This is not the article you are looking for
            return article;
        }
    });
}
1108882
function (levels, fn) {
    return function (label, val) {
        for (var i = 0; i < levels.length; i++) {
            if (levels[i] === exports.level) {
                return fn(label, val);
            }
        }
    };
}
1116213
function LevelTable(levelDb, options) {
  if (!(this instanceof LevelTable)) return new LevelTable(levelDb, options)
  if (!levelDb) throw new Error("I need a levelDb!")
  var db = sublevel(levelDb)
  this.db = db.sublevel(options.prefix || "levelThrottle")
}
382331
def insert_read_more_link(instance):
    

    # only deals with Article type
    if type(instance) != contents.Article: return


    SUMMARY_MAX_LENGTH = instance.settings.get('SUMMARY_MAX_LENGTH')
    READ_MORE_LINK = instance.settings.get('READ_MORE_LINK', None)
    READ_MORE_LINK_FORMAT = instance.settings.get('READ_MORE_LINK_FORMAT',
                                                  '<a class="read-more" href="/{url}">{text}</a>')

    if not (SUMMARY_MAX_LENGTH and READ_MORE_LINK and READ_MORE_LINK_FORMAT): return

    if hasattr(instance, '_summary') and instance._summary:
        summary = instance._summary
    else:
        summary = truncate_html_words(instance.content, SUMMARY_MAX_LENGTH)

    if summary != instance.content:
        read_more_link = READ_MORE_LINK_FORMAT.format(url=instance.url, text=READ_MORE_LINK)
        instance._summary = insert_into_last_element(summary, read_more_link)