2020年5月28日 星期四

project 對 dom.tree 先廣域搜索指定的節點,再排序

const getCommentLis = {
            main(root) {
                let commentList = [];

                let dataList = [{
                    level: [1],
                    node: root
                }];

                // 位數
                let digit = dataList[0].level.length;

                let i = 0;
                let data;
                while (null != (data = dataList[i++])) {
                    // debugger;

                    const level = data.level;
                    const node = data.node;

                    if (node.tagName != null) {
                        node.childNodes.forEach((child, i) => {
                            let _level = level.slice()
                            _level.push(i + 1);

                            if (_level.length > digit) {
                                digit = _level.length;
                            }

                            dataList.push({
                                level: _level,
                                node: child
                            });
                        });
                    } else {
                        if (node.nodeType == 8) {
                            let parent = node.parentNode;
                            commentList.push({
                                parent: parent,
                                node: node,
                                level
                            });
                        }
                    }
                } // endWhile
                // debugger;
                console.dir(commentList);

                commentList.sort((a, b) => {
                    if (Array.isArray(a.level)) {
                        a.level = this.getLevel(digit, a.level);
                    }

                    if (Array.isArray(b.level)) {
                        b.level = this.getLevel(digit, b.level);
                    }

                    return (a.level - b.level);
                });

                console.dir(commentList);
                return commentList;
            },
            getLevel(digit, level) {
                debugger;
                let j = digit - level.length;

                // debugger;
                // 基數
                let p = 1;
                for (let i = 0; i < j; i++) {
                    p *= 10;
                }

                // debugger;
                let res = 0;
                let num;
                while (null != (num = level.pop())) {
                    res = res + num * p;
                    // 十進位
                    p *= 10;
                }

                return res;
            }
        }

2019年9月25日 星期三

php get_headers 判斷URL是否有效


在php中判斷一個文件或目錄是否存在,大家通常都會想到is_file和file_exists兩個函數。但這兩個函數再判斷一個遠程url文件是否存在的問題上還是會存在這樣那樣的問題。這裡作者將和大家分享一種利用php get_headers函數來判斷遠程url文件是有效否存在的辦法。

關於php get_headers函數的作用及用法,可以參考本站文章:

php get_headers函數的作用及用法

下面來具體說如何利用php get_headers卻判斷url的真實有效性。

通過該函數的介紹,我們可以知道對於這個函數簡單的說就是它返回的是一個HTTP請求的頭文件信息,信息格式基本如下:

(1)

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

(2)

