<commit_before>window.markerTypes = {
  "family": "marker-fam",
  "gov":    "marker-gov",
  "news":   "marker-news",
  "social": "marker-soc"
};
window.infoTypes = {
  "picture": "info-picture",
  "video":   "info-video",
  "tweet":   "info-tweet"
};

window.mapInfo = [
  {
    "date": "August 9-10, 2014",
    "lat": 38.738312, // first lat-long is actually set by sosv (content.json)
    "lng": -90.273611, // so these aren't used
    "markers": [
      {
        "date": "August 9, 2014",
        "lat": 38.739332,
        "lng": -90.273152,
        "headline": "On August 9th, 18-year-old Michael Brown was shot and killed",
        "type": window.markerTypes.news,
        "contentType": window.infoTypes.video,
        "link": "",
        "content": "6SGkD6CN0mk"
      },
        {
"date": "August 10, 2014",
"lat": 38.743812,
"lng": -90.279095,
"headline": "",
"type": window.markerTypes.family,
"contentType": window.infoTypes.picture,
"link": "",
"content": "http://scontent-a-ams.cdninstagram.com/hphotos-xpf1/l/t51.2885-15/1738085_692070914213393_1197767717_n.jpg"
},
 {
"date": "August 10, 2014",
"lat": 38.740877,
"lng": -90.303086,
"headline": "",
"type": window.markerTypes.gov,
"contentType": window.infoTypes.video,
"link": "",
"content": "zUXqPDT8hr4"
},
    ]
  },
  {
    "date": "August 11, 2014",
    "lat": 38.749613,
    "lng": -90.279912,
    "markers": [
      {
"date": "August 11, 2014",
"lat": 38.749613,
"lng": -90.279912,
"headline": "Protests continue two days after Michael Brown's death",
"type": window.markerTypes.social,
"contentType": window.infoTypes.picture,
"link": "",
"content": "https://c4.staticflickr.com/4/3860/14794832317_db2b6eeb98_b.jpg"
},
    {
"date": "August 11, 2014",
"lat": 38.749613,
"lng": -90.279912,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.picture,
"link": "",
"content": "http://i.imgur.com/6kah8zq.png"
},
   {
"date": "August 11, 2014",
"lat": 38.735419,
"lng": -90.278376,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.tweet,
"link": "",
"content": '

It's just past 1 a.m. in #Ferguson, and this is what we're seeing pic.twitter.com/ZiKgGP2TGq
— Alan Blinder (@alanblinder) August 16, 2014
'
},
    ]
  },
  {
    "date": "August 12, 2014",
    "lat": 38.648863,
    "lng": -90.338427,
    "markers": [
      {
"date": "August 12, 2014",
"lat": 38.648863,
"lng": -90.338427,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.tweet,
"link": "",
"content": "

love this <3 RT @stevenjhsieh: Man waving a Palestinian flag in #Ferguson "because they supported St. Louis." pic.twitter.com/tn96pvFEXF
— Grim_Chickn (@grm_chikn) August 16, 2014
"
},
{
"date": "August 12, 2014",
"lat": 38.735419,
"lng": -90.278376,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.tweet,
"link": "",
"content": "

It's just past 1 a.m. in #Ferguson, and this is what we're seeing pic.twitter.com/ZiKgGP2TGq
— Alan Blinder (@alanblinder) August 16, 2014
"
},
{
"date": "August 12, 2014",
"lat": 38.738455,
"lng": -90.277542,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.picture,
"link": "",
"content": "

It's just past 1 a.m. in #Ferguson, and this is what we're seeing pic.twitter.com/ZiKgGP2TGq
— Alan Blinder (@alanblinder) August 16, 2014
"
},
    ]
  },
  {
    "date": "August 20th",
    "lat": 38.73857,
    "lng": -90.27387,
    "markers": [
    ]
  },
  {
    "date": "August 25th",
    "lat": 38.73857,
    "lng": -90.27387,
    "markers": [
    ]
  }
];
<commit_msg>Update ferguson.js<commit_after>window.markerTypes = {
  "family": "marker-fam",
  "gov":    "marker-gov",
  "news":   "marker-news",
  "social": "marker-soc"
};
window.infoTypes = {
  "picture": "info-picture",
  "video":   "info-video",
  "tweet":   "info-tweet"
};

window.mapInfo = [
  {
    "date": "August 9-10, 2014",
    "lat": 38.738312, // first lat-long is actually set by sosv (content.json)
    "lng": -90.273611, // so these aren't used
    "markers": [
      {
        "date": "August 9, 2014",
        "lat": 38.739332,
        "lng": -90.273152,
        "headline": "On August 9th, 18-year-old Michael Brown was shot and killed",
        "type": window.markerTypes.news,
        "contentType": window.infoTypes.video,
        "link": "",
        "content": "6SGkD6CN0mk"
      },
        {
"date": "August 10, 2014",
"lat": 38.743812,
"lng": -90.279095,
"headline": "",
"type": window.markerTypes.family,
"contentType": window.infoTypes.picture,
"link": "",
"content": "http://scontent-a-ams.cdninstagram.com/hphotos-xpf1/l/t51.2885-15/1738085_692070914213393_1197767717_n.jpg"
},
 {
"date": "August 10, 2014",
"lat": 38.740877,
"lng": -90.303086,
"headline": "",
"type": window.markerTypes.gov,
"contentType": window.infoTypes.video,
"link": "",
"content": "zUXqPDT8hr4"
},
    ]
  },
  {
    "date": "August 11, 2014",
    "lat": 38.749613,
    "lng": -90.279912,
    "markers": [
      {
"date": "August 11, 2014",
"lat": 38.749613,
"lng": -90.279912,
"headline": "Protests continue two days after Michael Brown's death",
"type": window.markerTypes.social,
"contentType": window.infoTypes.picture,
"link": "",
"content": "https://c4.staticflickr.com/4/3860/14794832317_db2b6eeb98_b.jpg"
},
    {
"date": "August 11, 2014",
"lat": 38.749613,
"lng": -90.279912,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.picture,
"link": "",
"content": "http://i.imgur.com/6kah8zq.png"
},
   {
"date": "August 11, 2014",
"lat": 38.735419,
"lng": -90.278376,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.tweet,
"link": "",
"content": '

It's just past 1 a.m. in #Ferguson, and this is what we're seeing pic.twitter.com/ZiKgGP2TGq
— Alan Blinder (@alanblinder) August 16, 2014
'
},
    ]
  },
  {
    "date": "August 12, 2014",
    "lat": 38.648863,
    "lng": -90.338427,
    "markers": [
      {
"date": "August 12, 2014",
"lat": 38.648863,
"lng": -90.338427,
"headline": "",
"type": window.markerTypes.social,
"contentType": window.infoTypes.tweet,
"link": "",
"content": "

love this <3 RT @stevenjhsieh: Man waving a Palestinian flag in #Ferguson "because they supported St. Louis." pic.twitter.com/tn96pvFEXF
— Grim_Chickn (@grm_chikn) August 16, 2014
"
},
{
"date": "August 12, 2014",
"lat": 38.648863,
"lng": -90.338427,
"headline": "",
"type": window.markerTypes.gov,
"contentType": window.infoTypes.video,
"link": "",
"content": "http://i.imgur.com/LsA3JUc.png"
},
{
"date": "August 12, 2014",
"lat": 38.738455,
"lng":  -90.277542,
"headline": "Protest continue to rock Ferguson",
"type": window.markerTypes.social,
"contentType": window.infoTypes.video,
"link": "",
"content": "qXhtvd0o2Fw"
},
    ]
  },
  {
    "date": "August 20th",
    "lat": 38.73857,
    "lng": -90.27387,
    "markers": [
    ]
  },
  {
    "date": "August 25th",
    "lat": 38.73857,
    "lng": -90.27387,
    "markers": [
    ]
  }
];
<|endoftext|>


<commit_before>/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that can be found in the LICENSE file. */
/* global define */
"use strict";

var isCordova;
var isWin;

