<disp-formula> elements must be converted to conforming elements
353008
def convert_disp_formula_elements(self):
        
        for disp in self.main.getroot().findall('.//disp-formula'):
            #find label element
            label_el = disp.find('label')
            graphic_el = disp.find('graphic')
            if graphic_el is None:  # No graphic, assume math as text instead
                text_span = etree.Element('span', {'class': 'disp-formula'})
                if 'id' in disp.attrib:
                    text_span.attrib['id'] = disp.attrib['id']
                append_all_below(text_span, disp)
                #Insert the text span before the disp-formula
                insert_before(disp, text_span)
                #If a label exists, modify and insert before text_span
                if label_el is not None:
                    label_el.tag = 'b'
                    insert_before(text_span, label_el)
                #Remove the disp-formula
                remove(disp)
                #Skip the rest, which deals with the graphic element
                continue
            #The graphic element is present
            #Create a file reference for the image
            xlink_href = ns_format(graphic_el, 'xlink:href')
            graphic_xlink_href = graphic_el.attrib[xlink_href]
            file_name = graphic_xlink_href.split('.')[-1] + '.png'
            img_dir = 'images-' + self.doi_suffix()
            img_path = '/'.join([img_dir, file_name])

            #Create the img element
            img_element = etree.Element('img', {'alt': 'A Display Formula',
                                                'class': 'disp-formula',
                                                'src': img_path})
            #Transfer the id attribute
            if 'id' in disp.attrib:
                img_element.attrib['id'] = disp.attrib['id']
            #Insert the img element
            insert_before(disp, img_element)
            #Create content for the label
            if label_el is not None:
                label_el.tag = 'b'
                insert_before(img_element, label_el)
            #Remove the old disp-formula element
            remove(disp)
