Set up a Mathjax configuration within the window
550149
function ConfigureMathJax() {
  window.MathJax = {
    //
    //  Load all input jax and preprocessors
    //  Load AMS extensions and the autoload extension for TeX
    //  Create stand-alone SVG elements with font caches by default
    //    (users can override that)
    //
    jax: ["input/TeX", "input/MathML", "input/AsciiMath", "output/SVG", "output/CommonHTML"],
    extensions: ["toMathML.js"],
    TeX: {extensions: window.Array("AMSmath.js","AMSsymbols.js","autoload-all.js")},
    SVG: {useFontCache: true, useGlobalCache: false, EqnChunk: 1000000, EqnDelay: 0},
    CommonHTML: {EqnChunk: 1000000, EqnDelay: 0, undefinedFamily:"monospace"},

    //
    //  This gets run before MathJax queues any actions
    //
    AuthorInit: function () {
      MathJax = window.MathJax;

      // Add custom paths to configuration
      for (let key in paths) {
        MathJax.Ajax.config.path[key] = paths[key];
      }

      delete MathJax.Hub.config.styles;               // don't need any styles
      MathJax.Hub.Startup.MenuZoom = function () {};  // don't load menu or zoom code
      MathJax.Extension.MathEvents = {
        Event:{}, Touch:{}, Hover:{}                  // fake structure to avid errors
      };
      MathJax.Ajax.loaded[MathJax.Ajax.fileURL("[MathJax]/extensions/MathEvents.js")] = true;

      //
      //  When creating stylesheets, no need to wait for them
      //  to become active, so just do the callback
      //
      MathJax.Ajax.timer.create = function (callback,node) {
        callback = MathJax.Callback(callback);
        callback(this.STATUS.OK);
        return callback;
      };

      //
      //  Use the console for messages, if we are requesting them
      //
      MathJax.Message.Set = function (text,n,delay) {
        if (displayMessages && n !== 0) {
          if (text instanceof window.Array)
            {text = MathJax.Localization._.apply(MathJax.Localization,text)}
          console.error(text);
        }
      };
      MathJax.Message.Clear = function () {};
      MathJax.Message.Remove = function () {};
      MathJax.Message.Init = function () {};

      //
      //  Trap Math Processing Errors
      //
      MathJax.Hub.Register.MessageHook("Math Processing Error",function (message) {
        AddError("Math Processing Error: "+message[2].message);
      });
      MathJax.Hub.Register.MessageHook("SVG Jax - unknown char",function (message) {
        AddError("SVG - Unknown character: U+"+message[1].toString(16).toUpperCase()+
                    " in "+(message[2].fonts||["unknown"]).join(","),!undefinedChar);
      });
      MathJax.Hub.Register.MessageHook("CommonHTML Jax - unknown char",function (message) {
        AddError("CHTML - Unknown character: U+"+message[1].toString(16).toUpperCase()+
                    " in "+(message[2].fonts||["unknown"]).join(","),!undefinedChar);
      });
      MathJax.Hub.Register.MessageHook("MathML Jax - unknown node type",function (message) {
        AddError("MathML - Unknown node type: "+message[1]);
      });
      MathJax.Hub.Register.MessageHook("MathML Jax - parse error",function (message) {
        AddError("MathML - "+message[1]);
      });
      MathJax.Hub.Register.MessageHook("AsciiMath Jax - parse error",function (message) {
        AddError("AsciiMath parse error: "+message[1]);
      });
      MathJax.Hub.Register.MessageHook("TeX Jax - parse error",function (message) {
        AddError("TeX parse error: "+message[1]);
      });
      MathJax.Hub.Register.MessageHook("file load error",function (message) {
        AddError("File load error: "+message[1]);
      });

      //
      //  Set the delays to 0 (we don't need to update the screen)
      //
      MathJax.Hub.processSectionDelay = 0;
      MathJax.Hub.processUpdateTime = 10000000;  // don't interrupt processing of output
      MathJax.Hub.processUpdateDelay = 0;

      //
      //  Adjust the SVG output jax
      //
      MathJax.Hub.Register.StartupHook("SVG Jax Config",function () {
        var SVG = MathJax.OutputJax.SVG, HTML = MathJax.HTML;

        //
        //  Don't need the styles
        //
        delete SVG.config.styles

        SVG.Augment({
          //
          //  Set up the default ex-size and width
          //
          InitializeSVG: function () {
            this.pxPerInch    = 96;
            this.defaultEx    = 6;
            this.defaultWidth = 100;
          },
          //
          //  Adjust preTranslate() to not try to find the ex-size or
          //  the container widths.
          //
          preTranslate: function (state) {
            var scripts = state.jax[this.id], i, m = scripts.length,
                script, prev, span, div, jax, ex, em,
                maxwidth = 100000, relwidth = false, cwidth,
                linebreak = this.config.linebreaks.automatic,
                width = this.config.linebreaks.width;
            //
            //  Loop through the scripts
            //
            for (i = 0; i < m; i++) {
              script = scripts[i]; if (!script.parentNode) continue;
              //
              //  Remove any existing output
              //
              prev = script.previousSibling;
              if (prev && String(prev.className).match(/^MathJax(_SVG)?(_Display)?( MathJax(_SVG)?_Processing)?$/))
                {prev.parentNode.removeChild(prev)}
              //
              //  Add the span, and a div if in display mode,
              //  then mark it as being processed
              //
              jax = script.MathJax.elementJax; if (!jax) continue;
              jax.SVG = {display: (jax.root.Get("display") === "block")}
              span = div = HTML.Element("span",{
                style: {"font-size": this.config.scale+"%", display:"inline-block"},
                className:"MathJax_SVG", id:jax.inputID+"-Frame", isMathJax:true, jaxID:this.id
              });
              if (jax.SVG.display) {
                div = HTML.Element("div",{className:"MathJax_SVG_Display"});
                div.appendChild(span);
              }
              div.className += " MathJax_SVG_Processing";
              script.parentNode.insertBefore(div,script);
              //
              //  Set SVG data for jax
              //
              jax.SVG.ex = ex = (data||defaults).ex;
              jax.SVG.em = em = ex / SVG.TeX.x_height * 1000; // scale ex to x_height
              jax.SVG.cwidth = width / em * 1000;
              jax.SVG.lineWidth = (linebreak ? width / em * 1000 : SVG.BIGDIMEN);
            }
            //
            //  Set state variables used for displaying equations in chunks
            //
            state.SVGeqn = state.SVGlast = 0; state.SVGi = -1;
            state.SVGchunk = this.config.EqnChunk;
            state.SVGdelay = false;
          }
        });

        //
        //  TEXT boxes use getBBox, which isn't implemented, so
        //  use a monspace font and fake the size.  Since these
        //  are used only for error messages and undefined characters,
        //  this should be good enough for now.
        //
        SVG.BBOX.TEXT.Augment({
          Init: function (scale,text,def) {
            if (!def) {def = {}}; def.stroke = "none";
            if (def["font-style"] === "") delete def["font-style"];
            if (def["font-weight"] === "") delete def["font-weight"];
            this.SUPER(arguments).Init.call(this,def);
            SVG.addText(this.element,text);
            // tweaking font fallback behavior: https://github.com/mathjax/MathJax-node/issues/299
            var textWidth = text.split('')
              .map(function(c) { return isFullwidthCodePoint(c.codePointAt()) ? data.cjkCharWidth : 8.5 })
              .reduce(function(a, b) { return a + b }, 0);
            var bbox = {width: textWidth, height: 18, y: -12};
            scale *= 1000/SVG.em;
            this.element.setAttribute("font-family","monospace");
            this.element.setAttribute("transform","scale("+scale+") matrix(1 0 0 -1 0 0)");
            this.w = this.r = bbox.width*scale; this.l = 0;
            this.h = this.H = -bbox.y*scale;
            this.d = this.D = (bbox.height + bbox.y)*scale;
          }
        });

        //
        //  Don't have mglyph load images
        //
        MathJax.Hub.Register.StartupHook("SVG mglyph Ready",function () {
          var MML = MathJax.ElementJax.mml;
          var MGLYPH = MML.mglyph;
          var TOSVG = MGLYPH.prototype.toSVG;
          MGLYPH.Augment({
            toSVG: function (variant,scale) {
              var values = this.getValues("src","width","height");
              if (values.src !== "" && !MGLYPH.GLYPH[values.src]) {
                if (!values.width || !values.height) {
                  AddError("mglyphs must have explicit width and height in mathjax-node");
                }
                MGLYPH.GLYPH[values.src] = {
                  img: {SRC: values.src, width: 0, height: 0},
                  status: "OK"
                };
              }
              return TOSVG.apply(this,arguments);
            }
          });
        });

      });

      //
      //  Adjust the CommonHTML output jax
      //
      MathJax.Hub.Register.StartupHook("CommonHTML Jax Config",function () {
        var CHTML = MathJax.OutputJax.CommonHTML, HTML = MathJax.HTML;

        //
        //  Don't need these styles
        //
        var STYLES = CHTML.config.styles;
        delete STYLES["#MathJax_CHTML_Tooltip"];
        delete STYLES[".MJXc-processing"];
        delete STYLES[".MJXc-processed"];
        delete STYLES[".mjx-chartest"];
        delete STYLES[".mjx-chartest .mjx-char"];
        delete STYLES[".mjx-chartest .mjx-box"];
        delete STYLES[".mjx-test"];
        delete STYLES[".mjx-ex-boxtest"];
        //  fontURL to current MathJax version
        if (!fontURL){
          fontURL = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/' + MathJax.version + '/fonts/HTML-CSS';
        }
        CHTML.Augment({
          webfontDir: fontURL,
          //
          //  Set up the default ex-size and width
          //
          getDefaultExEm: function () {
            var styles = document.head.getElementsByTagName("style");
            CHTMLSTYLES = styles[styles.length-1].innerHTML;
            this.pxPerInch    = 96;
            this.defaultEx    = 6;
            this.defaultEm    = 6 / CHTML.TEX.x_height * 1000;
            this.defaultWidth = 100;
          },
          //
          //  Adjust preTranslate() to not try to find the ex-size or
          //  the container widths.
          //
          preTranslate: function (state) {
            var scripts = state.jax[this.id], i, m = scripts.length,
                script, prev, node, jax, ex, em,
                maxwidth = 100000, relwidth = false, cwidth = 0,
                linebreak = this.config.linebreaks.automatic,
                width = this.config.linebreaks.width;
            //
            //  Loop through the scripts
            //
            for (i = 0; i < m; i++) {
              script = scripts[i]; if (!script.parentNode) continue;
              //
              //  Remove any existing output
              //
              prev = script.previousSibling;
              if (prev && prev.className && String(prev.className).substr(0,9) === "mjx-chtml")
                prev.parentNode.removeChild(prev);
              //
              //  Add the node for the math and mark it as being processed
              //
              jax = script.MathJax.elementJax; if (!jax) continue;
              jax.CHTML = {display: (jax.root.Get("display") === "block")}
              node = CHTML.Element("mjx-chtml",{
                id:jax.inputID+"-Frame", isMathJax:true, jaxID:this.id
              });
              if (jax.CHTML.display) {
                //
                // Zoom box requires an outer container to get the positioning right.
                //
                var NODE = CHTML.Element("mjx-chtml",{className:"MJXc-display",isMathJax:false});
                NODE.appendChild(node); node = NODE;
              }

              node.className += " MJXc-processing";
              script.parentNode.insertBefore(node,script);
              //
              //  Set CHTML data for jax
              //
              jax.CHTML.ex = ex = (data||defaults).ex;
              jax.CHTML.em = jax.CHTML.outerEm = em = ex / CHTML.TEX.x_height; // scale ex to x_height
              jax.CHTML.cwidth = width / em;
              jax.CHTML.lineWidth = (linebreak ? width / em : 1000000);
              jax.CHTML.scale = 1; jax.CHTML.fontsize = "100%";
            }
            //
            //  Set state variables used for displaying equations in chunks
            //
            state.CHTMLeqn = state.CHTMLlast = 0; state.CHTMLi = -1;
            state.CHTMLchunk = this.config.EqnChunk;
            state.CHTMLdelay = false;
          },

          //
          //  We are using a monospaced font, so fake the size
          //
          getHDW: function (c,name,styles) {
            return {h:.8, d:.2, w:c.length*.5};
          }

        });

        //
        //  Don't have mglyph load images
        //
        MathJax.Hub.Register.StartupHook("CommonHTML mglyph Ready",function () {
          var MML = MathJax.ElementJax.mml;
          var MGLYPH = MML.mglyph;
          var TOCHTML = MGLYPH.prototype.toCommonHTML;
          MGLYPH.Augment({
            toCommonHTML: function (node,options) {
              var values = this.getValues("src","width","height");
              if (values.src !== "" && !MGLYPH.GLYPH[values.src]) {
                if (!values.width || !values.height) {
                  AddError("mglyphs must have explicit width and height in mathjax-node");
                }
                MGLYPH.GLYPH[values.src] = {
                  img: {SRC: values.src, width: 0, height: 0},
                  status: "OK"
                };
              }
              return TOCHTML.apply(this,arguments);
            }
          });
        });

      });

      //
      //  Set up None output jax (for when only MathML output is needed)
      //
      MathJax.Hub.Register.StartupHook("End Jax", function () {
        MathJax.OutputJax.None = MathJax.OutputJax({
          id: "None",
          preTranslate: function () {},
          Translate: function () {},
          postTranslate: function () {}
        });
        MathJax.OutputJax.None.loadComplete("jax.js");
        MathJax.OutputJax.None.Register("jax/mml");
      });

      //
      //  Reset the color extension after `autoload-all`
      //
      if (MathJax.AuthorConfig.extensions.indexOf("TeX/color.js") == -1 && MathJax.AuthorConfig.extensions.indexOf("TeX/autoload-all.js") == -1) {
              MathJax.Hub.Register.StartupHook("TeX autoload-all Ready",function () {
                var macros = MathJax.InputJax.TeX.Definitions.macros;
                macros.color = "Color";
                delete macros.textcolor;
                delete macros.colorbox;
                delete macros.fcolorbox;
                delete macros.definecolor;
              });
            }

      //
      //  Start the typesetting queue when MathJax is ready
      //    (reseting the counters so that the initial math doesn't affect them)
      //
      MathJax.Hub.Register.StartupHook("End",function () {
        if (MathJax.OutputJax.SVG.resetGlyphs) MathJax.OutputJax.SVG.resetGlyphs(true);
        MathJax.ElementJax.mml.ID = 0;
        if (serverState === STATE.RESTART) {
          setTimeout(RestartMathJax, 100);
        } else {
          serverState = STATE.READY;
          MathJax.Hub.Queue(
            function () {sErrors = errors},
            StartQueue
          );
        }
      });
    }
  };

  if (extensions) {
    //
    // Parse added extensions list and add to standard ones
    //
    var extensionList = extensions.split(/\s*,\s*/);
    for (var i = 0; i < extensionList.length; i++) {
      var matches = extensionList[i].match(/^(.*?)(\.js)?$/);
      window.MathJax.extensions.push(matches[1] + '.js');
    }
  }

  //
  //  Turn arrays into jsdom window arrays
  //  (so "instanceof Array" will identify them properly)
  //
  var adjustArrays = function (obj) {
    for (var id in obj) {if (obj.hasOwnProperty(id)) {
      if (obj[id] instanceof Array) {
        var A = window.Array();
        obj[id] = A.concat.apply(A,obj[id]);
      } else if (typeof obj[id] === "object") {
        adjustArrays(obj[id]);
      }
    }}
  }
  if (MathJaxConfig) {
    adjustArrays(MathJaxConfig);
    // merge the defaults into the user configuration (to sanitize)
    window.MathJax = Insert(Insert({},MathJaxConfig),window.MathJax);
    if (MathJaxConfig.extensions) {
      window.MathJax.extensions = window.MathJax.extensions.concat(MathJaxConfig.extensions);
    }
  }
}
122193
function (element) {
      var JAX = HUB.getAllJax(element);
      var i, m, script, span = MathJax.HTML.Element("span",{style:{display:"block"}});
      var math = [], jax, root;
      for (i = 0, m = JAX.length; i < m; i++) {
        jax = JAX[i], root = jax.root, SRE = root.SRE;
        if (SRE && SRE.action.length) {
          if (SRE.width == null) {
            jax.sreGetMetrics();
            SRE.m = SRE.width; SRE.M = 1000000;
          }
          script = jax.SourceElement();
          script.previousSibling.style.display = "none";
          script.parentNode.insertBefore(span.cloneNode(false),script);
          math.push([jax,script]);
        }
      }
      for (i = 0, m = math.length; i < m; i++) {
        jax = math[i][0], script = math[i][1];
        if (script.previousSibling.offsetWidth)
          jax.root.SRE.cwidth = script.previousSibling.offsetWidth * jax.root.SRE.em;
      }
      for (i = 0, m = math.length; i < m; i++) {
        jax = math[i][0], script = math[i][1];
        script.parentNode.removeChild(script.previousSibling);
        script.previousSibling.style.display = "";
      }
    }