$(document).ready(function() {
  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }

  var locale = getParameterByName("locale");

  var extSettings;
  loadExtSettings();

  isCordova = parent.isCordova;
  isWin = parent.isWin;

  var $htmlContent = $("#htmlContent");

  var styles = ['', 'solarized-dark', 'github', 'metro-vibes', 'clearness', 'clearness-dark'];
  var currentStyleIndex = 0;
  if (extSettings && extSettings.styleIndex) {
    currentStyleIndex = extSettings.styleIndex;
  }

  var zoomSteps = ['zoomSmallest', 'zoomSmaller', 'zoomSmall', 'zoomDefault', 'zoomLarge', 'zoomLarger', 'zoomLargest'];
  var currentZoomState = 3;
  if (extSettings && extSettings.zoomState) {
    currentZoomState = extSettings.zoomState;
  }

  $htmlContent.removeClass();
  $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);

  $("#changeStyleButton").bind('click', function() {
    currentStyleIndex = currentStyleIndex + 1;
    if (currentStyleIndex >= styles.length) {
      currentStyleIndex = 0;
    }
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  $("#zoomInButton").bind('click', function() {
    currentZoomState++;
    if (currentZoomState >= zoomSteps.length) {
      currentZoomState = 6;
    }
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  $("#zoomOutButton").bind('click', function() {
    currentZoomState--;
    if (currentZoomState < 0) {
      currentZoomState = 0;
    }
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  $("#zoomResetButton").bind('click', function() {
    currentZoomState = 3;
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  //TODO making all links open in the user default browser
  $htmlContent.find("a").bind('click', function(e) {
    e.preventDefault();
    //TSCORE.openLinkExternally($(this).attr("href"));
  });

  $("#printButton").on("click", function() {
    $(".dropdown-menu").dropdown('toggle');
    window.print();
  });

  if (isCordova) {
    $("#printButton").hide();
  }

  // Init internationalization
  $.i18n.init({
    ns: {namespaces: ['ns.viewerMD']},
    debug: true,
    lng: locale,
    fallbackLng: 'en_US'
  }, function() {
    $('[data-i18n]').i18n();
  });

  function saveExtSettings() {
    var settings = {
      "styleIndex": currentStyleIndex,
      "zoomState":  currentZoomState
    };
    localStorage.setItem('viewerMDSettings', JSON.stringify(settings));
  }

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem("viewerMDSettings"));
  }

});

function setContent(content, fileDirectory) {
  var $htmlContent = $('#htmlContent');
  $htmlContent.append(content);

  // fixing embedding of local images
  $htmlContent.find("img[src]").each(function() {
    var currentSrc = $(this).attr("src");
    if (currentSrc.indexOf("http://") === 0 ||
        currentSrc.indexOf("https://") === 0 ||
        currentSrc.indexOf("file://") === 0 ||
        currentSrc.indexOf("data:") === 0) {
      // do nothing if src begins with http(s):// or data:
    } else {
      var path = "file://" + fileDirectory + (isWin ? "\\" : "/") + currentSrc;
      $(this).attr("src", path);
    }
  });
}
<commit_msg>disabling all links in html content<commit_after>/* Copyright (c) 2012-2015 The TagSpaces Authors. All rights reserved.
 * Use of this source code is governed by a AGPL3 license that can be found in the LICENSE file. */
/* global define */
"use strict";

var isCordova;
var isWin;

$(document).ready(function() {
  function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
      results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
  }

  var locale = getParameterByName("locale");

  var extSettings;
  loadExtSettings();

  isCordova = parent.isCordova;
  isWin = parent.isWin;

  var $htmlContent = $("#htmlContent");

  var styles = ['', 'solarized-dark', 'github', 'metro-vibes', 'clearness', 'clearness-dark'];
  var currentStyleIndex = 0;
  if (extSettings && extSettings.styleIndex) {
    currentStyleIndex = extSettings.styleIndex;
  }

  var zoomSteps = ['zoomSmallest', 'zoomSmaller', 'zoomSmall', 'zoomDefault', 'zoomLarge', 'zoomLarger', 'zoomLargest'];
  var currentZoomState = 3;
  if (extSettings && extSettings.zoomState) {
    currentZoomState = extSettings.zoomState;
  }

  $htmlContent.removeClass();
  $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);

  $("#changeStyleButton").bind('click', function() {
    currentStyleIndex = currentStyleIndex + 1;
    if (currentStyleIndex >= styles.length) {
      currentStyleIndex = 0;
    }
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  $("#zoomInButton").bind('click', function() {
    currentZoomState++;
    if (currentZoomState >= zoomSteps.length) {
      currentZoomState = 6;
    }
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  $("#zoomOutButton").bind('click', function() {
    currentZoomState--;
    if (currentZoomState < 0) {
      currentZoomState = 0;
    }
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  $("#zoomResetButton").bind('click', function() {
    currentZoomState = 3;
    $htmlContent.removeClass();
    $htmlContent.addClass('markdown ' + styles[currentStyleIndex] + " " + zoomSteps[currentZoomState]);
    saveExtSettings();
  });

  $("#printButton").on("click", function() {
    $(".dropdown-menu").dropdown('toggle');
    window.print();
  });

  if (isCordova) {
    $("#printButton").hide();
  }

  // Init internationalization
  $.i18n.init({
    ns: {namespaces: ['ns.viewerMD']},
    debug: true,
    lng: locale,
    fallbackLng: 'en_US'
  }, function() {
    $('[data-i18n]').i18n();
  });

  function saveExtSettings() {
    var settings = {
      "styleIndex": currentStyleIndex,
      "zoomState":  currentZoomState
    };
    localStorage.setItem('viewerMDSettings', JSON.stringify(settings));
  }

  function loadExtSettings() {
    extSettings = JSON.parse(localStorage.getItem("viewerMDSettings"));
  }

});

function setContent(content, fileDirectory) {
  var $htmlContent = $('#htmlContent');
  $htmlContent.append(content);

  // fixing embedding of local images
  $htmlContent.find("img[src]").each(function() {
    var currentSrc = $(this).attr("src");
    if (currentSrc.indexOf("http://") === 0 ||
        currentSrc.indexOf("https://") === 0 ||
        currentSrc.indexOf("file://") === 0 ||
        currentSrc.indexOf("data:") === 0) {
      // do nothing if src begins with http(s):// or data:
    } else {
      var path = "file://" + fileDirectory + (isWin ? "\\" : "/") + currentSrc;
      $(this).attr("src", path);
    }
  });

  $("#htmlContent").find("a").bind('click', function(e) {
    e.preventDefault();
    //TODO making all links open in the user default browser
    //message to parent openLinkExternally($(this).attr("href"));
  });
}
<|endoftext|>


<commit_before>export const pattern = /\\n/gim;
export const name = 'NEWLINE';

export default {
  name,
  pattern
};
<commit_msg>removed newline regex flags<commit_after>export const pattern = /\\n/g;
export const name = 'NEWLINE';

export default {
  name,
  pattern
};
<|endoftext|>


<commit_before>// From rust:
/* global resourcesSuffix */

var currentTheme = document.getElementById("themeStyle");
var mainTheme = document.getElementById("mainThemeStyle");

var savedHref = [];

function hasClass(elem, className) {
    return elem && elem.classList && elem.classList.contains(className);
}

function addClass(elem, className) {
    if (!elem || !elem.classList) {
        return;
    }
    elem.classList.add(className);
}

function removeClass(elem, className) {
    if (!elem || !elem.classList) {
        return;
    }
    elem.classList.remove(className);
}

function onEach(arr, func, reversed) {
    if (arr && arr.length > 0 && func) {
        var length = arr.length;
        var i;
        if (reversed !== true) {
            for (i = 0; i < length; ++i) {
                if (func(arr[i]) === true) {
                    return true;
                }
            }
        } else {
            for (i = length - 1; i >= 0; --i) {
                if (func(arr[i]) === true) {
                    return true;
                }
            }
        }
    }
    return false;
}

function onEachLazy(lazyArray, func, reversed) {
    return onEach(
        Array.prototype.slice.call(lazyArray),
        func,
        reversed);
}

function hasOwnProperty(obj, property) {
    return Object.prototype.hasOwnProperty.call(obj, property);
}

function usableLocalStorage() {
    // Check if the browser supports localStorage at all:
    if (typeof Storage === "undefined") {
        return false;
    }
    // Check if we can access it; this access will fail if the browser
    // preferences deny access to localStorage, e.g., to prevent storage of
    // "cookies" (or cookie-likes, as is the case here).
    try {
        return window.localStorage !== null && window.localStorage !== undefined;
    } catch(err) {
        // Storage is supported, but browser preferences deny access to it.
        return false;
    }
}

function updateLocalStorage(name, value) {
    if (usableLocalStorage()) {
        localStorage[name] = value;
    } else {
        // No Web Storage support so we do nothing
    }
}

function getCurrentValue(name) {
    if (usableLocalStorage() && localStorage[name] !== undefined) {
        return localStorage[name];
    }
    return null;
}

function switchTheme(styleElem, mainStyleElem, newTheme, saveTheme) {
    var fullBasicCss = "rustdoc" + resourcesSuffix + ".css";
    var fullNewTheme = newTheme + resourcesSuffix + ".css";
    var newHref = mainStyleElem.href.replace(fullBasicCss, fullNewTheme);

    if (styleElem.href === newHref) {
        return;
    }

    var found = false;
    if (savedHref.length === 0) {
        onEachLazy(document.getElementsByTagName("link"), function(el) {
            savedHref.push(el.href);
        });
    }
    onEach(savedHref, function(el) {
        if (el === newHref) {
            found = true;
            return true;
        }
    });
    if (found === true) {
        styleElem.href = newHref;
        // If this new value comes from a system setting or from the previously
        // saved theme, no need to save it.
        if (saveTheme === true) {
            updateLocalStorage("rustdoc-theme", newTheme);
        }
    }
}

function useSystemTheme(value) {
    if (value === undefined) {
        value = true;
    }

    updateLocalStorage("rustdoc-use-system-theme", value);

    // update the toggle if we're on the settings page
    var toggle = document.getElementById("use-system-theme");
    if (toggle && toggle instanceof HTMLInputElement) {
        toggle.checked = value;
    }
}

var updateSystemTheme = (function() {
    if (!window.matchMedia) {
        // fallback to the CSS computed value
        return function() {
            let cssTheme = getComputedStyle(document.documentElement)
                .getPropertyValue('content');

            switchTheme(
                currentTheme,
                mainTheme,
                JSON.parse(cssTheme) || light,
                true
            );
        };
    }

    // only listen to (prefers-color-scheme: dark) because light is the default
    var mql = window.matchMedia("(prefers-color-scheme: dark)");

    function handlePreferenceChange(mql) {
        // maybe the user has disabled the setting in the meantime!
        if (getCurrentValue("rustdoc-use-system-theme") !== "false") {
            var lightTheme = getCurrentValue("rustdoc-preferred-light-theme") || "light";
            var darkTheme = getCurrentValue("rustdoc-preferred-dark-theme") || "dark";

            if (mql.matches) {
                // prefers a dark theme
                switchTheme(currentTheme, mainTheme, darkTheme, true);
            } else {
                // prefers a light theme, or has no preference
                switchTheme(currentTheme, mainTheme, lightTheme, true);
            }

            // note: we save the theme so that it doesn't suddenly change when
            // the user disables "use-system-theme" and reloads the page or
            // navigates to another page
        }
    }

    mql.addListener(handlePreferenceChange);

    return function() {
        handlePreferenceChange(mql);
    };
})();

if (getCurrentValue("rustdoc-use-system-theme") !== "false" && window.matchMedia) {
    // call the function to initialize the theme at least once!
    updateSystemTheme();
} else {
    switchTheme(
        currentTheme,
        mainTheme,
        getCurrentValue("rustdoc-theme") || "light",
        false
    );
}
<commit_msg>Set preferred-dark-theme to the last dark theme<commit_after>// From rust:
/* global resourcesSuffix */

var darkThemes = ["dark", "ayu"];
var currentTheme = document.getElementById("themeStyle");
var mainTheme = document.getElementById("mainThemeStyle");
var localStoredTheme = getCurrentValue("rustdoc-theme");

var savedHref = [];

function hasClass(elem, className) {
    return elem && elem.classList && elem.classList.contains(className);
}

function addClass(elem, className) {
    if (!elem || !elem.classList) {
        return;
    }
    elem.classList.add(className);
}

function removeClass(elem, className) {
    if (!elem || !elem.classList) {
        return;
    }
    elem.classList.remove(className);
}

function onEach(arr, func, reversed) {
    if (arr && arr.length > 0 && func) {
        var length = arr.length;
        var i;
        if (reversed !== true) {
            for (i = 0; i < length; ++i) {
                if (func(arr[i]) === true) {
                    return true;
                }
            }
        } else {
            for (i = length - 1; i >= 0; --i) {
                if (func(arr[i]) === true) {
                    return true;
                }
            }
        }
    }
    return false;
}

function onEachLazy(lazyArray, func, reversed) {
    return onEach(
        Array.prototype.slice.call(lazyArray),
        func,
        reversed);
}

function hasOwnProperty(obj, property) {
    return Object.prototype.hasOwnProperty.call(obj, property);
}

function usableLocalStorage() {
    // Check if the browser supports localStorage at all:
    if (typeof Storage === "undefined") {
        return false;
    }
    // Check if we can access it; this access will fail if the browser
    // preferences deny access to localStorage, e.g., to prevent storage of
    // "cookies" (or cookie-likes, as is the case here).
    try {
        return window.localStorage !== null && window.localStorage !== undefined;
    } catch(err) {
        // Storage is supported, but browser preferences deny access to it.
        return false;
    }
}

function updateLocalStorage(name, value) {
    if (usableLocalStorage()) {
        localStorage[name] = value;
    } else {
        // No Web Storage support so we do nothing
    }
}

function getCurrentValue(name) {
    if (usableLocalStorage() && localStorage[name] !== undefined) {
        return localStorage[name];
    }
    return null;
}

function switchTheme(styleElem, mainStyleElem, newTheme, saveTheme) {
    var fullBasicCss = "rustdoc" + resourcesSuffix + ".css";
    var fullNewTheme = newTheme + resourcesSuffix + ".css";
    var newHref = mainStyleElem.href.replace(fullBasicCss, fullNewTheme);

    if (styleElem.href === newHref) {
        return;
    }

    var found = false;
    if (savedHref.length === 0) {
        onEachLazy(document.getElementsByTagName("link"), function(el) {
            savedHref.push(el.href);
        });
    }
    onEach(savedHref, function(el) {
        if (el === newHref) {
            found = true;
            return true;
        }
    });
    if (found === true) {
        styleElem.href = newHref;
        // If this new value comes from a system setting or from the previously
        // saved theme, no need to save it.
        if (saveTheme === true) {
            updateLocalStorage("rustdoc-theme", newTheme);
        }
    }
}

function useSystemTheme(value) {
    if (value === undefined) {
        value = true;
    }

    updateLocalStorage("rustdoc-use-system-theme", value);

    // update the toggle if we're on the settings page
    var toggle = document.getElementById("use-system-theme");
    if (toggle && toggle instanceof HTMLInputElement) {
        toggle.checked = value;
    }
}

var updateSystemTheme = (function() {
    if (!window.matchMedia) {
        // fallback to the CSS computed value
        return function() {
            let cssTheme = getComputedStyle(document.documentElement)
                .getPropertyValue('content');

            switchTheme(
                currentTheme,
                mainTheme,
                JSON.parse(cssTheme) || light,
                true
            );
        };
    }

    // only listen to (prefers-color-scheme: dark) because light is the default
    var mql = window.matchMedia("(prefers-color-scheme: dark)");

    function handlePreferenceChange(mql) {
        // maybe the user has disabled the setting in the meantime!
        if (getCurrentValue("rustdoc-use-system-theme") !== "false") {
            var lightTheme = getCurrentValue("rustdoc-preferred-light-theme") || "light";
            var darkTheme = getCurrentValue("rustdoc-preferred-dark-theme") || "dark";

            if (mql.matches) {
                // prefers a dark theme
                switchTheme(currentTheme, mainTheme, darkTheme, true);
            } else {
                // prefers a light theme, or has no preference
                switchTheme(currentTheme, mainTheme, lightTheme, true);
            }

            // note: we save the theme so that it doesn't suddenly change when
            // the user disables "use-system-theme" and reloads the page or
            // navigates to another page
        }
    }

    mql.addListener(handlePreferenceChange);

    return function() {
        handlePreferenceChange(mql);
    };
})();

if (getCurrentValue("rustdoc-use-system-theme") !== "false" && window.matchMedia) {
    // update the preferred dark theme if the user is already using a dark theme
    // See https://github.com/rust-lang/rust/pull/77809#issuecomment-707875732
    if (getCurrentValue("rustdoc-use-system-theme") === null
        && getCurrentValue("rustdoc-preferred-dark-theme") === null
        && darkThemes.indexOf(localStoredTheme) >= 0) {
        updateLocalStorage("rustdoc-preferred-dark-theme", localStoredTheme);
    }

    // call the function to initialize the theme at least once!
    updateSystemTheme();
} else {
    switchTheme(
        currentTheme,
        mainTheme,
        getCurrentValue("rustdoc-theme") || "light",
        false
    );
}
<|endoftext|>


<commit_before>(function(global, undef) {

	Core.declare("Assert", {

		/**
		 * Adds a new assertion check
		 *
		 * @param func {Function} Function for the test. Must return boolean.
		 * @param methodName {String} Name of the method to attach.
		 *
		 *
		 */
		add : function(func, methodName, msg) {
			// Attach given method as is to assertion
			this[methodName] = func;
			if(func.displayName == null) {
				func.displayName = "Assert." + methodName;
			}

			// Build assert method name
			var assertName = "assert";
			if (methodName.substring(0,2) == "is") {
				assertName += methodName.substring(2);
			} else {
				assertName += methodName.charAt(0).toUpperCase() + methodName.substring(1);
			}

			// Wrap method throw error for simplified throwing of exceptions in type checks
			if (func.length == 1) {
				this[assertName] = function(value) {
					if (!func(value)) {
						throw new TypeError(msg);
					}
				};
			} else {
				this[assertName] = function(value, compareTo) {
					if (!func(value, compareTo)) {
						throw new TypeError(msg.replace("%1", ""+compareTo));
					}
				};
			}

			this[assertName].displayName = "Assert." + assertName;
		}
	});

	// Alias for better compression
	var Assert = global.Assert;
	var toString = Object.prototype.toString;

	// Build mapping list for all native global objects
	var classToString = {
		Object : toString.call({}),
		Array : toString.call([]),
		String : toString.call(''),
		Boolean : toString.call(true),
		Number : toString.call(1),
		Date : toString.call(new Date),
		RegExp : toString.call(/x/),
		Function : toString.call(function(){})
	};

	var stringToClass = {};
	for (var cls in classToString) {
		stringToClass[classToString[cls]] = cls;
	}

	Assert.add(function(value) {
		var type = typeof value;
		return value == null || type == "boolean" || type == "number" || type == "string";
	}, "isPrimitive", "Not a primitive value!");

	Assert.add(function(value) { return typeof value == "boolean"; }, "isBoolean", "Not boolean!");
	Assert.add(function(value) { return value === true; }, "isTrue", "Not 'true'!");
	Assert.add(function(value) { return value === false; },"isFalse", "Not 'false'!");

	Assert.add(function(value) { return typeof value == "string"; }, "isString", "Not a string!");
	Assert.add(function(value) { return typeof value == "string" && value.length > 0; }, "isNonEmptyString", "Not a non empty string!");

	Assert.add(function(value) { return typeof value == "number" && isFinite(value); }, "isNumber", "Not a number!");
	Assert.add(function(value) { return value === 0; }, "isZero", "Not zero!");
	Assert.add(function(value) { return parseInt(value) === value; }, "isInteger", "Not an integer!");

	Assert.add(function(value) { return typeof value == "object"; }, "isObject", "Not an object!");
	Assert.add(function(value) { return value === null; }, "isNull", "Not 'null'!");
	Assert.add(function(value) { return value !== null; }, "isNotNull", "Is 'null'!");

	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Object"; }, "isMap", "Not a map (plain object)!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Array"; }, "isArray", "Not an array!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Function"; }, "isFunction", "Not a function!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "RegExp"; }, "isRegExp", "Not a regular expression!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Date"; }, "isDate", "Not a date object!");

	Assert.add(function(value) { return value && value.nodeType != undef; }, "isNode", "Not a node!");
	Assert.add(function(value) { return value && value.nodeType == 1; }, "isElement", "Not an element!");
	Assert.add(function(value) { return value && value.nodeType == 3; }, "isTextNode", "Not a text node!");
	Assert.add(function(value) { return value && value.nodeType == 9; }, "isDocument", "Not a document!");

	Assert.add(function(value, regexp) {
		return typeof value == "string" && !!value.match(regexp);
	}, "matchesRegExp", "Does not match regular expression!");

	Assert.add(function(value, func) {
		var ret = true;
		try{
			ret = !!func(value);
		} catch(ex) {
			ret = false;
		}

		return ret;
	}, "isAcceptedBy", "Is not accepted by defined check function!");

	Assert.add(function(value, list) {
		return list.indexOf(value) != -1;
	}, "isInList", "Is not in specified list!");

})(this);

<commit_msg>Minor code tweaks<commit_after>(function(global, undef) {

	Core.declare("Assert", {

		/**
		 * Adds a new assertion check
		 *
		 * @param func {Function} Function for the test. Must return boolean.
		 * @param methodName {String} Name of the method to attach.
		 * @param assertMsg {}
		 *
		 */
		add : function(func, methodName, assertMsg) {
			// Attach given method as is to assertion
			this[methodName] = func;
			if(func.displayName == null) {
				func.displayName = "Assert." + methodName;
			}

			// Build assert method name
			var assertName = "assert";
			if (methodName.substring(0,2) == "is") {
				assertName += methodName.substring(2);
			} else {
				assertName += methodName.charAt(0).toUpperCase() + methodName.substring(1);
			}

			// Wrap method throw error for simplified throwing of exceptions in type checks
			if (func.length == 1) {
				this[assertName] = function(value, customMsg) {
					if (!func(value)) {
						throw new TypeError('Value: "' + value + '": ' + (customMsg||assertMsg));
					}
				};
			} else {
				this[assertName] = function(value, compareTo, customMsg) {
					if (!func(value, compareTo)) {
						throw new TypeError('Value: "' + value + '": ' + (customMsg||assertMsg.replace("%1", ""+compareTo)));
					}
				};
			}

			this[assertName].displayName = "Assert." + assertName;
		}
	});

	// Alias for better compression
	var Assert = global.Assert;
	var toString = Object.prototype.toString;

	// Build mapping list for all native global objects
	var classToString = {
		Object : toString.call({}),
		Array : toString.call([]),
		String : toString.call(''),
		Boolean : toString.call(true),
		Number : toString.call(1),
		Date : toString.call(new Date),
		RegExp : toString.call(/x/),
		Function : toString.call(function(){})
	};

	var stringToClass = {};
	for (var cls in classToString) {
		stringToClass[classToString[cls]] = cls;
	}

	Assert.add(function(value) {
		var type = typeof value;
		return value == null || type == "boolean" || type == "number" || type == "string";
	}, "isPrimitive", "Not a primitive value!");

	Assert.add(function(value) { return typeof value == "boolean"; }, "isBoolean", "Not boolean!");
	Assert.add(function(value) { return value === true; }, "isTrue", "Not 'true'!");
	Assert.add(function(value) { return value === false; },"isFalse", "Not 'false'!");

	Assert.add(function(value) { return typeof value == "string"; }, "isString", "Not a string!");
	Assert.add(function(value) { return typeof value == "string" && value.length > 0; }, "isNonEmptyString", "Not a non empty string!");

	Assert.add(function(value) { return typeof value == "number" && isFinite(value); }, "isNumber", "Not a number!");
	Assert.add(function(value) { return value === 0; }, "isZero", "Not zero!");
	Assert.add(function(value) { return parseInt(value) === value; }, "isInteger", "Not an integer!");

	Assert.add(function(value) { return typeof value == "object"; }, "isObject", "Not an object!");
	Assert.add(function(value) { return value === null; }, "isNull", "Not 'null'!");
	Assert.add(function(value) { return value !== null; }, "isNotNull", "Is 'null'!");

	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Object"; }, "isMap", "Not a map (plain object)!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Array"; }, "isArray", "Not an array!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Function"; }, "isFunction", "Not a function!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "RegExp"; }, "isRegExp", "Not a regular expression!");
	Assert.add(function(value) { return stringToClass[toString.call(value)] == "Date"; }, "isDate", "Not a date object!");

	Assert.add(function(value) { return value && value.nodeType != undef; }, "isNode", "Not a node!");
	Assert.add(function(value) { return value && value.nodeType == 1; }, "isElement", "Not an element!");
	Assert.add(function(value) { return value && value.nodeType == 3; }, "isTextNode", "Not a text node!");
	Assert.add(function(value) { return value && value.nodeType == 9; }, "isDocument", "Not a document!");

	Assert.add(function(value, regexp) {
		return typeof value == "string" && !!value.match(regexp);
	}, "matchesRegExp", "Does not match regular expression %1!");

	Assert.add(function(value, func) {
		var ret = true;
		try{
			ret = !!func(value);
		} catch(ex) {
			ret = false;
		}

		return ret;
	}, "isAcceptedBy", "Is not accepted by defined check function!");

	Assert.add(function(value, list) {
		return list.indexOf(value) != -1;
	}, "isInList", "Is not in specified list!");

})(this);

<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import Parser from 'json-schema-parser'
import Immutable from 'immutable'
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'
import FlatButton from 'material-ui/FlatButton'
import TextField from 'material-ui/TextField'

import AppBaseComponent from '../components/AppBaseComponent'

import schema from '../../../../docs/schema/schema.json'

export default class ApiSpec extends AppBaseComponent {
  static propTypes = {
  }

  levelColomnStyle = { width: '10px' }
  typeColomnStyle = { width: '50px' }

  constructor(props) {
    super(props)

    this.state = {
      searchText: ''
    }
  }

  handleChange = (event) => {
    this.setState({
      searchText: event.target.value,
    })
  }

  createTable(name, property) {
    const rows = property.get('properties').map((v, k) => this.propertyRows(k, v, 1)).toList().flatMap((v) => v)
    return (

{name}

title {property.get('title')}

description {property.get('description')}

stability {property.get('stability')}

strictProperties {property.get('strictProperties') ? 'true' : 'false'}

          <TableHeader adjustForCheckbox={false} displaySelectAll={false}>
            <TableRow>
              <TableHeaderColumn style={Object.assign({}, this.levelColomnStyle)}>level</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>name</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({}, this.typeColomnStyle)}>type</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>description</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>format</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>pattern</TableHeaderColumn>
            </TableRow>
          </TableHeader>
          <TableBody displayRowCheckbox={false}>
            {rows}
          </TableBody>

    )
  }

  propertyRows(name, property, level) {
    const description = property.get('description')
    const types = property.get('type') || Immutable.List.of()
    const format = property.get('format')
    const pattern = property.get('pattern')
    const itemsProperties = property.get('items') && property.get('items').get('properties') ? property.get('items').get('properties') : undefined
    const properties = property.get('properties') || itemsProperties
    const rows = Immutable.List.of(
      <TableRow key={`${level}${name}`} style={Object.assign({})}>
        <TableRowColumn style={Object.assign({}, this.levelColomnStyle, { paddingLeft: `${24 + ((level - 1) * 5)}px` })}>{level}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{name}</TableRowColumn>
        <TableRowColumn style={Object.assign({}, this.typeColomnStyle)}>{types.join(', ')}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{description}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{format}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{pattern}</TableRowColumn>
      </TableRow>
    )
    const children = properties ? properties.map((v, k) => this.propertyRows(k, v, level + 1) ).toList().flatMap((v) => v) : undefined
    return children ? rows.concat(children) : rows
  }

  render() {
    const spec = this.createTable('timecard', Immutable.fromJS(Parser.parse(schema)))
    return (

          <FlatButton label='TOP' onClick={() => {super.handleUrlChange('')}} />

          <TextField
            hintText='api1'
            floatingLabelText='search'
            value={this.state.searchText}
            onChange={this.handleChange}
          />

        {spec}

    )
  }
}
<commit_msg>propertiesの下のオブジェクトをリストで表示するように修正 errorオブジェクトはその他オブジェクトからの参照のため、表示しない<commit_after>import React, { PropTypes } from 'react'
import Parser from 'json-schema-parser'
import Immutable from 'immutable'
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table'
import FlatButton from 'material-ui/FlatButton'
import TextField from 'material-ui/TextField'

import AppBaseComponent from '../components/AppBaseComponent'

import schema from '../../../../docs/schema/schema.json'

export default class ApiSpec extends AppBaseComponent {
  static propTypes = {
  }

  levelColomnStyle = { width: '10px' }
  typeColomnStyle = { width: '50px' }

  constructor(props) {
    super(props)

    this.state = {
      searchText: ''
    }
  }

  handleChange = (event) => {
    this.setState({
      searchText: event.target.value,
    })
  }

  createTable(name, property) {
    const rows = property.get('properties').map((v, k) => this.propertyRows(k, v, 1)).toList().flatMap((v) => v)
    return (

{name}

title {property.get('title')}

description {property.get('description')}

stability {property.get('stability')}

strictProperties {property.get('strictProperties') ? 'true' : 'false'}

          <TableHeader adjustForCheckbox={false} displaySelectAll={false}>
            <TableRow>
              <TableHeaderColumn style={Object.assign({}, this.levelColomnStyle)}>level</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>name</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({}, this.typeColomnStyle)}>type</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>description</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>format</TableHeaderColumn>
              <TableHeaderColumn style={Object.assign({})}>pattern</TableHeaderColumn>
            </TableRow>
          </TableHeader>
          <TableBody displayRowCheckbox={false}>
            {rows}
          </TableBody>

    )
  }

  propertyRows(name, property, level) {
    const description = property.get('description')
    const types = property.get('type') || Immutable.List.of()
    const format = property.get('format')
    const pattern = property.get('pattern')
    const itemsProperties = property.get('items') && property.get('items').get('properties') ? property.get('items').get('properties') : undefined
    const properties = property.get('properties') || itemsProperties
    const rows = Immutable.List.of(
      <TableRow key={`${level}${name}`} style={Object.assign({})}>
        <TableRowColumn style={Object.assign({}, this.levelColomnStyle, { paddingLeft: `${24 + ((level - 1) * 5)}px` })}>{level}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{name}</TableRowColumn>
        <TableRowColumn style={Object.assign({}, this.typeColomnStyle)}>{types.join(', ')}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{description}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{format}</TableRowColumn>
        <TableRowColumn style={Object.assign({})}>{pattern}</TableRowColumn>
      </TableRow>
    )
    const children = properties ? properties.map((v, k) => this.propertyRows(k, v, level + 1) ).toList().flatMap((v) => v) : undefined
    return children ? rows.concat(children) : rows
  }

  render() {
    const specs = Immutable.fromJS(Parser.parse(schema).properties).map((v, k) => {
      if (k === 'error') {
        // 共通のエラーオブジェクトなので無視
      } else {
        return this.createTable(k, v)
      }
    }).toList()
    return (

          <FlatButton label='TOP' onClick={() => {super.handleUrlChange('')}} />

          <TextField
            hintText='api1'
            floatingLabelText='search'
            value={this.state.searchText}
            onChange={this.handleChange}
          />

        {specs}

    )
  }
}
<|endoftext|>


<commit_before>#!/bin/sh

/*jshint -W015*/

'use strict';

var coap = require('../lib');

var args = [].concat(process.argv);

args.shift();
args.shift();

if (args.length === 0)
{
  console.log('Usage: node client.js [options] uri [< payload-file]');
  console.log();
  console.log('Request options:');
  console.log(' --type:          CON (default) or NON');
  console.log(' --code:          GET (default), POST, PUT or DELETE');
  console.log(' --accept:        media type from the Content-Format registry');
  console.log(' --contentFormat: media type from the Content-Format registry');
  console.log(' --observe:       true');
  console.log(' --ifNoneMatch:   true');
  console.log(' --ifMatch:       hex string (e.g. 00aa1e23)');
  console.log(' --eTag:          hex string (e.g. 00aa1e23)');
  console.log(' --uriHost:       IPv4 or IPv6 address (e.g. 2222::3)');
  console.log(' --uriPort:       number (e.g. 1337)');
  console.log(' --uriPath:       string (e.g. /foo/bar/baz)');
  console.log(' --uriQuery:      string (e.g. foo=bar&baz=1)');
  console.log(' --locationPath:  string (e.g. /foo/bar/baz)');
  console.log(' --locationQuery: string (e.g. foo=bar&baz=1)');
  console.log(' --payload:       string or - for stdin');
  console.log();
  console.log('Exchange options:');
  console.log(' --blockSize');
  console.log(' --maxRetransmit');
  console.log(' --transactionTimeout');
  console.log(' --exchangeTimeout');
  console.log();
  console.log('Example URIs:');
  console.log(' > coap://[2222::3]:5683/.well-known/core?href=foo&bar=baz');
  console.log(' > coap://127.0.0.1/.well-known/core');
  console.log(' > /temperature');

  process.exit(0);
}

var options = {
  type: coap.Message.Type.CON,
  code: coap.Message.Code.GET
};

if (args.length > 0 && args.length % 2 === 1)
{
  options.uri = args.pop();
}

while (args.length)
{
  var optionValue = args.pop();
  var optionName = args.pop().replace(/^-+/, '');

  switch (optionName)
  {
    case 'ifMatch':
    case 'eTag':
    case 'token':
      optionValue = createBufferFromHexString(optionValue);
      break;

    default:
      var numericValue = parseInt(optionValue, 10);

      if (!isNaN(numericValue))
      {
        optionValue = numericValue;
      }
      else if (optionValue === 'true' || optionValue === 'false')
      {
        optionValue = optionValue === 'true';
      }
  }

  options[optionName] = optionValue;
}

if (typeof options.observe !== 'undefined')
{
  options.observe = 0;
}

var responseCount = 0;
var responseLimit = options.limit > 0 ? options.limit : 0;

var client = new coap.Client();

client.on('error', prettyEvent('client', 'error'));
client.on('transaction timeout', function(req)
{
  console.log('[client#transaction timeout]');
  console.log(req.toPrettyString());
});
client.on('exchange timeout', function(req)
{
  console.log('[client#exchange timeout]');
  console.log(req.toPrettyString());
});
client.on('message sent', function(message, retries)
{
  console.log('[client#message sent]');

  if (retries > 0)
  {
    console.log(
      "Retransmission of %s (%d of %d)",
      message.getTransactionKey(),
      retries,
      options.maxRetransmit || 4
    );
  }
  else
  {
    console.log(message.toPrettyString());
  }
});
client.on('message received', function(message)
{
  console.log('[client#message received]');
  console.log(message.toPrettyString());
});

var req;

try
{
  req = coap.Message.fromObject(options);
}
catch (err)
{
  console.error(err.stack);
  process.exit(1);
}

if (options.payload === '-')
{
  process.stdin.resume();
  process.stdin.on('data', function(payload)
  {
    process.stdin.pause();

    req.setPayload(payload);

    client.request(req, options);
  });
}
else
{
  client.request(req, options);
}

req.on('error', prettyEvent('req', 'error'));
req.on('timeout', function()
{
  console.log('[req#timeout]');

  client.destroy();
});
req.on('acknowledged', prettyEvent('req', 'acknowledged'));
req.on('reset', prettyEvent('req', 'reset'));
req.on('cancelled', prettyEvent('req', 'cancelled'));
req.on('response', function(res)
{
  ++responseCount;

  console.log('[req#response]');
  console.log(res.toPrettyString());

  var isObserver = res.getObserve() > 0;

  if (!isObserver
    || (responseLimit > 0 && responseCount === responseLimit))
  {
    if (isObserver)
    {
      client.cancel(req);
    }

    client.destroy();
  }
});

function prettyEvent(eventSource, eventName)
{
  return function()
  {
    console.log('[%s#%s]', eventSource, eventName);

    if (arguments.length > 0)
    {
      console.log('%s', arguments[0].toString());
    }
  };
}

function createBufferFromHexString(hexString)
{
  var buffer = new Buffer(
    (hexString.length + (hexString.length % 2 ? 1 : 0)) / 2
  );

  for (var i = 0, b = 0, l = hexString.length; i < l; i += 2, b += 1)
  {
    buffer[b] = parseInt('0x' + hexString.substr(i, 2), 16);
  }

  return buffer;
}
<commit_msg>Corrected a file name in the usage help string.<commit_after>#!/bin/sh

/*jshint -W015*/

'use strict';

var coap = require('../lib');

var args = [].concat(process.argv);

args.shift();
args.shift();

if (args.length === 0)
{
  console.log('Usage: node coap-client.js [options] uri [< payload-file]');
  console.log();
  console.log('Request options:');
  console.log(' --type:          CON (default) or NON');
  console.log(' --code:          GET (default), POST, PUT or DELETE');
  console.log(' --accept:        media type from the Content-Format registry');
  console.log(' --contentFormat: media type from the Content-Format registry');
  console.log(' --observe:       true');
  console.log(' --ifNoneMatch:   true');
  console.log(' --ifMatch:       hex string (e.g. 00aa1e23)');
  console.log(' --eTag:          hex string (e.g. 00aa1e23)');
  console.log(' --uriHost:       IPv4 or IPv6 address (e.g. 2222::3)');
  console.log(' --uriPort:       number (e.g. 1337)');
  console.log(' --uriPath:       string (e.g. /foo/bar/baz)');
  console.log(' --uriQuery:      string (e.g. foo=bar&baz=1)');
  console.log(' --locationPath:  string (e.g. /foo/bar/baz)');
  console.log(' --locationQuery: string (e.g. foo=bar&baz=1)');
  console.log(' --payload:       string or - for stdin');
  console.log();
  console.log('Exchange options:');
  console.log(' --blockSize');
  console.log(' --maxRetransmit');
  console.log(' --transactionTimeout');
  console.log(' --exchangeTimeout');
  console.log();
  console.log('Example URIs:');
  console.log(' > coap://[2222::3]:5683/.well-known/core?href=foo&bar=baz');
  console.log(' > coap://127.0.0.1/.well-known/core');
  console.log(' > /temperature');

  process.exit(0);
}

var options = {
  type: coap.Message.Type.CON,
  code: coap.Message.Code.GET
};

if (args.length > 0 && args.length % 2 === 1)
{
  options.uri = args.pop();
}

while (args.length)
{
  var optionValue = args.pop();
  var optionName = args.pop().replace(/^-+/, '');

  switch (optionName)
  {
    case 'ifMatch':
    case 'eTag':
    case 'token':
      optionValue = createBufferFromHexString(optionValue);
      break;

    default:
      var numericValue = parseInt(optionValue, 10);

      if (!isNaN(numericValue))
      {
        optionValue = numericValue;
      }
      else if (optionValue === 'true' || optionValue === 'false')
      {
        optionValue = optionValue === 'true';
      }
  }

  options[optionName] = optionValue;
}

if (typeof options.observe !== 'undefined')
{
  options.observe = 0;
}

var responseCount = 0;
var responseLimit = options.limit > 0 ? options.limit : 0;

var client = new coap.Client();

client.on('error', prettyEvent('client', 'error'));
client.on('transaction timeout', function(req)
{
  console.log('[client#transaction timeout]');
  console.log(req.toPrettyString());
});
client.on('exchange timeout', function(req)
{
  console.log('[client#exchange timeout]');
  console.log(req.toPrettyString());
});
client.on('message sent', function(message, retries)
{
  console.log('[client#message sent]');

  if (retries > 0)
  {
    console.log(
      "Retransmission of %s (%d of %d)",
      message.getTransactionKey(),
      retries,
      options.maxRetransmit || 4
    );
  }
  else
  {
    console.log(message.toPrettyString());
  }
});
client.on('message received', function(message)
{
  console.log('[client#message received]');
  console.log(message.toPrettyString());
});

var req;

try
{
  req = coap.Message.fromObject(options);
}
catch (err)
{
  console.error(err.stack);
  process.exit(1);
}

if (options.payload === '-')
{
  process.stdin.resume();
  process.stdin.on('data', function(payload)
  {
    process.stdin.pause();

    req.setPayload(payload);

    client.request(req, options);
  });
}
else
{
  client.request(req, options);
}

req.on('error', prettyEvent('req', 'error'));
req.on('timeout', function()
{
  console.log('[req#timeout]');

  client.destroy();
});
req.on('acknowledged', prettyEvent('req', 'acknowledged'));
req.on('reset', prettyEvent('req', 'reset'));
req.on('cancelled', prettyEvent('req', 'cancelled'));
req.on('response', function(res)
{
  ++responseCount;

  console.log('[req#response]');
  console.log(res.toPrettyString());

  var isObserver = res.getObserve() > 0;

  if (!isObserver
    || (responseLimit > 0 && responseCount === responseLimit))
  {
    if (isObserver)
    {
      client.cancel(req);
    }

    client.destroy();
  }
});

function prettyEvent(eventSource, eventName)
{
  return function()
  {
    console.log('[%s#%s]', eventSource, eventName);

    if (arguments.length > 0)
    {
      console.log('%s', arguments[0].toString());
    }
  };
}

function createBufferFromHexString(hexString)
{
  var buffer = new Buffer(
    (hexString.length + (hexString.length % 2 ? 1 : 0)) / 2
  );

  for (var i = 0, b = 0, l = hexString.length; i < l; i += 2, b += 1)
  {
    buffer[b] = parseInt('0x' + hexString.substr(i, 2), 16);
  }

  return buffer;
}
<|endoftext|>


<commit_before>/* eslint-disable no-console */
/* eslint-disable no-fallthrough */
// <nowiki>

(function() {

	/* 反importScript */
	var whitelist = ["Xiplus", "A2093064-test", "A2093064-bot"];
	if (whitelist.indexOf(mw.config.get('wgUserName')) === -1) {
		alert("請勿importScript User:Xiplus/global.js！可能有未預期的危害發生。");
		return;
	}

	console.log("using User:Xiplus/global.js");

	mw.loader.using(['mediawiki.util']).done(function() {
		/* mediawiki.util */

		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/APIedit.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/APIedit.js&action=raw&ctype=text/javascript');
		mw.loader.using(['mediawiki.util']).done(function() {
			mw.loader.load('https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-ShowMessageNames.js&oldid=554722666&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		});
		// [[File:Krinkle_CVNSimpleOverlay_wiki.js]]
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Krinkle/Scripts/CVNSimpleOverlay_wiki.js&oldid=18174822&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		mw.loader.load("https://zh.wikipedia.org/w/index.php?title=User:Bluedeck/serve/edit-count.js&oldid=49623399&action=raw&ctype=text/javascript"); // 08:46, 5 August 2018 (UTC)
		mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-edittop.js&action=raw&ctype=text/javascript');

		/* wikiplus */
		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/w.js');
		mw.loader.load('https://wikiplus-app.com/Main.min.js');
		(function() {
			function wikiplusSettingdefaultSummary(w) {
				if (w.sectionNumber == -1) {
					return ' ';
				}
				if (w.sectionNumber === 0) {
					return '/* 首段 */ ';
				}
				return '/* ' + w.sectionName + ' */ ';
			}
			var wikiplusSetting = {
				"defaultSummary": wikiplusSettingdefaultSummary.toString().replace(/\s+/g, " "),
				"documatation": "http://zh.moegirl.org/User:%E5%A6%B9%E7%A9%BA%E9%85%B1/Wikiplus/%E8%AE%BE%E7%BD%AE%E8%AF%B4%E6%98%8E"
			};
			localStorage.setItem("Wikiplus_Settings", JSON.stringify(wikiplusSetting));
		})();

		/* XTools */
		mw.loader.load('https://www.mediawiki.org/w/index.php?title=XTools/ArticleInfo.js&oldid=2625658&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)

		/* FakeRollback */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/FakeRollback.js&action=raw&ctype=text/javascript');
		}

		/* AutoUndo */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndo.js&action=raw&ctype=text/javascript');
		}

		/* AutoUndoGlobal */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndoGlobal.js&action=raw&ctype=text/javascript');

		/* cvn-smart */
		// mw.loader.load('https://xiplus.ddns.net/wikipedia_rc/gadget.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/cvn-smart-gadget.js&action=raw&ctype=text/javascript');

		/* history-merge */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) !== -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/history-merge.js&action=raw&ctype=text/javascript');
		}

		/* list-user-last-active */
		switch (mw.config.get('wgDBname')) {
			case 'zhwiki':
				break;
			default:
				mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/list-user-last-active.js&action=raw&ctype=text/javascript');
				break;
		}

		/* smart rollback */
		if (typeof window.smartRollbackConfig === 'undefined') {
			window.smartRollbackConfig = {};
		}
		var smartRollbackConfig = window.smartRollbackConfig;
		smartRollbackConfig.toolLinkMethod = 'p-tb';
		smartRollbackConfig.editSummaries = ['批量回退無意義文字', '批量回退破壞'];
		mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/smart_rollback.js&action=raw&ctype=text/javascript');

		/* get-translatewiki-link */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/get-translatewiki-link.js&action=raw&ctype=text/javascript');

		/* UTC clock */
		mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript');

		/* CentralAuth */
		function showCentralAuth(username) {
			if (username === undefined) {
				return;
			}
			if (mw.util.isIPAddress(username, true)) {
				username = username.replace(/\/\d+$/, '');
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/meta/stalktoy/' + username,
					'全域封禁'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://whatismyipaddress.com/ip/' + username,
					'地理位置'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'http://whois.tanet.edu.tw/showWhoisPublic.php?queryString=' + username,
					'TANet'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/ipcheck/index.php?ip=' + username,
					'Proxy Checker'
				);
			} else {
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:CentralAuth') + '?target=' + encodeURIComponent(username),
					'全域帳號'
				);
			}
			mw.util.addPortletLink(
				'p-cactions',
				'https://xtools.wmflabs.org/globalcontribs/' + username,
				'全域貢獻 (xtools)'
			);
			mw.util.addPortletLink(
				'p-cactions',
				'https://tools.wmflabs.org/guc/?by=date&user=' + username,
				'全域貢獻 (guc)'
			);
		}
		if (mw.config.get('wgNamespaceNumber') === 2 || mw.config.get('wgNamespaceNumber') === 3) {
			showCentralAuth(mw.config.get('wgTitle').replace(/^([^/]+).*$/, '$1'));
		} else if (mw.config.get('wgRelevantUserName') !== null) {
			showCentralAuth(mw.config.get('wgRelevantUserName'));
		} else if (mw.config.get('wgCanonicalSpecialPageName') === 'Contributions') {
			showCentralAuth($('[name="target"]').val());
		}

		/* Admin list */
		switch (mw.config.get('wgDBname')) {
			// case 'zh_classicalwiki':
			// case 'zh_yuewiki':
			case 'zhwiki':
				// case 'zhwikibooks':
				// case 'zhwikinews':
				// case 'zhwikiquote':
				// case 'zhwikisource':
				// case 'zhwikivoyage':
				// case 'zhwiktionary':
				break;
			default:
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:Userlist') + '?group=sysop',
					'管理員列表'
				);
		}

		/* Twinkle */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'simplewiki':
			case 'test2wiki':
			case 'zh_classicalwiki':
			case 'zhwiki':
			case 'zhwikibooks':
			// case 'zhwikinews':
			case 'zhwikiquote':
			// case 'zhwikisource':
			case 'zhwikiversity':
			case 'zhwikivoyage':
			case 'zhwiktionary':
				break;
			default:
				console.log("Load Twinkle-global");
				mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Xiplus/Twinkle.js&action=raw&ctype=text/javascript');
				break;
		}

		/* Popup */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'zhwiki':
				break;
			default:
				console.log("載入 A2569875Popup");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopupsSetting_zh-hant.js&action=raw&ctype=text/javascript');
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopups.css&action=raw&ctype=text/css', 'text/css');
				break;
		}

		/* tagger */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			switch (mw.config.get('wgDBname')) {
				case 'enwiki':
					break;
				default:
					if (typeof (window.taggerConfig) == 'undefined') window.taggerConfig = {};
					var taggerConfig = window.taggerConfig;
					taggerConfig.noDeleteOnly = false;

					if (typeof (taggerConfig) == 'undefined') taggerConfig = {};
					taggerConfig.tags = [];
					taggerConfig.editSummary = [];
					taggerConfig.tags[1] = '{{delete|Vandalism}}';
					taggerConfig.editSummary[taggerConfig.tags[1]] = '+delete';
					taggerConfig.tags[2] = '{{delete|Nonsense}}';
					taggerConfig.editSummary[taggerConfig.tags[2]] = '+delete';
					taggerConfig.tags[3] = '{{delete|Vandalism. Created by LTA from zhwiki.}}';
					taggerConfig.editSummary[taggerConfig.tags[3]] = '+delete';
					taggerConfig.tags.other = 'This is used for the option you have to select to be able to insert a custom template';
					mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/tagger.js&action=raw&ctype=text/javascript');
					break;
			}
		}

		/* 側欄 */
		mw.util.addPortletLink(
			'p-tb',
			'/wiki/Special:PrefixIndex/' + mw.config.get('wgPageName'),
			'前綴索引',
			't-prefixindex',
			'',
			'',
			$('#t-specialpages')
		);

		if (mw.config.get("wgNamespaceNumber") == 8) {
			mw.util.addPortletLink(
				'p-cactions',
				'https://translatewiki.net/wiki/' + mw.config.get("wgPageName").split("/")[0] + '/zh-hant?action=edit',
				'translatewiki'
			);
		}

		mw.loader.using(['mediawiki.api']).done(function() {
			new mw.Api().get({
				action: "query",
				format: "json",
				list: "logevents",
				leprop: "comment|type",
				letype: "delete",
				letitle: mw.config.get('wgPageName')
			}).then(function(data) {
				for (var i = 0; i < data.query.logevents.length; i++) {
					var comment = data.query.logevents[i].comment;
					console.log(comment);
				}
			});
		});

		/* mediawiki.util */
	});

	/* CurIDLink */
	mw.loader.using(['mediawiki.api', 'mediawiki.ForeignApi', 'mediawiki.notify']).then(function() {
		if (mw.config.get('wgDBname') === 'metawiki') {
			var api = new mw.Api();
		} else {
			var api = new mw.ForeignApi('//meta.wikimedia.org/w/api.php');
		}
		api.loadMessagesIfMissing(['Link-by-id', 'Link-by-id-desc']).then(function() {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=MediaWiki:Gadget-CurIDLink.js&action=raw&ctype=text/javascript');
		}, function() {
			mw.notify('Load CurIDLink messages failed', { type: 'error' })
		});
	}, function() {
		console.error('Load CurIDLink dependencies failed');
	});

	/* shortURL */
	mw.loader.using(['mediawiki.util', 'oojs-ui', 'mediawiki.ForeignApi', 'mediawiki.notify']).done(function() {
		mw.loader.getScript('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript').then(function() {
			mw.loader.load('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-shortURL.js&action=raw&ctype=text/javascript');
		});
	});

	console.log("global.js end");

})();