726605
function convertShape (shape, tag) {
  return templates.element({
    'tag': tag,
    'width': shape.width,
    'height': shape.height,
    'fill': shape.properties.fill
  });
}
654245
function parseFunctionSourceElements() {
        var statement, body = [], token, directive, firstRestricted,
            oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesisCount,
            node = new Node();

        expect('{');

        while (startIndex < length) {
            if (lookahead.type !== Token.StringLiteral) {
                break;
            }
            token = lookahead;

            statement = parseStatementListItem();
            body.push(statement);
            if (statement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = source.slice(token.start + 1, token.end - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    tolerateUnexpectedToken(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }

        oldLabelSet = state.labelSet;
        oldInIteration = state.inIteration;
        oldInSwitch = state.inSwitch;
        oldInFunctionBody = state.inFunctionBody;
        oldParenthesisCount = state.parenthesizedCount;

        state.labelSet = {};
        state.inIteration = false;
        state.inSwitch = false;
        state.inFunctionBody = true;
        state.parenthesizedCount = 0;

        while (startIndex < length) {
            if (match('}')) {
                break;
            }
            body.push(parseStatementListItem());
        }

        expect('}');

        state.labelSet = oldLabelSet;
        state.inIteration = oldInIteration;
        state.inSwitch = oldInSwitch;
        state.inFunctionBody = oldInFunctionBody;
        state.parenthesizedCount = oldParenthesisCount;

        return node.finishBlockStatement(body);
    }
146664
function convertDomToJyt(dom) {
    var i, elems, tempElem;

    // if just one element in the array, bump it up a level
    if (utils.isArray(dom) && dom.length === 1) {
        dom = dom[0];
    }
    // if multiple, then we create a sibling array of elems and return it
    else if (utils.isArray(dom)) {
        elems = [];
        for (i = 0; i < dom.length; i++) {
            tempElem = convertDomToJyt(dom[i]);
            if (tempElem !== null) {
                elems.push(tempElem);
            }
        }

        return runtime.naked(elems, null);
    }

    // if type is string, then just return it
    if (dom.type === 'text') {
        return dom.data;
    }
    // if no dom name, then just return empty string since it is likely a comment
    if (!dom.name) {
        return null;
    }

    // if we get here then we have just one element
    var elem = runtime.elem(dom.name);
    var childCount = dom.children && dom.children.length;

    // attributes should be the same
    elem.attributes = dom.attribs;

    // recursively add children
    if (dom.children && dom.children.length) {
        elem.children = [];
        for (i = 0; i < childCount; i++) {
            tempElem = convertDomToJyt(dom.children[i]);
            if (tempElem !== null) {
                elem.children.push(tempElem);
            }
        }

        // if one child that is a string, bring it up a level
        if (elem.children.length === 1 && utils.isString(elem.children[0])) {
            elem.text = elem.children[0];
            delete elem.children;
        }
        // if no children, remove it
        else if (elem.children.length === 0) {
            delete elem.children;
        }
    }

    return elem;
}
933596
function( value, element, param ) {
			if ( this.optional(element) ) {
				return "dependency-mismatch";
			}

			var previous = this.previousValue(element),
				validator, data;

			if (!this.settings.messages[element.name] ) {
				this.settings.messages[element.name] = {};
			}
			previous.originalMessage = this.settings.messages[element.name].remote;
			this.settings.messages[element.name].remote = previous.message;

			param = typeof param === "string" && { url: param } || param;

			if ( previous.old === value ) {
				return previous.valid;
			}

			previous.old = value;
			validator = this;
			this.startRequest(element);
			data = {};
			data[element.name] = value;
			$.ajax($.extend(true, {
				url: param,
				mode: "abort",
				port: "validate" + element.name,
				dataType: "json",
				data: data,
				context: validator.currentForm,
				success: function( response ) {
					var valid = response === true || response === "true",
						errors, message, submitted;

					validator.settings.messages[element.name].remote = previous.originalMessage;
					if ( valid ) {
						submitted = validator.formSubmitted;
						validator.prepareElement(element);
						validator.formSubmitted = submitted;
						validator.successList.push(element);
						delete validator.invalid[element.name];
						validator.showErrors();
					} else {
						errors = {};
						message = response || validator.defaultMessage( element, "remote" );
						errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message;
						validator.invalid[element.name] = true;
						validator.showErrors(errors);
					}
					previous.valid = valid;
					validator.stopRequest(element, valid);
				}
			}, param));
			return "pending";
		}
581794
function convertRules (config) {
  const result = {}

  const eslintRules = new CLIEngine({
    useEslintrc: false,
    baseConfig: {
      extends: [require.resolve(`@vue/eslint-config-${config}`)]
    }
  }).getConfigForFile().rules

  const getRuleOptions = (ruleName, defaultOptions = []) => {
    const ruleConfig = eslintRules[ruleName]

    if (!ruleConfig || ruleConfig === 0 || ruleConfig === 'off') {
      return
    }

    if (Array.isArray(ruleConfig) && (ruleConfig[0] === 0 || ruleConfig[0] === 'off')) {
      return
    }

    if (Array.isArray(ruleConfig) && ruleConfig.length > 1) {
      return ruleConfig.slice(1)
    }

    return defaultOptions
  }

  // https://eslint.org/docs/rules/indent
  const indent = getRuleOptions('indent', [4])
  if (indent) {
    result.indent_style = indent[0] === 'tab' ? 'tab' : 'space'

    if (typeof indent[0] === 'number') {
      result.indent_size = indent[0]
    }
  }

  // https://eslint.org/docs/rules/linebreak-style
  const linebreakStyle = getRuleOptions('linebreak-style', ['unix'])
  if (linebreakStyle) {
    result.end_of_line = linebreakStyle[0] === 'unix' ? 'lf' : 'crlf'
  }

  // https://eslint.org/docs/rules/no-trailing-spaces
  const noTrailingSpaces = getRuleOptions('no-trailing-spaces', [{ skipBlankLines: false, ignoreComments: false }])
  if (noTrailingSpaces) {
    if (!noTrailingSpaces[0].skipBlankLines && !noTrailingSpaces[0].ignoreComments) {
      result.trim_trailing_whitespace = true
    }
  }

  // https://eslint.org/docs/rules/eol-last
  const eolLast = getRuleOptions('eol-last', ['always'])
  if (eolLast) {
    result.insert_final_newline = eolLast[0] !== 'never'
  }

  // https://eslint.org/docs/rules/max-len
  const maxLen = getRuleOptions('max-len', [{ code: 80 }])
  if (maxLen) {
    // To simplify the implementation logic, we only read from the `code` option.

    // `max-len` has an undocumented array-style configuration,
    // where max code length specified directly as integers
    // (used by `eslint-config-airbnb`).

    if (typeof maxLen[0] === 'number') {
      result.max_line_length = maxLen[0]
    } else {
      result.max_line_length = maxLen[0].code
    }
  }

  return result
}
327068
def _parse_formula(s):
    """"""
    scanner = re.compile(r'''
        (\s+) |         # whitespace
        (\(|\)) |       # group
        ([A-Z][a-z]*) | # element
        (\d+) |         # number
        ([a-z]) |       # variable
        (\Z) |          # end
        (.)             # error
    ''', re.DOTALL | re.VERBOSE)

    def transform_subformula(form):
        """Extract radical if subformula is a singleton with a radical."""
        if isinstance(form, dict) and len(form) == 1:
            # A radical in a singleton subformula is interpreted as a
            # numbered radical.
            element, value = next(iteritems(form))
            if isinstance(element, Radical):
                return Radical('{}{}'.format(element.symbol, value))
        return form

    stack = []
    formula = {}
    expect_count = False

    def close(formula, count=1):
        if len(stack) == 0:
            raise ParseError('Unbalanced parenthesis group in formula')
        subformula = transform_subformula(formula)
        if isinstance(subformula, dict):
            subformula = Formula(subformula)

        formula = stack.pop()
        if subformula not in formula:
            formula[subformula] = 0
        formula[subformula] += count
        return formula

    for match in re.finditer(scanner, s):
        (whitespace, group, element, number, variable, end,
            error) = match.groups()

        if error is not None:
            raise ParseError(
                'Invalid token in formula string: {!r}'.format(match.group(0)),
                span=(match.start(), match.end()))
        elif whitespace is not None:
            continue
        elif group is not None and group == '(':
            if expect_count:
                formula = close(formula)
            stack.append(formula)
            formula = {}
            expect_count = False
        elif group is not None and group == ')':
            if expect_count:
                formula = close(formula)
            expect_count = True
        elif element is not None:
            if expect_count:
                formula = close(formula)
            stack.append(formula)
            if element in 'RX':
                formula = Radical(element)
            else:
                formula = Atom(element)
            expect_count = True
        elif number is not None and expect_count:
            formula = close(formula, int(number))
            expect_count = False
        elif variable is not None and expect_count:
            formula = close(formula, Expression(variable))
            expect_count = False
        elif end is not None:
            if expect_count:
                formula = close(formula)
        else:
            raise ParseError(
                'Invalid token in formula string: {!r}'.format(match.group(0)),
                span=(match.start(), match.end()))

    if len(stack) > 0:
        raise ParseError('Unbalanced parenthesis group in formula')

    return Formula(formula)
928005
function checkVertStretch (up, dn, g, doP) /* non-MathML */ {
  if (g.nodeName.toLowerCase() == 'mo' && g.childNodes.length == 1) {
    var c = g.firstChild, s = c.data;
    if (c.nodeType == 3 /* Text */ && (up > 0.9 || dn > 0.9)
      && (M.prefix_[s] < 25 || M.postfix_[s] < 25
        || '|\u2016\u221A' /* ‖ &radic; */.indexOf(s) != -1 || doP)) {
      var r = (up + dn) / 1.2, radicQ = s == '\u221A',
        v = (radicQ ? 0.26 : 0.35) + ((radicQ ? 0.15 : 0.25) - dn) / r;
      g.style.fontSize = r.toFixed(3) + 'em';
      g.style.verticalAlign = v.toFixed(3) + 'em';
      g.fmUp = up;
      g.fmDn = dn;
      g.style.display = 'inline-block';
      g.style.transform = g.style.msTransform = g.style.MozTransform =
        g.style.WebkitTransform = 'scaleX(0.5)';
    }
  }
}
359911
def validate
      xsd = Nokogiri::XML::Schema(File.read(SCHEMA_FILE))
      out = ""
      xsd.validate(@report).each do |error|
        out << error.message unless error.message == "Element 'algorithm', attribute 'publication_ref': '' is not a valid value of the atomic type 'xs:IDREF'." || error.message == "Element 'descriptor', attribute 'publication_ref': '' is not a valid value of the atomic type 'xs:IDREF'." 
        # @todo ignore case sensitivity error: error.message The value 'NO' is not an.Element of the set {'Yes', 'No'}.
      end
      return out
    end
542946
function convertStyleToRules( style ) {
		var styleDef = style.getDefinition(),
			rules = {},
			rule,
			attrs = styleDef.attributes;

		rules[ styleDef.element ] = rule = {
			styles: styleDef.styles,
			requiredStyles: styleDef.styles && CKEDITOR.tools.objectKeys( styleDef.styles )
		};

		if ( attrs ) {
			attrs = copy( attrs );
			rule.classes = attrs[ 'class' ] ? attrs[ 'class' ].split( /\s+/ ) : null;
			rule.requiredClasses = rule.classes;
			delete attrs[ 'class' ];
			rule.attributes = attrs;
			rule.requiredAttributes = attrs && CKEDITOR.tools.objectKeys( attrs );
		}

		return rules;
	}
1211913
function parseComponentBlockParams(element, program) {
      var l = element.attributes.length;
      var attrNames = [];

      for (var i = 0; i < l; i++) {
        attrNames.push(element.attributes[i].name);
      }

      var asIndex = attrNames.indexOf('as');

      if (asIndex !== -1 && l > asIndex && attrNames[asIndex + 1].charAt(0) === '|') {
        // Some basic validation, since we're doing the parsing ourselves
        var paramsString = attrNames.slice(asIndex).join(' ');
        if (paramsString.charAt(paramsString.length - 1) !== '|' || paramsString.match(/\|/g).length !== 2) {
          throw new Error('Invalid block parameters syntax: \'' + paramsString + '\'');
        }

        var params = [];
        for (i = asIndex + 1; i < l; i++) {
          var param = attrNames[i].replace(/\|/g, '');
          if (param !== '') {
            if (ID_INVERSE_PATTERN.test(param)) {
              throw new Error('Invalid identifier for block parameters: \'' + param + '\' in \'' + paramsString + '\'');
            }
            params.push(param);
          }
        }

        if (params.length === 0) {
          throw new Error('Cannot use zero block parameters: \'' + paramsString + '\'');
        }

        element.attributes = element.attributes.slice(0, asIndex);
        program.blockParams = params;
      }
    }
1293907
String verifyMathML(String canMathML) throws MathConverterException {
        try {
            Document tempDoc = XMLHelper.string2Doc(canMathML, true);
            Content content = scanFormulaNode((Element) tempDoc.getFirstChild());
            //verify the formula
            if (content == Content.mathml) {
                return canMathML;
            } else {
                throw new MathConverterException("could not verify produced mathml, content was: " + content.name());
            }
        } catch (Exception e) {
            logger.error("could not verify mathml", e);
            throw new MathConverterException("could not verify mathml");
        }
    }
500363
function parseFunctionSourceElements() {
        var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody;

        expect('{');

        while (index < length) {
            token = lookahead();
            if (token.type !== Token.StringLiteral) {
                break;
            }

            sourceElement = parseSourceElement();
            sourceElements.push(sourceElement);
            if (sourceElement.expression.type !== Syntax.Literal) {
                // this is not directive
                break;
            }
            directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
            if (directive === 'use strict') {
                strict = true;
                if (firstRestricted) {
                    throwError(firstRestricted, Messages.StrictOctalLiteral);
                }
            } else {
                if (!firstRestricted && token.octal) {
                    firstRestricted = token;
                }
            }
        }

        oldLabelSet = labelSet;
        oldInIteration = inIteration;
        oldInSwitch = inSwitch;
        oldInFunctionBody = inFunctionBody;

        labelSet = {};
        inIteration = false;
        inSwitch = false;
        inFunctionBody = true;

        while (index < length) {
            if (match('}')) {
                break;
            }
            sourceElement = parseSourceElement();
            if (typeof sourceElement === 'undefined') {
                break;
            }
            sourceElements.push(sourceElement);
        }

        expect('}');

        labelSet = oldLabelSet;
        inIteration = oldInIteration;
        inSwitch = oldInSwitch;
        inFunctionBody = oldInFunctionBody;

        return {
            type: Syntax.BlockStatement,
            body: wrapBlock(sourceElements)
        };
    }
398355
def convert_fig_elements(self):
        
        for fig in self.main.getroot().findall('.//fig'):
            if fig.getparent().tag == 'p':
                elevate_element(fig)
        for fig in self.main.getroot().findall('.//fig'):
            #self.convert_fn_elements(fig)
            #self.convert_disp_formula_elements(fig)
            #Find label and caption
            label_el = fig.find('label')
            caption_el = fig.find('caption')
            #Get the graphic node, this should be mandatory later on
            graphic_el = fig.find('graphic')
            #Create a file reference for the image
            xlink_href = ns_format(graphic_el, 'xlink:href')
            graphic_xlink_href = graphic_el.attrib[xlink_href]
            file_name = graphic_xlink_href.split('.')[-1] + '.png'
            img_dir = 'images-' + self.doi_suffix()
            img_path = '/'.join([img_dir, file_name])

            #Create the content: using image path, label, and caption
            img_el = etree.Element('img', {'alt': 'A Figure', 'src': img_path,
                                           'class': 'figure'})
            if 'id' in fig.attrib:
                img_el.attrib['id'] = fig.attrib['id']
            insert_before(fig, img_el)

            #Create content for the label and caption
            if caption_el is not None or label_el is not None:
                img_caption_div = etree.Element('div', {'class': 'figure-caption'})
                img_caption_div_b = etree.SubElement(img_caption_div, 'b')
                if label_el is not None:
                    append_all_below(img_caption_div_b, label_el)
                    append_new_text(img_caption_div_b, '. ', join_str='')
                if caption_el is not None:
                    caption_title = caption_el.find('title')
                    if caption_title is not None:
                        append_all_below(img_caption_div_b, caption_title)
                        append_new_text(img_caption_div_b, ' ', join_str='')
                    for each_p in caption_el.findall('p'):
                        append_all_below(img_caption_div, each_p)
                insert_before(fig, img_caption_div)

            #Remove the original <fig>
            remove(fig)
612472
function acceptNode(node) {
  var parent = node.parentElement;
  var isMath = (parent && parent.getAttribute && parent.getAttribute('class')) ? parent.getAttribute('class').includes('katex') || parent.getAttribute('class').includes('MathJax') : false;
  return parent &&
         parent.nodeName !== 'SCRIPT' &&
         parent.nodeName !== 'STYLE' &&
         parent.nodeName !== 'CODE' &&
         parent.nodeName !== 'PRE' &&
         parent.nodeName !== 'SPAN' &&
         parent.nodeName !== 'D-HEADER' &&
         parent.nodeName !== 'D-BYLINE' &&
         parent.nodeName !== 'D-MATH' &&
         parent.nodeName !== 'D-CODE' &&
         parent.nodeName !== 'D-BIBLIOGRAPHY' &&
         parent.nodeName !== 'D-FOOTER' &&
         parent.nodeName !== 'D-APPENDIX' &&
         parent.nodeName !== 'D-FRONTMATTER' &&
         parent.nodeName !== 'D-TOC' &&
         parent.nodeType !== 8 && //comment nodes
         !isMath;
}
555120
def internal_to_elem(pfsh, factory=ET.Element):

    

    attribs = {}
    text = None
    tail = None
    sublist = []
    tag = list(pfsh.keys())
    if len(tag) != 1:
        raise ValueError("Illegal structure with multiple tags: %s" % tag)
    tag = tag[0]
    value = pfsh[tag]
    if isinstance(value, dict):
        for k, v in list(value.items()):
            if k[:1] == "@":
                attribs[k[1:]] = v
            elif k == "#text":
                text = v
            elif k == "#tail":
                tail = v
            elif isinstance(v, list):
                for v2 in v:
                    sublist.append(internal_to_elem({k: v2}, factory=factory))
            else:
                sublist.append(internal_to_elem({k: v}, factory=factory))
    else:
        text = value
    e = factory(tag, attribs)
    for sub in sublist:
        e.append(sub)
    e.text = text
    e.tail = tail
    return e
1107768
function processFormat( value, src, dst ) {
  if( !dst.format ) return value;
  try {
    if( !Array.isArray( dst.format ) )
      throw "Must be an array with two elements!";
    var intlFunc = dst.format[0];
    if( typeof intlFunc !== 'function' )
      throw "First element of the array must be a function!";
    var intlId = dst.format[1];
    if( typeof intlId !== 'string' )
      throw "Second element of the array must be a string!";
    return intlFunc( intlId, value );
  }
  catch( ex ) {
    console.error( ex );
    fail(
      "Error in format of link "
        + PropertyManager(src.obj) + "." + src.name
        + " -> "
        + PropertyManager(dst.obj) + "." + dst.name + "!\n"
        + ex
    );
  }
}