596423
function(hljs) {
  var CONSTANTS = {
    className: 'symbol',
    begin: '\\$(ADMINTOOLS|APPDATA|CDBURN_AREA|CMDLINE|COMMONFILES32|COMMONFILES64|COMMONFILES|COOKIES|DESKTOP|DOCUMENTS|EXEDIR|EXEFILE|EXEPATH|FAVORITES|FONTS|HISTORY|HWNDPARENT|INSTDIR|INTERNET_CACHE|LANGUAGE|LOCALAPPDATA|MUSIC|NETHOOD|OUTDIR|PICTURES|PLUGINSDIR|PRINTHOOD|PROFILE|PROGRAMFILES32|PROGRAMFILES64|PROGRAMFILES|QUICKLAUNCH|RECENT|RESOURCES_LOCALIZED|RESOURCES|SENDTO|SMPROGRAMS|SMSTARTUP|STARTMENU|SYSDIR|TEMP|TEMPLATES|VIDEOS|WINDIR)'
  };

  var DEFINES = {
    // ${defines}
    className: 'constant',
    begin: '\\$+{[a-zA-Z0-9_]+}'
  };

  var VARIABLES = {
    // $variables
    className: 'variable',
    begin: '\\$+[a-zA-Z0-9_]+',
    illegal: '\\(\\){}'
  };

  var LANGUAGES = {
    // $(language_strings)
    className: 'constant',
    begin: '\\$+\\([a-zA-Z0-9_]+\\)'
  };

  var PARAMETERS = {
    // command parameters
    className: 'params',
    begin: '(ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HKCR|HKCU|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM|HKPD|HKU|IDABORT|IDCANCEL|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SYSTEM|TEMPORARY)'
  };

  var COMPILER ={
    // !compiler_flags
    className: 'constant',
    begin: '\\!(addincludedir|addplugindir|appendfile|cd|define|delfile|echo|else|endif|error|execute|finalize|getdllversionsystem|ifdef|ifmacrodef|ifmacrondef|ifndef|if|include|insertmacro|macroend|macro|packhdr|searchparse|searchreplace|tempfile|undef|verbose|warning)'
  };

  return {
    case_insensitive: false,
    keywords: {
      keyword:
      'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ChangeUI CheckBitmap ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exch Exec ExecShell ExecWait ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileReadUTF16LE FileReadWord FileSeek FileWrite FileWriteByte FileWriteUTF16LE FileWriteWord FindClose FindFirst FindNext FindWindow FlushINI FunctionEnd GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetLabelAddress GetTempFileName Goto HideWindow Icon IfAbort IfErrors IfFileExists IfRebootFlag IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText IntCmp IntCmpU IntFmt IntOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadLanguageFile LockWindow LogSet LogText ManifestDPIAware ManifestSupportedOS MessageBox MiscButtonText Name Nop OutFile Page PageCallbacks PageExEnd Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename RequestExecutionLevel ReserveFile Return RMDir SearchPath SectionEnd SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionGroupEnd SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetPluginUnload SetRebootFlag SetRegView SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCmpS StrCpy StrLen SubCaption SubSectionEnd Unicode UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIFileVersion VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegStr WriteUninstaller XPStyle',
      literal:
      'admin all auto both colored current false force hide highest lastused leave listonly none normal notset off on open print show silent silentlog smooth textonly true user '
    },
    contains: [
      hljs.HASH_COMMENT_MODE,
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'string',
        begin: '"', end: '"',
        illegal: '\\n',
        contains: [
          { // $\n, $\r, $\t, $$
            className: 'symbol',
            begin: '\\$(\\\\(n|r|t)|\\$)'
          },
          CONSTANTS,
          DEFINES,
          VARIABLES,
          LANGUAGES
        ]
      },
      { // line comments
        className: 'comment',
        begin: ';', end: '$',
        relevance: 0
      },
      {
        className: 'function',
        beginKeywords: 'Function PageEx Section SectionGroup SubSection', end: '$'
      },
      COMPILER,
      DEFINES,
      VARIABLES,
      LANGUAGES,
      PARAMETERS,
      hljs.NUMBER_MODE,
      { // plug::ins
        className: 'literal',
        begin: hljs.IDENT_RE + '::' + hljs.IDENT_RE
      }
    ]
  };
}
409624
def mathjax_for_markdown(pelicanobj, mathjax_script, mathjax_settings):
    """"""

    # Create the configuration for the markdown template
    config = {}
    config['mathjax_script'] = mathjax_script
    config['math_tag_class'] = 'math'
    config['auto_insert'] = mathjax_settings['auto_insert']

    # Instantiate markdown extension and append it to the current extensions
    try:
        if isinstance(pelicanobj.settings.get('MD_EXTENSIONS'), list): # pelican 3.6.3 and earlier
            pelicanobj.settings['MD_EXTENSIONS'].append(PelicanMathJaxExtension(config))
        else:
            pelicanobj.settings['MARKDOWN'].setdefault('extensions', []).append(PelicanMathJaxExtension(config))
    except:
        sys.excepthook(*sys.exc_info())
        sys.stderr.write("\nError - the pelican mathjax markdown extension failed to configure. MathJax is non-functional.\n")
        sys.stderr.flush()