// </nowiki>
<commit_msg>Update interface-global.js<commit_after>/* eslint-disable no-console */
/* eslint-disable no-fallthrough */
// <nowiki>

(function() {

	/* 反importScript */
	var whitelist = ["Xiplus", "A2093064-test", "A2093064-bot"];
	if (whitelist.indexOf(mw.config.get('wgUserName')) === -1) {
		alert("請勿importScript User:Xiplus/global.js！可能有未預期的危害發生。");
		return;
	}

	console.log("using User:Xiplus/global.js");

	mw.loader.using(['mediawiki.util']).done(function() {
		/* mediawiki.util */

		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/APIedit.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/APIedit.js&action=raw&ctype=text/javascript');
		mw.loader.using(['mediawiki.util']).done(function() {
			mw.loader.load('https://en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-ShowMessageNames.js&oldid=554722666&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		});
		// [[File:Krinkle_CVNSimpleOverlay_wiki.js]]
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Krinkle/Scripts/CVNSimpleOverlay_wiki.js&oldid=18174822&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)
		mw.loader.load("https://zh.wikipedia.org/w/index.php?title=User:Bluedeck/serve/edit-count.js&oldid=49623399&action=raw&ctype=text/javascript"); // 08:46, 5 August 2018 (UTC)
		mw.loader.load('//en.wikipedia.org/w/index.php?title=MediaWiki:Gadget-edittop.js&action=raw&ctype=text/javascript');

		/* wikiplus */
		// mw.loader.load('https://xiplus.ddns.net/Xiplus-zhWP/w.js');
		mw.loader.load('https://wikiplus-app.com/Main.min.js');
		(function() {
			function wikiplusSettingdefaultSummary(w) {
				if (w.sectionNumber == -1) {
					return ' ';
				}
				if (w.sectionNumber === 0) {
					return '/* 首段 */ ';
				}
				return '/* ' + w.sectionName + ' */ ';
			}
			var wikiplusSetting = {
				"defaultSummary": wikiplusSettingdefaultSummary.toString().replace(/\s+/g, " "),
				"documatation": "http://zh.moegirl.org/User:%E5%A6%B9%E7%A9%BA%E9%85%B1/Wikiplus/%E8%AE%BE%E7%BD%AE%E8%AF%B4%E6%98%8E"
			};
			localStorage.setItem("Wikiplus_Settings", JSON.stringify(wikiplusSetting));
		})();

		/* XTools */
		mw.loader.load('https://www.mediawiki.org/w/index.php?title=XTools/ArticleInfo.js&oldid=2625658&action=raw&ctype=text/javascript'); // 08:46, 5 August 2018 (UTC)

		/* FakeRollback */
		/*
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/FakeRollback.js&action=raw&ctype=text/javascript');
		}
		*/

		/* AutoUndo */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndo.js&action=raw&ctype=text/javascript');
		}

		/* AutoUndoGlobal */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:WhitePhosphorus/js/AutoUndoGlobal.js&action=raw&ctype=text/javascript');

		/* cvn-smart */
		// mw.loader.load('https://xiplus.ddns.net/wikipedia_rc/gadget.js');
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/cvn-smart-gadget.js&action=raw&ctype=text/javascript');

		/* history-merge */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) !== -1) {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/history-merge.js&action=raw&ctype=text/javascript');
		}

		/* list-user-last-active */
		switch (mw.config.get('wgDBname')) {
			case 'zhwiki':
				break;
			default:
				mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/list-user-last-active.js&action=raw&ctype=text/javascript');
				break;
		}

		/* smart rollback */
		if (typeof window.smartRollbackConfig === 'undefined') {
			window.smartRollbackConfig = {};
		}
		var smartRollbackConfig = window.smartRollbackConfig;
		smartRollbackConfig.toolLinkMethod = 'p-tb';
		smartRollbackConfig.editSummaries = ['批量回退無意義文字', '批量回退破壞'];
		mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/smart_rollback.js&action=raw&ctype=text/javascript');

		/* get-translatewiki-link */
		mw.loader.load('https://meta.wikimedia.org/w/index.php?title=User:Xiplus/js/get-translatewiki-link.js&action=raw&ctype=text/javascript');

		/* UTC clock */
		mw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript');

		/* CentralAuth */
		function showCentralAuth(username) {
			if (username === undefined) {
				return;
			}
			if (mw.util.isIPAddress(username, true)) {
				username = username.replace(/\/\d+$/, '');
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/meta/stalktoy/' + username,
					'全域封禁'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://whatismyipaddress.com/ip/' + username,
					'地理位置'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'http://whois.tanet.edu.tw/showWhoisPublic.php?queryString=' + username,
					'TANet'
				);
				mw.util.addPortletLink(
					'p-cactions',
					'https://tools.wmflabs.org/ipcheck/index.php?ip=' + username,
					'Proxy Checker'
				);
			} else {
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:CentralAuth') + '?target=' + encodeURIComponent(username),
					'全域帳號'
				);
			}
			mw.util.addPortletLink(
				'p-cactions',
				'https://xtools.wmflabs.org/globalcontribs/' + username,
				'全域貢獻 (xtools)'
			);
			mw.util.addPortletLink(
				'p-cactions',
				'https://tools.wmflabs.org/guc/?by=date&user=' + username,
				'全域貢獻 (guc)'
			);
		}
		if (mw.config.get('wgNamespaceNumber') === 2 || mw.config.get('wgNamespaceNumber') === 3) {
			showCentralAuth(mw.config.get('wgTitle').replace(/^([^/]+).*$/, '$1'));
		} else if (mw.config.get('wgRelevantUserName') !== null) {
			showCentralAuth(mw.config.get('wgRelevantUserName'));
		} else if (mw.config.get('wgCanonicalSpecialPageName') === 'Contributions') {
			showCentralAuth($('[name="target"]').val());
		}

		/* Admin list */
		switch (mw.config.get('wgDBname')) {
			// case 'zh_classicalwiki':
			// case 'zh_yuewiki':
			case 'zhwiki':
				// case 'zhwikibooks':
				// case 'zhwikinews':
				// case 'zhwikiquote':
				// case 'zhwikisource':
				// case 'zhwikivoyage':
				// case 'zhwiktionary':
				break;
			default:
				mw.util.addPortletLink(
					'p-cactions',
					mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', 'Special:Userlist') + '?group=sysop',
					'管理員列表'
				);
		}

		/* Twinkle */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'simplewiki':
			case 'test2wiki':
			case 'zh_classicalwiki':
			case 'zhwiki':
			case 'zhwikibooks':
			// case 'zhwikinews':
			case 'zhwikiquote':
			// case 'zhwikisource':
			case 'zhwikiversity':
			case 'zhwikivoyage':
			case 'zhwiktionary':
				break;
			default:
				console.log("Load Twinkle-global");
				mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Xiplus/Twinkle.js&action=raw&ctype=text/javascript');
				break;
		}

		/* Popup */
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'zhwiki':
				break;
			default:
				console.log("載入 A2569875Popup");
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopupsSetting_zh-hant.js&action=raw&ctype=text/javascript');
				mw.loader.load('//zh.wikipedia.org/w/index.php?title=User:A2569875-sandbox/MyPopups.css&action=raw&ctype=text/css', 'text/css');
				break;
		}

		/* tagger */
		if ($.inArray('sysop', mw.config.get('wgUserGroups')) === -1) {
			switch (mw.config.get('wgDBname')) {
				case 'enwiki':
					break;
				default:
					if (typeof (window.taggerConfig) == 'undefined') window.taggerConfig = {};
					var taggerConfig = window.taggerConfig;
					taggerConfig.noDeleteOnly = false;

					if (typeof (taggerConfig) == 'undefined') taggerConfig = {};
					taggerConfig.tags = [];
					taggerConfig.editSummary = [];
					taggerConfig.tags[1] = '{{delete|Vandalism}}';
					taggerConfig.editSummary[taggerConfig.tags[1]] = '+delete';
					taggerConfig.tags[2] = '{{delete|Nonsense}}';
					taggerConfig.editSummary[taggerConfig.tags[2]] = '+delete';
					taggerConfig.tags[3] = '{{delete|Vandalism. Created by LTA from zhwiki.}}';
					taggerConfig.editSummary[taggerConfig.tags[3]] = '+delete';
					taggerConfig.tags.other = 'This is used for the option you have to select to be able to insert a custom template';
					mw.loader.load('//meta.wikimedia.org/w/index.php?title=User:Hoo_man/tagger.js&action=raw&ctype=text/javascript');
					break;
			}
		}

		/* 側欄 */
		mw.util.addPortletLink(
			'p-tb',
			'/wiki/Special:PrefixIndex/' + mw.config.get('wgPageName'),
			'前綴索引',
			't-prefixindex',
			'',
			'',
			$('#t-specialpages')
		);

		if (mw.config.get("wgNamespaceNumber") == 8) {
			mw.util.addPortletLink(
				'p-cactions',
				'https://translatewiki.net/wiki/' + mw.config.get("wgPageName").split("/")[0] + '/zh-hant?action=edit',
				'translatewiki'
			);
		}

		mw.loader.using(['mediawiki.api']).done(function() {
			new mw.Api().get({
				action: "query",
				format: "json",
				list: "logevents",
				leprop: "comment|type",
				letype: "delete",
				letitle: mw.config.get('wgPageName')
			}).then(function(data) {
				for (var i = 0; i < data.query.logevents.length; i++) {
					var comment = data.query.logevents[i].comment;
					console.log(comment);
				}
			});
		});

		/* mediawiki.util */
	});

	/* CurIDLink */
	mw.loader.using(['mediawiki.api', 'mediawiki.ForeignApi', 'mediawiki.notify']).then(function() {
		if (mw.config.get('wgDBname') === 'metawiki') {
			var api = new mw.Api();
		} else {
			var api = new mw.ForeignApi('//meta.wikimedia.org/w/api.php');
		}
		api.loadMessagesIfMissing(['Link-by-id', 'Link-by-id-desc']).then(function() {
			mw.loader.load('https://meta.wikimedia.org/w/index.php?title=MediaWiki:Gadget-CurIDLink.js&action=raw&ctype=text/javascript');
		}, function() {
			mw.notify('Load CurIDLink messages failed', { type: 'error' })
		});
	}, function() {
		console.error('Load CurIDLink dependencies failed');
	});

	/* shortURL */
	mw.loader.using(['mediawiki.util', 'oojs-ui', 'mediawiki.ForeignApi', 'mediawiki.notify']).done(function() {
		mw.loader.getScript('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-site-lib.js&action=raw&ctype=text/javascript').then(function() {
			mw.loader.load('https://zh.wikipedia.org/w/index.php?title=MediaWiki:Gadget-shortURL.js&action=raw&ctype=text/javascript');
		});
	});

	/* Sandbox link */
	mw.loader.using(['mediawiki.util']).done(function() {
		var link, label;
		switch (mw.config.get('wgContentLanguage')) {
			case 'zh':
				link = '沙盒';
				label = '沙盒';
				break;

			default:
				link = 'sandbox';
				label = 'Sandbox';
				break;
		}
		switch (mw.config.get('wgDBname')) {
			case 'enwiki':
			case 'zhwiki':
			case 'zhwikiversity':
				break;
			default:
				mw.util.addPortletLink(
					'p-personal',
					'/wiki/User:Xiplus/' + link,
					label,
					'pt-sandbox',
					'',
					'',
					'#pt-preferences'
				);
				break;
		}
	});

	console.log("global.js end");

})();