Array
(
    [0] => HTTP/1.0 404 Not Found
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

從以上兩種情況可以很容易看出,如果判斷該url是否有效存在肯定是通過數組中的第一個元素值來判斷的。服務器返回 200 即文件正確返回的意思,服務器返回 404 即文件不存在,因此從這個地方就可以很容易的判斷一個url的是否存在了

2019年3月14日 星期四

堆疊樹

// 堆疊樹(由下往上)

// (1~n) m 的子節點為 2m, 2m+1
// 階層從 1階 開始
// 每階最多 (2(level-1)次方) 個節點
let data = [26, 5, 19, 1, 61, 11, 59, 15, 48, 77];

// 最後一個有子節點的節點
let lastParentIndex = Math.floor(data.length / 2) - 1;

console.log(JSON.stringify(data));
// 往前拜訪每個有孩子的節點
for (let i = lastParentIndex; i >= 0; i--) {
    debugger;
    check(i, data);
}
console.log(JSON.stringify(data));

//----------------------------
// 檢查父節點與子節點的大小
function check(parent_index, _data) {
    debugger;

    // 會不斷往下有子節點的節點探索
    while (parent_index <= lastParentIndex) {

        let leftIndex = (parent_index + 1) * 2 - 1;
        let rightIndex = leftIndex + 1;

        // 可能沒有 right 子節點
        rightIndex = (rightIndex >= _data.length) ? null : rightIndex;

        // console.log('%d = %d',  _data[leftIndex], _data[rightIndex]);

        let maxIndex = (rightIndex == null || (_data[leftIndex] > _data[rightIndex])) ? leftIndex : rightIndex;

        if (_data[parent_index] < _data[maxIndex]) {
            // 交換
            let temp = _data[maxIndex];
            _data[maxIndex] = _data[parent_index];
            _data[parent_index] = temp;
        }

        // 往下層比較
        // 確定變動的節點要比他的子節點大
        parent_index = maxIndex;
    }
}
------------------------------------------------------------------------
// 堆疊樹(由上往下)

// (1~n) m 的子節點為 2m, 2m+1
// 階層從 1階 開始
// 每階最多 (2(level-1)次方) 個節點
let data = [26, 5, 19, 1, 61, 11, 59, 15, 48, 77];

console.log(JSON.stringify(data));
// 往前拜訪每個有孩子的節點
for (let i = 0; i < data.length; i++) {
    debugger;
    check(i, data);
}
console.log(JSON.stringify(data));

//----------------------------
// 檢查父節點與子節點的大小
function check(parent_index, _data) {
    debugger;

    let prev_index;

    // 會不斷往下有子節點的節點探索
    while (parent_index >= 0) {


        if (prev_index != null) {
            // 回朔 只需比對上一個子節點
            if (_data[parent_index] < _data[prev_index]) {
                // 交換
                let temp = _data[prev_index];
                _data[prev_index] = _data[parent_index];
                _data[parent_index] = temp;
            }

        } else {
            // 第一次進入

            let leftIndex = (parent_index + 1) * 2 - 1;
            let rightIndex = leftIndex + 1;

            leftIndex = (leftIndex >= _data.length) ? null : leftIndex;
            rightIndex = (rightIndex >= _data.length) ? null : rightIndex;


            if (leftIndex == null && rightIndex == null) {
                // 都沒有子節點
                return;
            }

            console.log('%d(%d,%d)', _data[parent_index], _data[leftIndex], _data[rightIndex]);

            let maxIndex = (rightIndex == null || (_data[leftIndex] > _data[rightIndex])) ? leftIndex : rightIndex;

            if (_data[parent_index] < _data[maxIndex]) {
                // 交換
                let temp = _data[maxIndex];
                _data[maxIndex] = _data[parent_index];
                _data[parent_index] = temp;
            }
        }
        //-----------------------
        prev_index = parent_index;
        // 往下層比較
        // 確定變動的節點要比他的子節點大
        let nextCheckIndex = Math.floor((parent_index + 1) / 2) - 1;

        if (nextCheckIndex == parent_index && parent_index == 0) {
            // 只為了解決無限迴圈
            return;
        }

        // 往上
        parent_index = nextCheckIndex;
    }
}

2019年3月13日 星期三

DoublyLinkedList

module.exports = DoublyLinkedList;


// 雙向連結
function DoublyLinkedList() {

    let head;
    let tail;
    let length;

    this._head = function (node) {
        if (node == null) {
            return head;
        } else {
            head = node;
        }
    };

    this._tail = function (node) {
        if (node == null) {
            return tail;
        } else {
            tail = node;
        }
    };

    this._length = function (_length) {
        if (_length == null) {
            return length;
        } else {
            length = _length;
        }
    };

}

(function () {
    this.append = function (el) {
        debugger;

        let node = new Node(el);

        if (this._head() == null) {
            this._head(node);

            this._length(1);
            this._tail(node);

        } else {
            let prev_node = this._head();
            let count = 0;

            while (prev_node.next != null) {
                prev_node = prev_node.next;
                count++;
            }

            prev_node.next = node;
            node.prev = prev_node;

            this._length(++count);
            this._tail(prev_node);
        }

    };

    this.insert = function (position, el) {

    };

    this.remove = function (el) {

    };

    this.removeAt = function (position) {

    };

    this.indexOf = function (position) {

    };

    this.size = function () {
        return this._length();
    };

    this.toJSON = function () {
        debugger;
        let res = [];
        let node = this._head();

        do {
            if (node == null) {
                break;
            } else {
                res.push(JSON.stringify(node.element));
            }
        } while ((node = node.next) != null);

        return res.join(',');
    };

}).call(DoublyLinkedList.prototype);


//==============================================================================

function Node(el) {
    this.element = el;
    this.prev = null;
    this.next = null;
}

2019年3月7日 星期四

worker 環境判定

if(typeof Window !== 'undefined'){
    // browser
}else if(typeof WorkerGlobalScope !== 'undefined'){
    // browser worker
   
}else if(typeof module !== 'undefined'){
    // node.js
    const {isMainThread} = require('worker_threads');
       
    if(isMainThread){
        // MainThread
    }else{
        // worker
    }
}

2019年3月5日 星期二

所有的html標籤

所有的html標籤

不同系統的換行符號

str.replace(/(\r\n|\n)/, '')


|一、概念:

換行符‘\n’和回車符‘\r’

(1)換行符就是另起一行  — ‘\n‘ 10 換行(newline)

(2)回車符就是回到一行的開頭 — ‘\r‘ 13 回車(return)

所以我們平時編寫檔案的回車符應該確切來說叫做回車換行符 

CR: 回車(Carriage Return) \r
LF: 換行(Line Feed) \n

二、應用:
(1)在微軟的MS-DOS和Windows中,使用“回車CR(‘\r’)”和“換行LF(‘\n’)”兩個字元作為換行符;
(2)Windows系統裡面,每行結尾是 回車 換行(CR LF),即“\r\n”;
(3)Unix系統裡,每行結尾只有 換行LF,即“\n”;
(4)Mac系統裡,每行結尾是 回車CR 即’\r’。
Mac OS 9 以及之前的系統的換行符是 CR,從 Mac OS X (後來改名為“OS X”)開始的換行符是 LF即‘\n’,和Unix/Linux統一了。
三、影響:
(1)一個直接後果是,Unix/Mac系統下的檔案在Windows裡開啟的話,所有文字會變成一行;
(2)而Windows裡的檔案在Unix/Mac下開啟的話,在每行的結尾可能會多出一個^M符號。
(3)Linux儲存的檔案在windows上用記事本看的話會出現黑點。
四、可以相互轉換:
在linux下,命令unix2dos 是把linux檔案格式轉換成windows檔案格式,命令dos2unix 是把windows格式轉換成linux檔案格式。
在不同平臺間使用FTP軟體傳送檔案時, 在ascii文字模式傳輸模式下, 一些FTP客戶端程式會自動對換行格式進行轉換. 經過這種傳輸的檔案位元組數可能會發生變化.
 如果你不想ftp修改原檔案, 可以使用bin模式(二進位制模式)傳輸文字。
一個程式在windows上執行就生成CR/LF換行格式的文字檔案,而在Linux上執行就生成LF格式換行的文字檔案。

2019年2月26日 星期二

拖曳一個小方塊.......不錯用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./js_lib/jquery-3.3.1.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        body {
            position: relative;
        }

        div.container_1 {
            height: 1000px;
            background-color: #ffc;
            position: relative;
        }

        #moveEvent {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            border: 1px dashed;
            z-index: 99999;
            display: none;
            user-select: none;
            opacity: 0;
        }

        #box_1 {
            width: 100px;
            height: 100px;
            position: absolute;
            top: 50px;
            left: 100px;
            z-index: 100;
            background-color: #00F;
            user-select: none;
        }
    </style>