129347
function initHannWindow(buffer, size, normCoefs) {
  let linSum = 0;
  let powSum = 0;
  const step = 2 * PI / size;

  for (let i = 0; i < size; i++) {
    const phi = i * step;
    const value = 0.5 - 0.5 * cos(phi);

    buffer[i] = value;

    linSum += value;
    powSum += value * value;
  }

  normCoefs.linear = size / linSum;
  normCoefs.power = sqrt(size / powSum);
}
1181350
function (str, x, y) {

		var defaultChartStyle = defaultOptions.chart.style;

		return this.createElement('span')
			.attr({
				text: str,
				x: mathRound(x),
				y: mathRound(y)
			})
			.css({
				whiteSpace: 'nowrap',
				fontFamily: defaultChartStyle.fontFamily,
				fontSize: defaultChartStyle.fontSize
			});
	}
2991
function RestartMathJax() {
  if (timer) {
    MathJax.Hub.queue.queue = [];  // clear MathJax queue, so pending operations won't fire
    MathJax = timer = window = document = html = content = null;
    ReportError("Timeout waiting for MathJax:  restarting");
  }
  serverState = STATE.STOPPED;
  GetWindow();
  ConfigureMathJax();
  StartMathJax();
}
601533
function(msg) {
      if (!Assistive.hook) return;
      var script = document.getElementById(msg[1]);
      if (script && script.id) {
        var jax = MathJax.Hub.getJaxFor(script.id);
        if (jax && jax.enriched) {
          Explorer.StateChange(script.id, jax);
          Explorer.liveRegion.Add();
          Explorer.AddEvent(script);
        }
      }
    }