// </nowiki>
<|endoftext|>


<commit_before>
/*
 * SmilePlease v1.0 - a lightweight library for taking screenshots of the current state of DOM
 * Author: Venkat Subramanian <venkat.crescentian@gmail.com>
 *
 * Copyright (c) 2016 Venkat Subramanian (https://github.com/Venkatb4U)
 * Licence: MIT
 */

 /*
  USAGE:
  -----
	smilePlease(dom, [optional callback]); (or) __(dom, [optional callback]);
 */

var smilePlease = function (target, callback) {

	(function (tg, cb) {
	 	"use strict";

	 	var DOMURL = window.URL || window.webkitURL || window;

		function sp () {
			(function init(sp) {
				sp.target = tg;

				// cloning the target to avoid polluting the original doc reference
				sp.targetClone = tg.cloneNode(true);

				sp.createCanvas();
				sp.render();
			})(this);
		};

		sp.prototype = {

			createCanvas: function () {
				var canvas = document.createElement('canvas');
				canvas.setAttribute('width', this.target.offsetWidth + 'px');
				canvas.setAttribute('height', this.target.offsetHeight + 'px');
				this.canvas = canvas;
				this.ctx = canvas.getContext('2d');
			},

			getStyles: function (elem, isRoot, prop) {
				var cs = window.getComputedStyle(elem,null);
			  	if (prop) {
				  return prop + ":" + cs.getPropertyValue(prop) + ";";
				}
				var len = cs.length || 0;
				var inlStyles = "";
				while (--len) {

				  var style = cs[len];

				  // skipping to add 'margins' to the canvas for Root elem
				  if (isRoot && (style.indexOf('margin') > -1 || style.indexOf('margin-') > -1)) {
				  	  continue;
				  }

				  inlStyles += (style + ":" + cs.getPropertyValue(style) + ";");
				}
				return inlStyles;
			},

			applyStyles: function (target) {

				var nodeList = target ? target.getElementsByTagName('*') : this.target.getElementsByTagName('*'),
					nodeListLen = nodeList.length || 0;
				var nodeCloneList = this.targetClone.getElementsByTagName('*');

				while (--nodeListLen) {
					nodeCloneList[nodeListLen].style = this.getStyles(nodeList[nodeListLen]);
				}

				(function rootNodeStyleFix (sp) { // target tag style apply
					sp.targetClone.style = sp.getStyles(sp.target, true);
				})(this);

				return nodeCloneList;
			},

			cookBlob: function (target) {
				var target = target || this.targetClone;

				this.applyStyles();

				var xmlSer = new XMLSerializer();
				var serialisedDom = xmlSer.serializeToString(target);

				var svgScaffold = '<svg xmlns="http://www.w3.org/2000/svg" id="sp_svg">' +
							           '<foreignObject width="100%" height="100%">' +
								           '
' +
								           		serialisedDom +
								           '
' +
							           '</foreignObject>' +
						          '</svg>';
			    // console.log(serialisedDom);
				// var xmlParser = new DOMParser();
				// var xmlDoc = xmlParser.parseFromString(svgScaffold, "text/xml");

				// xmlDoc.getElementById('sp_root').appendChild(domExtract);
				return svgScaffold;
			},

			render: function () {
				var self = this;
				var img = new Image();
				var cookedBlob = this.cookBlob();

				var svg = new Blob([cookedBlob], {type: 'image/svg+xml'});
				var url = DOMURL.createObjectURL(svg);

				img.src = url;
				img.setAttribute('width', this.canvas.width + 'px');
				img.setAttribute('height', this.canvas.height + 'px');

				img.onload = function () {
					var imgWidth = img.width;
					var imgHeight = img.height;

					self.canvas.width = imgWidth;
					self.canvas.height = imgHeight;

				  	// self.ctx.drawImage(img, 0, 0, 500, 300, 0, 0, 500, 300);
				  	self.ctx.drawImage(img, 0, 0);
				  	// document.body.appendChild(img);
				  	DOMURL.revokeObjectURL(url);
				}

				// document.body.appendChild(img);
				document.body.appendChild(this.canvas);

			}

		};

		return new sp();

	}(function(target) {
		return typeof target === 'string' ? document.querySelector(target) : target;
	}(target), callback));
}