</head>

<body>
    <div id="moveEvent">
        <!-- 全螢幕的畫布 -->
    </div>
    <div class="container_1">
        <p id="box_1">
            box
        </p>
    </div>
    <script>

        // screen 與 #box_1 的座標差
        let topOffset;
        let leftOffset;
        let callback;


        $('#box_1').on('mousedown', function (e) {
            console.dir(e);


            let { left, top } = $(this).position();

            topOffset = top - e.screenY;
            leftOffset = left - e.screenX;
            //-----------------------
            callback = (function (leftOffset, topOffset, x, y) {
                let left = x + leftOffset;
                let top = y + topOffset;

                $('#box_1').css({
                    top: top,
                    left: left
                });
            }).bind(this, leftOffset, topOffset);
            //-----------------------
            $('#moveEvent').css('display', 'block');
        });

        $('#moveEvent').on('mousemove', function (e) {
            console.log('offset:(%s, %s)', e.offsetX, e.offsetY);
            console.log('screen(%s, %s)', e.screenX, e.screenY);

            if(callback){
                callback(e.screenX, e.screenY);
            }
        });

        $('#moveEvent').on('mouseup', function () {
            callback = undefined;
            $('#moveEvent').css('display', '');
        });
    </script>
</body>

</html>

2019年2月25日 星期一