754063
function waitForJavaScript() {
  if (window.MathJax) {
    // Amazon EC2: fix TeX font detection
    MathJax.Hub.Register.StartupHook('HTML-CSS Jax Startup', function () {
      var htmlCss = MathJax.OutputJax['HTML-CSS'];
      htmlCss.Font.checkWebFont = function (check, font, callback) {
        if (check.time(callback)) {
          return;
        }
        if (check.total === 0) {
          htmlCss.Font.testFont(font);
          setTimeout(check, 200);
        } else {
          callback(check.STATUS.OK);
        }
      };
    });
    MathJax.Hub.Queue(function () {
      window.status = 'done';
    });
  } else {
    setTimeout(function () {
      window.status = 'done';
    }, 2000);
  }
}
693218
function() {
      var n = JSLitmus._tests.length, markers = [], data = [];
      var d, min = 0, max = -1e10;
      var normalize = jsl.$('test_normalize').checked;

      // Gather test data
      for (var i=0; i < JSLitmus._tests.length; i++) {
        var test = JSLitmus._tests[i];
        if (test.count) {
          var hz = test.getHz(normalize);
          var v = hz != Infinity ? hz : 0;
          data.push(v);
          markers.push('t' + jsl.escape(test.name + '(' + jsl.toLabel(hz)+ ')') + ',000000,0,' +
            markers.length + ',10');
          max = Math.max(v, max);
        }
      }
      if (markers.length <= 0) return null;

      // Build chart title
      var title = document.getElementsByTagName('title');
      title = (title && title.length) ? title[0].innerHTML : null;
      var chart_title = [];
      if (title) chart_title.push(title);
      chart_title.push('Ops/sec (' + platform + ')');

      // Build labels
      var labels = [jsl.toLabel(min), jsl.toLabel(max)];

      var w = 250, bw = 15;
      var bs = 5;
      var h = markers.length*(bw + bs) + 30 + chart_title.length*20;

      var params = {
        chtt: escape(chart_title.join('|')),
        chts: '000000,10',
        cht: 'bhg',                     // chart type
        chd: 't:' + data.join(','),     // data set
        chds: min + ',' + max,          // max/min of data
        chxt: 'x',                      // label axes
        chxl: '0:|' + labels.join('|'), // labels
        chsp: '0,1',
        chm: markers.join('|'),         // test names
        chbh: [bw, 0, bs].join(','),    // bar widths
        // chf: 'bg,lg,0,eeeeee,0,eeeeee,.5,ffffff,1', // gradient
        chs: w + 'x' + h
      };
      return 'http://chart.apis.google.com/chart?' + jsl.join(params, '=', '&');
    }