__ = smilePlease; // short-hand alias.

// e.g.
__('#test');

<commit_msg>callback mechanism<commit_after>
/*
 * SmilePlease v1.0 - a lightweight library for taking screenshots of the current state of DOM
 * Author: Venkat Subramanian <venkat.crescentian@gmail.com>
 *
 * Copyright (c) 2016 Venkat Subramanian (https://github.com/Venkatb4U)
 * Licence: MIT
 */

 /*
  USAGE:
  -----
	smilePlease(dom, [optional callback]); (or) __(dom, [optional callback]);
 */

var smilePlease = function (target, callback) {

	(function (tg, cb) {
	 	"use strict";

	 	var DOMURL = window.URL || window.webkitURL || window;

		function sp () {
			(function init(sp) {
				sp.target = tg;
				sp.cb = cb;

				// cloning the target to avoid polluting the original doc reference
				sp.targetClone = tg.cloneNode(true);

				sp.createCanvas();
				sp.render();
			})(this);
		};

		sp.prototype = {

			createCanvas: function () {
				var canvas = document.createElement('canvas');
				canvas.setAttribute('width', this.target.offsetWidth + 'px');
				canvas.setAttribute('height', this.target.offsetHeight + 'px');
				this.canvas = canvas;
				this.ctx = canvas.getContext('2d');
			},

			getStyles: function (elem, isRoot, prop) {
				var cs = window.getComputedStyle(elem,null);
			  	if (prop) {
				  return prop + ":" + cs.getPropertyValue(prop) + ";";
				}
				var len = cs.length || 0;
				var inlStyles = "";
				while (--len) {

				  var style = cs[len];

				  // skipping to add 'margins' to the canvas for Root elem
				  if (isRoot && (style.indexOf('margin') > -1 || style.indexOf('margin-') > -1))
				  	  continue;

				  inlStyles += (style + ":" + cs.getPropertyValue(style) + ";");
				}
				return inlStyles;
			},

			applyStyles: function (target) {

				var nodeList = target ? target.getElementsByTagName('*') : this.target.getElementsByTagName('*'),
					nodeListLen = nodeList.length || 0;
				var nodeCloneList = this.targetClone.getElementsByTagName('*');

				while (--nodeListLen)
					nodeCloneList[nodeListLen].style = this.getStyles(nodeList[nodeListLen]);

				(function rootNodeStyleFix (sp) { // target tag style apply
					sp.targetClone.style = sp.getStyles(sp.target, true);
				})(this);

				return nodeCloneList;
			},

			cookBlob: function (target) {
				var target = target || this.targetClone;

				this.applyStyles();

				var xmlSer = new XMLSerializer();
				var serialisedDom = xmlSer.serializeToString(target);

				var svgScaffold = '<svg xmlns="http://www.w3.org/2000/svg" id="sp_svg">' +
							           '<foreignObject width="100%" height="100%">' +
								           '
' +
								           		serialisedDom +
								           '
' +
							           '</foreignObject>' +
						          '</svg>';
			    // console.log(serialisedDom);
				// var xmlParser = new DOMParser();
				// var xmlDoc = xmlParser.parseFromString(svgScaffold, "text/xml");

				// xmlDoc.getElementById('sp_root').appendChild(domExtract);
				return svgScaffold;
			},

			render: function () {
				var self = this;
				var img = new Image();
				var cookedBlob = this.cookBlob();

				var svg = new Blob([cookedBlob], {type: 'image/svg+xml'});
				var url = DOMURL.createObjectURL(svg);

				img.src = url;
				img.setAttribute('width', this.canvas.width + 'px');
				img.setAttribute('height', this.canvas.height + 'px');

				img.onload = function () {
					var imgWidth = img.width;
					var imgHeight = img.height;

					self.canvas.width = imgWidth;
					self.canvas.height = imgHeight;

				  	// self.ctx.drawImage(img, 0, 0, 500, 300, 0, 0, 500, 300);
				  	self.ctx.drawImage(img, 0, 0);
				  	// document.body.appendChild(img);
				  	DOMURL.revokeObjectURL(url);

				  	// callback trigger
				  	self.cb && self.cb(self.canvas);
				}

				// document.body.appendChild(img);
				document.body.appendChild(this.canvas);

			}

		};

		return new sp();

	}(function(target) {
		return typeof target === 'string' ? document.querySelector(target) : target;
	}(target), callback));
}