yahoo serialize

/*
Copyright (c) 2014, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/

'use strict';

// Generate an internal UID to make the regexp pattern harder to guess.
var UID                 = Math.floor(Math.random() * 0x10000000000).toString(16);
var PLACE_HOLDER_REGEXP = new RegExp('"@__(F|R|D)-' + UID + '-(\\d+)__@"', 'g');

var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
var UNSAFE_CHARS_REGEXP   = /[<>\/\u2028\u2029]/g;

// Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
// Unicode char counterparts which are safe to use in JavaScript strings.
var ESCAPED_CHARS = {
    '<'     : '\\u003C',
    '>'     : '\\u003E',
    '/'     : '\\u002F',
    '\u2028': '\\u2028',
    '\u2029': '\\u2029'
};

function escapeUnsafeChars(unsafeChar) {
    return ESCAPED_CHARS[unsafeChar];
}

module.exports = function serialize(obj, options) {
    options || (options = {});

    // Backwards-compatability for `space` as the second argument.
    if (typeof options === 'number' || typeof options === 'string') {
        options = {space: options};
    }

    var functions = [];
    var regexps   = [];
    var dates     = [];

    // Returns placeholders for functions and regexps (identified by index)
    // which are later replaced by their string representation.
    function replacer(key, value) {
        if (!value) {
            return value;
        }

        // If the value is an object w/ a toJSON method, toJSON is called before
        // the replacer runs, so we use this[key] to get the non-toJSONed value.
        var origValue = this[key];
        var type = typeof origValue;

        if (type === 'object') {
            if(origValue instanceof RegExp) {
                return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
            }

            if(origValue instanceof Date) {
                return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
            }
        }

        if (type === 'function') {
            return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
        }

        return value;
    }

    var str;

    // Creates a JSON string representation of the value.
    // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
    if (options.isJSON && !options.space) {
        str = JSON.stringify(obj);
    } else {
        str = JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
    }

    // Protects against `JSON.stringify()` returning `undefined`, by serializing
    // to the literal string: "undefined".
    if (typeof str !== 'string') {
        return String(str);
    }

    // Replace unsafe HTML and invalid JavaScript line terminator chars with
    // their safe Unicode char counterpart. This _must_ happen before the
    // regexps and functions are serialized and added back to the string.
    str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);

    if (functions.length === 0 && regexps.length === 0 && dates.length === 0) {
        return str;
    }

    // Replaces all occurrences of function, regexp and date placeholders in the
    // JSON string with their string representations. If the original value can
    // not be found, then `undefined` is used.
    return str.replace(PLACE_HOLDER_REGEXP, function (match, type, valueIndex) {
        if (type === 'D') {
            return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
        }

        if (type === 'R') {
            return regexps[valueIndex].toString();
        }

        var fn           = functions[valueIndex];
        var serializedFn = fn.toString();

        if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) {
            throw new TypeError('Serializing native function: ' + fn.name);
        }

        return serializedFn;
    });
}

2019年2月13日 星期三

java swing 刊誤

p525>> 
import java.awt.event.*;
import java.awt.Window;

public class BasicWindowMonitor extends WindowAdapter {

  public void windowClosing(WindowEvent e) {
    Window w = e.getWindow();
    w.setVisible(false);
    w.dispose();
    System.exit(0);
  }
}

2019年2月9日 星期六

node.js 路徑

// 專案目錄位置
const root = fs.realpathSync('./');

require(`${root}/node_modules/..........`);

 

process.cwd()