1337704
def setup(self, mute_inline_plotting=None, show_plot_outline=None):
        """"""
        assert self.shellwidget is not None

        self.mute_inline_plotting = mute_inline_plotting
        self.show_plot_outline = show_plot_outline

        if self.figviewer is not None:
            self.mute_inline_action.setChecked(mute_inline_plotting)
            self.show_plot_outline_action.setChecked(show_plot_outline)
            return

        self.figviewer = FigureViewer(background_color=self.background_color)
        self.figviewer.setStyleSheet("FigureViewer{"
                                     "border: 1px solid lightgrey;"
                                     "border-top-width: 0px;"
                                     "border-bottom-width: 0px;"
                                     "border-left-width: 0px;"
                                     "}")
        self.thumbnails_sb = ThumbnailScrollBar(
            self.figviewer, background_color=self.background_color)

        # Option actions :
        self.setup_option_actions(mute_inline_plotting, show_plot_outline)

        # Create the layout :
        main_widget = QSplitter()
        main_widget.addWidget(self.figviewer)
        main_widget.addWidget(self.thumbnails_sb)
        main_widget.setFrameStyle(QScrollArea().frameStyle())

        self.tools_layout = QHBoxLayout()
        toolbar = self.setup_toolbar()
        for widget in toolbar:
            self.tools_layout.addWidget(widget)
        self.tools_layout.addStretch()
        self.setup_options_button()

        layout = create_plugin_layout(self.tools_layout, main_widget)
        self.setLayout(layout)