__ = smilePlease; // short-hand alias.

// e.g.
__('#test', function(canvas) {
	document.body.appendChild(canvas);
});

<|endoftext|>


<commit_before>/**
 * Created by rinesnow on 16/3/29.
 */
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var crypto = require('crypto');
var session= require('express-session');
var moment = require('moment');
var authentication = require('./authentication.js');

var app = express();

//连接数据库
var mongoose = require('mongoose');
var models = require('./models/models');

var User = models.User;
var Intern = models.Intern;

mongoose.connect('mongodb://localhost:27017/interns');
mongoose.connection.on('error',console.error.bind(console,'连接数据库失败!'));

//定义EJS模版引擎和末班文件位置
app.set('views', path.join(__dirname,'views'));
app.set('view engine','ejs');

//定义静态文件目录
app.use(express.static(path.join(__dirname,'public')));

//定义数据解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//建立session模型
app.use(session({
    secret:'liuchong',//?
    name:'intern',
    //一周内免登录
    cookie:{maxAge:1000 * 60 * 60*24*7},//设置session的保存时间为 60min*24小时*7一周
    resave: false,
    saveUnintiallized:true
}));

//添加  页面提示功能
app.use(function(req, res, next) {
    res.locals.user = req.session.user;//???
    var err = req.session.error;//赋值给err变量,
    //var success = req.session.success;//赋值给err变量,

    delete req.session.error;//然后清空session内的数据
    res.locals.message = '';//初始化
    //res.locals.success = '';//初始化

    if (err) {
        //html通过js被操作,在html中用{%-message%}调用
        res.locals.message = '
' + err + '
';
    }
    //if (success) {
    //    //html通过js被操作,在html中用{%-message%}调用
    //    res.locals.success = '
' + success + '
';
    //}

    next();//?
});

   var OAuth = require('wechat-oauth');
   var client = new OAuth('wx75d11b4f981b1ded', '7a915c525f39451f3af19407012459ad');
 // var openid='hehehe';