439965
def fromJavascript(cls, javascript_datetime):

        ''' 
        '''

    # validate inputs
        title = 'Javascript datetime string input for labDT.fromJavascript'
        jsDTpattern = re.compile('\s*\(.*\)$')
        jsGMTpattern = re.compile('GMT[-\+]\d{4}')
        if not jsGMTpattern.findall(javascript_datetime):
            raise Exception('\n%s must have a GMT timezone adjustment.' % title)

    # construct datetime from javascript string
        adj_input = jsDTpattern.sub('', javascript_datetime)
        if '-' in adj_input:
            adj_input = adj_input.replace('-','+')
        elif '+' in adj_input:
            adj_input = adj_input.replace('+','-')
        python_datetime = dTparser.parse(adj_input)
        dT = python_datetime.astimezone(pytz.utc)
        dt_kwargs = {
            'year': dT.year,
            'month': dT.month,
            'day': dT.day,
            'hour': dT.hour,
            'minute': dT.minute,
            'second': dT.second,
            'microsecond': dT.microsecond,
            'tzinfo': dT.tzinfo
        }
        return labDT(**dt_kwargs)
821917
function() {

      var x, els, y, div, blocks, el, next, previous, span;

      blocks = hashedit.config.blocks;

      // setup sortable classes
      els = document.querySelectorAll('[hashedit] ' + blocks);


      // set [data-hashedit-sortable=true]
      for (y = 0; y < els.length; y += 1) {

        // setup blocks
        if(els[y].querySelector('.hashedit-block-menu') === null) {

          els[y].setAttribute('hashedit-block', '');

          // create element menu
          div = document.createElement('DIV');
          div.setAttribute('class', 'hashedit-block-menu');
          div.setAttribute('contentEditable', 'false');
          div.innerHTML = '<label><i class="material-icons">more_vert</i> ' + hashedit.i18n('Layout Menu') + '</label>';

          // create up
          span = document.createElement('span');
          span.setAttribute('class', 'hashedit-block-add');
          span.innerHTML = '<i class="material-icons">add</i> ' + hashedit.i18n('Add');

          // append the handle to the wrapper
          div.appendChild(span);

          // create up
          span = document.createElement('span');
          span.setAttribute('class', 'hashedit-block-up');
          span.innerHTML = '<i class="material-icons">arrow_upward</i> ' + hashedit.i18n('Move Up');

          // append the handle to the wrapper
          div.appendChild(span);

          // create down
          span = document.createElement('span');
          span.setAttribute('class', 'hashedit-block-down');
          span.innerHTML = '<i class="material-icons">arrow_downward</i> ' + hashedit.i18n('Move Down');

          // append the handle to the wrapper
          div.appendChild(span);

          // create remove
          span = document.createElement('span');
          span.setAttribute('class', 'hashedit-block-duplicate');
          span.innerHTML = '<i class="material-icons">content_copy</i> ' + hashedit.i18n('Duplicate');

          // append the handle to the wrapper
          div.appendChild(span);

          // create properties
          span = document.createElement('span');
          span.setAttribute('class', 'hashedit-block-properties');
          span.innerHTML = '<i class="material-icons">settings</i> ' + hashedit.i18n('Settings');

          // append the handle to the wrapper
          div.appendChild(span);

          // create remove
          span = document.createElement('span');
          span.setAttribute('class', 'hashedit-block-remove');
          span.innerHTML = '<i class="material-icons">cancel</i> ' + hashedit.i18n('Remove');

          // append the handle to the wrapper
          div.appendChild(span);

          els[y].appendChild(div);

        }

      }

    }