app.use(function ifAuthorized(req,res,next){

    // var url = client.getAuthorizeURL('www.coderwitkey.com', 'STATE', 'snsapi_userinfo');
    var query = require('url').parse(req.url,true).query;
          console.log(query);

    var code = query.code;
          console.log(code);

    client.getUserByCode(code,function (err, result) {
      // var accessToken = result.data.access_token;
      // var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

      console.log('这是result:'+result.openid);
      // console.log(accessToken);

      // console.log("这是openid2"+openid);

       User.findOne({openid:result.openid},function(err,user){
           if(err){
               console.log('这是err'+err);
           }
            if(user){//有这个user 那么直接跳转
                return res.redirect('/');
            }
            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newUser = new User({

                openid:result.openid,//openid 作为key存入，以后再用用户信息就用openid调。
                nickname:result.nickname,
                headimg:result.headimgurl
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存用户信息失败！"+err);
                }
                console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });
    });
    // req.code=code;
    next();
});

//响应首页get请求
// app.get('/',authentication.ifAuthorized);//检测是否登录了
app.get('/',function(req,res){

      console.log('首页!');
    res.render('login',{
        user: req.session.user,//也要加?
        title:'内推推推'
    });
    // Note.find({author:openid}).exec(function(err,allNotes){
    //     if(err){
    //         console.log(err);
    //         return res.redirect('/');
    //     }
    //     res.render('index',{
    //        title:'首页',
    //         openid: openid,
    //         notes:allNotes
    //     });
    // })
});

//登出
app.get('/quit',function(req,res){
    //退出功能只需将session中的user删除即可。
    // req.session.user = null;
    console.log('退出!');
    return res.redirect('/login');
});

//发布

//响应发布get请求
// app.get('/post',authentication.ifAuthorized);//检测是否登录了
app.get('/post',function(req,res){
   console.log('res.code:'+res.code);

    client.getUserByCode(res.code,function (err, result) {
      // var accessToken = result.data.access_token;
      // var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

      // console.log(result);
      // console.log(accessToken);

      // console.log("这是openid2"+openid);
      console.log('这是result:'+result.openid);

      // intern.openid=result.openid;
      // intern.company='腾讯';
      // intern.email='www.liuchong.com';
      // intern.category='Tech';
      // intern.content='I want you!';

       Intern.findOne({createTime:Date.now},function(err,intern){
           if(err){
               console.log(err);
           }

            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newIntern = new Intern({

                openid:result.openid,//用户的id
                company:'腾讯',
                email:'www.liuchong.com',
                category:'Tech',
                content:'I want you!',
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存实习信息失败！"+err);
                }
                console.log('保存实习信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });
    });
   console.log('发布!');
    res.render('post',{
        user: req.session.user,//也要加?
        title:'发布'
    });
});
//响应发布post请求
app.post('/post',function(req,res){

     User.findOne({openid:openid},function(err,user){
           if(err){
               console.log(err);
           }
            if(user){//有这个user 那么直接跳转
                return res.redirect('/');
            }
        });
   var note = new Note({
       title:req.body.title,
       author:openid,
       tag: req.body.tag,
       content: req.body.content
   });
    note.save(function(err,doc){
       if(err){
           console.log(err);
           return res.redirect('/post');
       }
        console.log('文章发表成功!')
        return res.redirect('/');
    });
});
//

//博客细节

// app.get('/detail/',authentication.ifAuthorized);//检测是否登录了
app.get('/detail/:_id',function(req,res){//:id?
   console.log('查看笔记!');
    Note.findOne({_id:req.params._id}).exec(function(err,art){
        if(err){
            console.log(err);
            return res.redirect('/');
        }
        if(art) {
            res.render('detail', {
                title: '笔记详情',
                user: req.session.user,
                art: art,
                moment:moment
            });
            console.log(art);
        }
    });
});

// app.get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx75d11b4f981b1ded&secret=7a915c525f39451f3af19407012459ad&code=CODE&grant_type=authorization_code',function(req,res){

// });//获取appid

app.listen(3000, function(req,res){
    console.log('app is running at port 3000');
});<commit_msg>yonghu id<commit_after>/**
 * Created by rinesnow on 16/3/29.
 */
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var crypto = require('crypto');
var session= require('express-session');
var moment = require('moment');
var authentication = require('./authentication.js');

var app = express();

//连接数据库
var mongoose = require('mongoose');
var models = require('./models/models');

var User = models.User;
var Intern = models.Intern;

mongoose.connect('mongodb://localhost:27017/interns');
mongoose.connection.on('error',console.error.bind(console,'连接数据库失败!'));

//定义EJS模版引擎和末班文件位置
app.set('views', path.join(__dirname,'views'));
app.set('view engine','ejs');

//定义静态文件目录
app.use(express.static(path.join(__dirname,'public')));

//定义数据解析器
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

//建立session模型
app.use(session({
    secret:'liuchong',//?
    name:'intern',
    //一周内免登录
    cookie:{maxAge:1000 * 60 * 60*24*7},//设置session的保存时间为 60min*24小时*7一周
    resave: false,
    saveUnintiallized:true
}));

//添加  页面提示功能
app.use(function(req, res, next) {
    res.locals.user = req.session.user;//???
    var err = req.session.error;//赋值给err变量,
    //var success = req.session.success;//赋值给err变量,

    delete req.session.error;//然后清空session内的数据
    res.locals.message = '';//初始化
    //res.locals.success = '';//初始化

    if (err) {
        //html通过js被操作,在html中用{%-message%}调用
        res.locals.message = '
' + err + '
';
    }
    //if (success) {
    //    //html通过js被操作,在html中用{%-message%}调用
    //    res.locals.success = '
' + success + '
';
    //}

    next();//?
});

   var OAuth = require('wechat-oauth');
   var client = new OAuth('wx75d11b4f981b1ded', '7a915c525f39451f3af19407012459ad');
 // var openid='hehehe';
app.use(function ifAuthorized(req,res,next){

    // var url = client.getAuthorizeURL('www.coderwitkey.com', 'STATE', 'snsapi_userinfo');
    var query = require('url').parse(req.url,true).query;
          console.log(query);

    var code = query.code;
          console.log(code);

    client.getUserByCode(code,function (err, result) {
      // var accessToken = result.data.access_token;
      // var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

      console.log('这是result:'+result.openid);
      // console.log(accessToken);

      // console.log("这是openid2"+openid);

       User.findOne({openid:result.openid},function(err,user){
           if(err){
               console.log('这是err'+err);
           }
            // if(user){//有这个user 那么直接跳转
            //     return res.redirect('/');
            // }
            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newUser = new User({

                openid:result.openid,//openid 作为key存入，以后再用用户信息就用openid调。
                nickname:result.nickname,
                headimg:result.headimgurl
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存用户信息失败！"+err);
                }
                console.log('保存用户信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });
    });
    // req.code=code;
    next();
});

//响应首页get请求
// app.get('/',authentication.ifAuthorized);//检测是否登录了
app.get('/',function(req,res){

      console.log('首页!');
    res.render('login',{
        user: req.session.user,//也要加?
        title:'内推推推'
    });
    // Note.find({author:openid}).exec(function(err,allNotes){
    //     if(err){
    //         console.log(err);
    //         return res.redirect('/');
    //     }
    //     res.render('index',{
    //        title:'首页',
    //         openid: openid,
    //         notes:allNotes
    //     });
    // })
});

//登出
app.get('/quit',function(req,res){
    //退出功能只需将session中的user删除即可。
    // req.session.user = null;
    console.log('退出!');
    return res.redirect('/login');
});

//发布

//响应发布get请求
// app.get('/post',authentication.ifAuthorized);//检测是否登录了
app.get('/post',function(req,res){
   console.log('res.code:'+res.code);

    client.getUserByCode(res.code,function (err, result) {
      // var accessToken = result.data.access_token;
      // var openid = result.openid;//必须要手动点击URL，原地刷新没用的。

      // console.log(result);
      // console.log(accessToken);

      // console.log("这是openid2"+openid);
      console.log('这是result:'+result.openid);

      // intern.openid=result.openid;
      // intern.company='腾讯';
      // intern.email='www.liuchong.com';
      // intern.category='Tech';
      // intern.content='I want you!';

       Intern.findOne({createTime:Date.now},function(err,intern){
           if(err){
               console.log(err);
           }

            // //对密码进行md5加密
            // var md5 = crypto.createHash('md5'),
            //     md5newopenid = md5.update(openid).digest('hex');
            //新建user对象用于保存数据
            var newIntern = new Intern({

                openid:result.openid,//用户的id
                company:'腾讯',
                email:'www.liuchong.com',
                category:'Tech',
                content:'I want you!',
            });

            newUser.save(function(err,doc){
                if(err){
                    console.log("保存实习信息失败！"+err);
                }
                console.log('保存实习信息成功!');//怎么实现弹出框!!!!??????
                return res.redirect('/');
            });
        });
    });
   console.log('发布!');
    res.render('post',{
        user: req.session.user,//也要加?
        title:'发布'
    });
});
//响应发布post请求
app.post('/post',function(req,res){

     User.findOne({openid:openid},function(err,user){
           if(err){
               console.log(err);
           }
            if(user){//有这个user 那么直接跳转
                return res.redirect('/');
            }
        });
   var note = new Note({
       title:req.body.title,
       author:openid,
       tag: req.body.tag,
       content: req.body.content
   });
    note.save(function(err,doc){
       if(err){
           console.log(err);
           return res.redirect('/post');
       }
        console.log('文章发表成功!')
        return res.redirect('/');
    });
});
//

//博客细节

// app.get('/detail/',authentication.ifAuthorized);//检测是否登录了
app.get('/detail/:_id',function(req,res){//:id?
   console.log('查看笔记!');
    Note.findOne({_id:req.params._id}).exec(function(err,art){
        if(err){
            console.log(err);
            return res.redirect('/');
        }
        if(art) {
            res.render('detail', {
                title: '笔记详情',
                user: req.session.user,
                art: art,
                moment:moment
            });
            console.log(art);
        }
    });
});

// app.get('https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx75d11b4f981b1ded&secret=7a915c525f39451f3af19407012459ad&code=CODE&grant_type=authorization_code',function(req,res){

// });//获取appid

app.listen(3000, function(req,res){
    console.log('app is running at port 3000');
});<|endoftext|>