732475
function mvScan (sP) {
  var s = sP || scanString('mathvariant'), tok = scanMeTok(s), me = tok[0];
  if (!F.elem(M.mtagName(me), ['mi', 'mn', 'mo', 'mtext', 'mspace', 'ms']))
    throw 'Can only apply a mathvariant to a MathML token (atomic) element, at ' +
    'position ' + M.re_.lastIndex;

  me.setAttribute('mathvariant', s);

  if (/bold/.test(s)) M.addClass(me, 'ma-bold');
  else if (s == 'normal' || s == 'italic') M.addClass(me, 'ma-nonbold');

  M.addClass(me, /italic/.test(s) ? 'ma-italic' : 'ma-upright');

  if (/double-struck/.test(s)) M.addClass(me, 'ma-double-struck');
  else if (/fraktur/.test(s)) M.addClass(me, 'ma-fraktur');
  else if (/script/.test(s)) M.addClass(me, 'ma-script');
  else if (/sans-serif/.test(s)) M.addClass(me, 'ma-sans-serif');

  // (monospace, initial, tailed, looped, stretched) currently don't add classes

  return tok;
}
806028
function setup (index) {
  function get () {
    return this[ArrayIndex.get](index);
  }
  function set (v) {
    return this[ArrayIndex.set](index, v);
  }
  return {
    enumerable: true,
    configurable: true,
    get: get,
    set: set
  };
}
370659
function(w, h) {
    grids[0].set( space.size.$multiply( 0.1 ) ).to( space.size.$multiply( 0.9, 0.3 ) ).init( 50, 50, "fix", "fix" );
    grids[1].set( space.size.$multiply( 0.1, 0.4 ) ).to( space.size.$multiply( 0.9, 0.6 ) ).init( 50, 50, "flex", "flex" );
    grids[2].set( space.size.$multiply( 0.1, 0.7 ) ).to( space.size.$multiply( 0.9, 0.9 ) ).init( 5, 8, "stretch", "stretch" );
  }
352643
def extension(line, cell=None):
  
  parser = _commands.CommandParser(prog='%extension', description="""
Load an extension into Datalab. Currently only mathjax is supported.
""")
  subparser = parser.subcommand('mathjax', 'Enabled MathJaX support in Datalab.')
  subparser.set_defaults(ext='mathjax')
  parser.set_defaults(func=_extension)
  return _utils.handle_magic_line(line, cell, parser)