国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

開發拾遺

qc1iu / 1707人閱讀

摘要:字符串轉成中文二進制直接量和隱式轉換兩個字符串恰好以的科學記數法開頭,字符串被隱式轉換為浮點數,也就等效于轉為進制,無此的松比較如果值為,那么它會滿足任何一條使用對象的瀏覽器兼容性問題同時支持和分割日期的時間字符串不支持分割日期的時間

python unicode字符串轉成中文
s = "u6d4bu8bd5u957fu5ea6" 
s = s.replace("u", "u") 
print s.decode("unicode-escape")
php 二進制直接量
$bin = bindec("110011");  
$bin = 0b110011;
php foreach list
$arr = [
    [1, 2],
    [3, 4],
];
foreach ($arr as list($a, $b)) {
    echo $a.$b
";
}
PHP ==和隱式轉換
var_dump(md5("240610708") == md5("QNKCDZO"));// true  兩個字符串恰好以0e 的科學記數法開頭,字符串被隱式轉換為浮點數,也就等效于0×10^0
var_dump(sha1("aaroZmOk") == sha1("aaK1STfY"));// true
var_dump("0x1234Ab" == "1193131");// true 0x1234Ab轉為16進制,php7無此bug
var_dump( 0 == "a" );// true
var_dump( "0" == "a" );// true
== 、switch、in_array 的松比較
// 如果 $name 值為 0,那么它會滿足任何一條 case
switch ($name) {// 使用switch (strval($name)) {
    case "danny":
        break;
    case "eve":
        break;
}
$needle = "1abc"; 
$haystack = array(1,2,3); 
var_dump(in_array($needle, $haystack);// true
javascript Date對象的瀏覽器兼容性問題

// chrome同時支持"-"和"/"分割日期的時間字符串;safari不支持"-"分割日期的時間字符串

var arr = "2010-03-15 10:30:00".split(/[- / :]/),
    date = new Date(arr[0], arr[1]-1, arr[2], arr[3], arr[4], arr[5]);
javascript 模擬Object.keys()
function keys(obj){
  var a = [];
  for(a[a.length] in obj);
  return a;
}
javascript數組去重
function dedupe(array){
    return Array.from(new Set(array));
}

dedupe([1,1,2,3]) //[1,2,3]
工具

// 命令行提示tldr npm install -g tldr


octotree 是一款可為 GitHub 和 GitLab 添加側邊欄文件導航的 Chrome 和 Opera 插件
python下載視頻工具

Sublime Text3 漢化

// Package Control:Install Package,輸入Chinese,選擇ChineseLocalization

javascript reduce
arr = [1,2,3,4,5] 
arr.reduce(function(a,b){ 
return a*10+b; 
});//12345
var result = [1, 2, 3, 4, 5].reduce(function(prev, curr, index, array){
debugger;
    prev.push(curr * 2);
    return prev;
}, []);
console.log(result);//[2, 4, 6, 8, 10]
//求最大值
var max = arr.reduce(function(pre,cur,inde,arr){return pre>cur?pre:cur;});
var arr = [ {name: "brick1"}, {name: "brick2"}, {name: "brick3"} ]
function carryBricks(arr){
  return arr.reduce(function(prev, current, index, array){
    if (index === 0){
      return current.name;
    }
    else if (index === array.length - 1){
      return prev + " & " + current.name;
    }
    else {
      return prev + ", " + current.name;
    }
  }, "");
 }//brick11, brick12 & brick13
//去重
var arr = [1, 3, 1, "x", "zz", "x", false, false];
var result = arr.reduce(function(prev, curr, i, array) {
    var flag = prev.every(function(value) {
        return value !== curr;
    });
    flag && prev.push(curr);
    return prev;
}, []);
console.log(result);
jquery插件

輸入提示自動完成插件tokeninput
tablesorter 表格排序
Date.js執行日期/時間的計算
圖片裁剪
日期選擇插件pickadate.js
javascript刻度條插件

0.1+0.2
Math.round( (.1+.2)*100)/100; //0.3
mysql分解聯合查詢
select * from teacher 
join school on teacher.id = school.id
join course on teacher.id = course.id
where course.name= "english"  

分解后 
select * from course where name = "english"
select * from  school where course_id = 1
select * from teacher where school_id in (1,2,3) 
字符串中每個字母重復出現的次數
 var temp = {};
   "abcdaabc".replace(/(w{1})/g,function($1){
        temp[$1] ? temp[$1]+=1 : temp[$1] = 1;
    })
    console.log(temp) // {a: 3, b: 2, c: 2, d: 1}
composer

PHP HTTP請求套件
實現 Laravel 模型的無限極分類

php一維數組 轉 多維數組
$arr = ["a", "b", "c", "d"];
$child = array();
$res = [];
while($v = array_pop($arr)) {
    $res = [$v => $child];
    $child = $res;
}
python中字符串的按位或
a = "1000111000"
b = "1000000001"

c = int(a, 2) | int(b, 2)

print("{0:b}".format(c))#1000111001
python生成斐波拉契數列
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return "done"
php正則匹配
$str="{a:1,b:2,c:3}"; 
preg_match_all("/(w+):(d+)/", $str, $matches); 
$arr = array_combine($matches[1], $matches[2]);#["a"=>1,"b"=>2,"c"=>3]
php max/min
max(ceil(-0.5), 0) # -0.0
max(0, ceil(-0.5)) # 0
NaN
_.isNaN = function(obj){
    return _.isNumber(obj) && obj !==+obj;
};
Mysql 用 一張表中的數據更新另一張表的數據

update tableA as ca inner join tableB as cb set ca.thumbs=cb.thumbs where cb.courseid=1;
24.php后期靜態綁定

class A {   
public static function get_self() {     
return new self();   
}      
public static function get_static() {     
return new static();   
} 
}   
 class B extends A {} 
get_class(B::get_self());//A 
get_class(B::get_static()) //B 
get_class(A::get_static());//A
json_encode輸出動態javascript
$images = array(  "myself.png" , "friends.png" , "colleagues.png" ); 
$js_code = "var images = " . json_encode($images);  
echo $js_code; // var images = ["myself.png","friends.png","colleagues.png"]
String.fromCharCode
var regex_num_set = /&#(d+);/g;
var str = "Here is some text: 每日一色|蓝白~"

str2 = str.replace(regex_num_set, function(_, $1) {
  return String.fromCharCode($1);
});//"Here is some text: 每日一色|藍白~"
日期格式補0
"2015-5-2".replace(/(?=d)/g, "0")#"2015-05-02"
"2015-5-2".replace(/-(d)(?=-|$)/g, "-0$1")#"2015-05-02"
array_merge如果傳的參數中有一個不是數組;則返回null
$arr = [1,2,3];
$new = "";
array_merge($arr, $new);//null
array_merge($arr, (array)$new);
php switch使用的是==比較;而不是===
switch (0) {//switch (strval(0))
    case "test1":
        echo 1;
    case "test2":
        echo 2;
    case "test3":
        echo 3;
        break;
}
javascript數組的map方法對一個數組中的空位置(沒有設置過值或值被刪除)不會調用提供的callback回調函數
var arr=[1,,3];//第2個位置為空位置
 
var result=arr.map(function(x){
     console.log(x);
     return x + 1;//2,undefined,4
});
arr[1]=undefined;//第2個位置為非空位置,有值undefined
result=arr.map(function(x){
     console.log(x);
     return x + 1;//2,NaN,4
});
setTimeout傳入參數
for(var i = 0; i
循環中promise
var userIds = ["aaa", "bbb", "ccc"];

//這里getUserById返回的是Promise
var promises = arr.map(userIds => getUserById(userId));

Promise
    .all(promises)
    .then(function(users) {
        console.log(users); //這里就是users的列表了
    });
hasClass
function hasClass(element, cName) {
  return (" " + element.className + " ").indexOf(" " + cName + " ") > -1;
}
補零
"2016-1-9 12:12:20".replace(/-(d)(?=-|s)/g, "-0$1")
var str = "2016-1-9 12:12:20";
var ss = str.replace(/-([0-9]+)/g, function(match, p) {
    return p.length !== 1 ? match : "-0" + p;
});
getUrlParameter
var getUrlParameter = function getUrlParameter(sParam) {
    var sPageURL = decodeURIComponent(window.location.search.substring(1)),
        sURLVariables = sPageURL.split("&"),
        sParameterName,
        i;

    for (i = 0; i < sURLVariables.length; i++) {
        sParameterName = sURLVariables[i].split("=");

        if (sParameterName[0] === sParam) {
            return sParameterName[1] === undefined ? true : sParameterName[1];
        }
    }
};
隨機數
Math.round(Math.random() * 1000)//生成0~1000之間的隨機整數
((Math.random() * 10 + 5).toFixed(1) - 0)//產生一個5到15之間,包含一位小數的隨機數Math.floor((Math.random() * 10 + 5) * 10) / 10
顯示隱藏元素
window.onload=function(){  
    var li=document.getElementsByTagName("li");    
      for(var j=0;j
判斷一個json對象中是否含有某個key
function find (obj, key) {
    if (! typeof obj === "object") return false;
    if (key in obj) return true;
    for (var k in obj) if find(obj[k], key) return true;
    return false;
}
數組合并
array = [[1,2,3],[4,5,6],[7,8,9]];
array=array.reduce(function(a,b){return a.concat(b)})//[1,2,3,4,5,6,7,8,9]
array.concat.apply([], array);
區間索引
function getRangeIndex(scrollTop) {
    var i=0;
    ranges = [2,3,6,22,88];
    for (;i
快速生成一個數組,數組的元素是前N個自然數
let f = length => Array.from({length}).map((v,k) => k);
let f = length => [...Array.from({length}).keys()]
let fn = len => Object.keys(new Array(len + 1).join(","))
每取10行放到一個新的文件中
with open("file.txt") as reader, open("newfile.txt", "w") as writer:
    for index, line in enumerate(reader):
        if index % 10 == 0:
            writer.write(line)
按首字母排序
var arr = [9,8,7,6,5,1,"在", "我", "里", "阿","z","a","h","m"];
arr.sort(function(a,b){return a.toString().localeCompare(b)}) //[1, 5, 6, 7, 8, 9, "阿", "里", "我", "在", "a", "h", "m", "z"]
刪除字符串的空格
$str="                            Controllable Eu valence for photoluminescence tuning in apatite-typed";
//pC:所有的unicode“other” pZ:所有的unicode“separator” ,所有空格和不可見字符
echo $str = preg_replace("/^[pZpC]+|[pZpC]+$/u","",$str);//Controllable Eu valence for photoluminescence tuning in apatite-typed
PHP解析JSON得到科學計數法后的int
$json = "{"number": 12345678901234567890}";
var_dump(json_decode($json,1));//[ "number" => 1.2345678901235e+19]
var_dump(json_decode($json,1, 512, JSON_BIGINT_AS_STRING));//["number" => "12345678901234567890"]
//http://cn2.php.net/manual/zh/function.json-decode.php
MySQL中所有數據庫的數據大小
SELECT table_schema, (
(
SUM( DATA_LENGTH ) + SUM( INDEX_LENGTH )
) /1024 /1024
) AS datasize
FROM  `TABLES`
GROUP BY table_schema
LIMIT 0 , 30
合并數組
//一般會用Array.prototype.concat()函數,但不適合來合并兩個大型數組,會消耗大量內存來存儲新創建的數組。可用Array.prototype.push來替代創建一個新數組,可減少內存的使用。
var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];
console.log(array1.push.call(array1, array2)); // [1,2,3,[4,5,6]];
php上傳文件
$tmp_name="test.jpg";
    if(version_compare(phpversion(),"5.5.0") >= 0 && class_exists("CURLFile")){
        $fields["file"] = new CURLFile(realpath($tmp_name));
    }else{
        $fields["file"] = "@".$tmp_name;//加@符號curl就會把它當成是文件上傳處理
    }
php stdclass
$tanteng = new stdClass();
$tanteng->name = "tanteng";
$tanteng->email = "xxx@qq.com";
 //把定義的對象『轉換』成數組
$info = get_object_vars($tanteng);
$user = new stdClass();
$user->name = "gouki";
$user->hehe = "hehe";
$myUser = $user;
$myUser->name = "flypig";
 //$myUser的屬性確實改變了$user聲明的stdClass屬性。而如果$user是一個數組,賦值給$myUser,那就拷貝了一個副本給$myUser,這樣增大系統開銷
print_r($user);
 
print_r($myUser);
 
print_r($user);
PHP浮點數運算精度
$a = 69.1;
 
$b = $a*100;
 
$c = $b-6910;//-9.0949470177293E-13

$c = round($b)-6910;
$x = 8 - 6.4;  // which is equal to 1.6
$y = 1.6;
var_dump($x == $y); // is not true
var_dump(round($x, 2) == round($y, 2)); // this is true
$a = intval( 0.58*100 );//57
 
$b = 0.58*100;
$a = intval( (0.58*1000)/10 );//58
intval( round(0.58*100 ));//58
防止瀏覽器屏蔽window.open

修改session_id的保存位置
session_set_cookie_params(0,‘/’,‘testdomain’);
session_start();//開啟session
echo ‘Old Session id:’.session_id().‘
’; session_regenerate_id(true);//重置session_id,并使原session無效 echo ‘New Session id:’.session_id().‘
’; //echo session_id()失效 setcookie(session_name(),session_id(),0,‘/’,‘testdomain’);//手動更新session_id
CRUL命令簡單分析請求細節所占用的時間
curl -o /dev/null -s -w %{http_code}:%{time_namelookup}:%{time_redirect}:%{time_pretransfer}:%{time_connect}:%{time_starttransfer}:%{time_total}:%{speed_download} www.baidu.com
//這個例子是分析一次百度的請求各個參數:http狀態碼、DNS解析時間、重定向時間、從開始到準備傳輸的時間、TCP連接時間、開始傳輸時間、總時間、下載速度CURL文檔:https://curl.haxx.se/docs/manpage.html
php上周時間
echo "
上周起始時間:
"; echo date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),date("d")-date("w")+1-7,date("Y")))," "; echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y")))," "; echo date("Y-m-d",strtotime("-1 week last monday"))." 00:00:00"; echo date("Y-m-d",strtotime("last sunday"))." 23:59:59"; //當前時間的上一周時間 每周時間固定為7天 date("Y-m-d", strtotime("-1 week")) //如果當前日期為2016-5-31, 用date("Y-m-d", strtotime("-1 month"))會產生錯誤。因為這里把 -1 month按照-30 days來算 date("Y-m-d", strtotime("2016-05-31 -1 month")) = 2016-05-01 date("Y-m-d", strtotime("2016-01-31 +1 month")) = 2016-03-02 //如果需要取當前月的前后月份的話,需要小心,正確做法可以改為 date("m", strtotime(date("Y-m-1")." -1 month")) date("m", strtotime(date("Y-m-1")." +1 month"))
{ "a":"1","b":"2"} 變成 "a:1;b:2"
var obj = {"a":"1","b":"2","c":"3"};
var str = $.map(obj,function(n,index){return ""+index+":"+n;}).join(";");//"a:1;b:2;c:3"
var str = JSON.stringify(obj).replace(/"|{|}/g, "").replace(/,/g, ";")
Object.keys({"a":"1","b":"2"}).map(function(key){return key+":"+info[key]}).join(";");
python格式化
ips = (
    (1, "10.121.1.1:4730"),
    (2, "127.0.0.1:4730"),
    (3, "127.0.0.1:4730")
)

dic = {}
for v, k in ips:
    dic.setdefault(k, []).append((v, k))

print dic
{
    "10.121.1.1:4730":
        [(1, "10.121.1.1:4730")], 
    "127.0.0.1:4730":
        [(2, "127.0.0.1:4730"), (3, "127.0.0.1:4730")]
}
PHP生成連續數據
$numbers = array(0, 1, 3, 5, 6, 8, 10);
sort($numbers);
$new = range(array_shift($numbers),end($numbers));//[0 1 2 3 4 5 6 7 8 9 10]
$a = [0,1,3,5,6,8,10];//原始數據
sort($a);
range(array_shift($a),array_pop($a));
javascript對象復制
function clone(e) {
    var t = {};
    for (var n in e) e.hasOwnProperty(n) && (t[n] = e[n]);
    return t;
}
過濾掉emoji表情
function filterEmoji($str)
{
    $str = preg_replace_callback(
            "/./u",
            function (array $match) {
                return strlen($match[0]) >= 4 ? "" : $match[0];
            },
            $str);

     return $str;
 }
javascript選擇器
function $(selector, context) {
        context = context || document;
        var elements = context.querySelectorAll(selector);
        return Array.prototype.slice.call(elements);
    };
jquery對象對比,開發中要盡量先保存創建的jQuery對象,然后多次使用
var elem1 = $("#navList li");
var elem2 = $("#navList li");
elem1 ==elem2;//false
//應該比較dom本身不是 jQuery對象
$("div") === $("div") //false
$("div")[0] === $("div")[0]//true
for 循環和異步調用的問題
for (var i = 0; i < 6; i++) {
    // do 同步執行,里面的 i 是 0 
    do(i).then(function() {
       // another 異步執行,此時 i 已經是循環后的6
        another(i)
    })
}
//使用閉包保存變量的方式來解決
for (var i = 0; i < 6; i++) {
    // 立即執行函數作閉包,保存變量i為index
    (function(index) {
        do(index).then(function() {
            another(index);
        })
    })(i)
}
按照字母和數字的順序進行排序
var arr = ["A1","A2","A100","A7","B2","A10","A14","B12","C1","C10","C5"]
arr.sort(function(a, b) {
  var ret = a.charCodeAt(0) - b.charCodeAt(0); // 首字母處理
  if (ret == 0) {
    ret = +a.slice(1) - +b.slice(1); // 數字處理
  }
  return ret;//["A1", "A2", "A7", "A10", "A14", "A100", "B2", "B12", "C1", "C5", "C10"]
});
JSON.parse轉換報錯
var getValue = function (objStr) {
    return new Function("return " + objStr)()
}
// 調用
var res1 = getValue("{"foo" : 1, }")//Object {foo: 1}
JSON.parse(res1);
javascript正則替換
var str = "abc{xdf}efg{dfg}ijk{232}";
var arr = ["d", "h", "l"];
var result = str.match(/{.*?}/g);
for (var i = 0; i < result.length; i++) {
    str = str.replace(result[i], arr[i])
}
console.log(str);
//abcdefghijkl
javascript閉包
function Score(){
    this.scores = [];
}
Score.prototype.add = function(score){
    this.scores.push(score);
};
Score.prototype.showAverage = function(){
    let sum = this.scores.reduce(function(pre,cur){
        return pre+cur;
    });
    console.log(sum*1.0/this.scores.length);
};
let scores = [90,80,70];
let score1 = new Score();
scores.forEach(score1.add);//scores.forEach(score1.add.bind(score1));
scores.forEach(function(score) {
    score1.add(score);
});
score1.showAverage();
javascript array reduce()
arr.reduce(function (pre, cur, index) {
    if (index >= 3) {
        return pre;
    }
    return pre + cur;
}, initVal);
javascript 漢字占2字節
function getLength(str) {
    return str.replace(/[^ -~]/g, "AA").length;
}

function limitMaxLength(str, maxLength) {
    var result = [];
    for (var i = 0; i < maxLength; i++) {
        var char = str[i]
        if (/[^ -~]/.test(char))
            maxLength--;
        result.push(char);
    }
    return result.join("");
}
隱藏手機號
echo substr_replace ("13412343312","****",3,4) ;//134**3312
javascript數組降維
var flatten = function(array) {
    return array.reduce(function(previous, i) {
        if (Object.prototype.toString.call(i) !== "[object Array]") {
            return (previous.push(i), previous);
        }
        return (Array.prototype.push.apply(previous, flatten(i)), previous);
    }, []);
};
undefined
flatten([[1, 2],[3, 4, 5], [6, 7, 8, 9,[11,12,[12,13,[14]]]],10]);
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
[[0, 1], [2, 3], [4, 5]].reduce(function(a, b) {
    return a.concat(b);
});
獲取content-type
//獲取content-type
function getContentType($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_exec($ch);
    $contentType = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
    return $contentType;
}
 
//獲取url后綴
function getUrlExtension($url)
{
    $parseurl = parse_url($url);
    $extension = pathinfo($parseurl["path"], PATHINFO_EXTENSION);
    return $extension;
}
PHP隨機合并數組并保持原排序
//隨機合并兩個數組元素,保持原有數據的排序不變(即各個數組的元素在合并后的數組中排序與自身原來一致)
function shuffleMergeArray() {
    $mergeArray = array();
    $sum = count($array1) + count($array2);
    for ($k = $sum; $k > 0; $k--) {
        $number = mt_rand(1, 2);
        if ($number == 1) {
            $mergeArray[] = $array2 ? array_shift($array2) : array_shift($array1);
        } else {
            $mergeArray[] = $array1 ? array_shift($array1) : array_shift($array2);
        }
    }


    return $mergeArray;
//合并前的數組:
$array1 = array(1, 2, 3, 4);
$array2 = array("a", "b", "c", "d", "e");

//合并后的數據:
$mergeArray = array (
  0 => "a",
  1 => 1,
  2 => "b",
  3 => 2,
  4 => "c",
  5 => "d",
  6 => 3,
  7 => 4,
  8 => "e",
)
仿知乎復制文本自帶版權聲明
document.body.addEventListener("copy", function (e) {
????if (window.getSelection().toString() && window.getSelection().toString().length > 42) {
????????setClipboardText(e);
????????alert("商業轉載請聯系作者獲得授權,非商業轉載請注明出處,謝謝合作。");
????}
});
?
function setClipboardText(event) {
????var clipboardData = event.clipboardData || window.clipboardData;
????if (clipboardData) {
????????event.preventDefault();
?
????????var htmlData = ""
????????????+ "著作權歸作者所有。
" ????????????+ "商業轉載請聯系作者獲得授權,非商業轉載請注明出處。
" ????????????+ "作者:DIYgod
" ????????????+ "鏈接:" + window.location.href + "
" ????????????+ "來源:Anotherhome

" ????????????+ window.getSelection().toString(); ????????var textData = "" ????????????+ "著作權歸作者所有。 " ????????????+ "商業轉載請聯系作者獲得授權,非商業轉載請注明出處。 " ????????????+ "作者:DIYgod " ????????????+ "鏈接:" + window.location.href + " " ????????????+ "來源:Anotherhome " ????????????+ window.getSelection().toString(); ? ????????clipboardData.setData("text/html", htmlData); ????????clipboardData.setData("text/plain",textData); ????} }
根據用戶積分判斷等級
//lv1:1~50
//lv2:51~110
//lv3:111~180
//lv4:181~260
function getLevel($point) {
    $level = 0;
    while($point >= 0) {
        $point -= 50 + $level++ * 10;
    }
    return $level;
}
0000000序列遞增
for ($i = 0; $i < 100; $i++) { 
    $zero = "";
    $k = 7-strlen($i);
    for ($j = $k; $j >0; $j--) { 
        $zero .= 0;
    }
    echo $zero.$i."
"; } for (var i = 0 ; i <= 100; i ++){ var zero = ""; for (var j = 7-i.toString().length; j > 0; j--) { zero += "0"; } console.log(zero + i); } for ($i=0;$i<=9999999;$i++) echo str_pad($i,7,"0",STR_PAD_LEFT); //Array.from(Array(1000000).keys()).map(function(x){ return "0".repeat(8 - ("" + (x + 1)).length) + (x+1)})
判斷遠程圖片是否存在
function exist_file($url){ 
$opts=array( 
"http"=>array( 
"method"=>"HEAD", 
"timeout"=>2 
)); 
@file_get_contents($url,false,stream_context_create($opts)); 
if ($http_response_header[0] == "HTTP/1.1 200 OK") { 
return true; 
} else { 
return false; 
} 
}
檢測函數類型
function getType(value){  //基本上可以返回所有的類型,不論你是自定義還是原生
    return Object.prototype.toString.call(value).match(/s{1}(w+)/)[1];
}
let obj = new Object();
console.log(getType(obj)); //"Object"
moment.js時間處理
var a = moment([2016, 0, 15]);
var b = moment([2016, 7, 31]);
var diff = b.diff(a, "months");

var diffMonths = Array
        .apply([], new Array(diff + 1))
        .map(function(item, index) {
            return a.clone().add(index, "month").format("YYYY-MM");
        });

console.log(diffMonths);//["2016-01", "2016-02", "2016-03", "2016-04", "2016-05", "2016-06", "2016-07"]
php中文正則匹配
php中文正則匹配$str = "one中國你好two";
$preg = "/P{Han}+/u";
$result = preg_replace($preg, "", $str);
var_dump($result); //string(12) "中國你好" p小寫是匹配漢字,P大寫是匹配非漢字
生成6位的數字驗證碼
console.log(("000000" + Math.floor(Math.random() * 999999)).slice(-6));
console.log(Math.random().toString().slice(-6));
console.log(/d{6}/.exec(Math.random())[0])
console.log("" + Math.floor(Math.random() * 999999));
16進制顏色代碼生成
(function(){
return "#"+("00000"+(Math.random()*0x1000000<<0).toString(16)).slice(-6);
})()
php 模擬 tail -f
$handle = popen("tail -f /var/log/nginx/access.log 2>&1", "r");
     while(!feof($handle)) {
     $buffer = fgets($handle);
     echo "$buffer
";
     flush();
}
pclose($handle);
mysql distinct
test表的結構
id test1 test2
1 a 1
2 a 2
3 a 3
4 a 1
5 b 1
6 b 2
7 b 3
8 b 2
select distinct test1 from test
test1
a
b
select distinct test1, id from test
test1 id
a 1
a 2
a 3
a 4
b 5
b 6
b 7
b 8
SELECT id, group_concat( DISTINCT test1 ) t FROM test GROUP BY test1
id t
1 a
5 b
php下載文件
try {
    $client = new GuzzleHttpClient($url,[
    "curl.options" => [
        CURLOPT_SSL_VERIFYPEER=>2,
        CURLOPT_SSL_VERIFYHOST=true,
    ]
]);
    $data = $client->request("get","http://xxxx")->getBody()->getContents();
    Storage::disk("local")->put("filename", $data);
} catch (GuzzleHttpRequestException $e) {
    echo "fetch fail";
}
javascript sort 排序
var  arr=[3,4,6,21,2,3,4,1,2,9,6,3,4,5,6,7,2,3];
arr.sort(function(a,b){
        return  a>b;
});
console.log(arr);//[9, 3, 2, 3, 2, 3, 2, 1, 3, 4, 4, 4, 5, 6, 6, 6, 7, 21]

var  arr=[3,4,6,21,2,3,4,1,2,9,6,3,4,5,6,7,2,3];
arr.sort(function(a,b){
        return  a-b;
});
console.log(arr);//[1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 6, 6, 6, 7, 9, 21]
var  arr=[
        {name:"one",age:10},
        {name:"two",age:40},
        {name:"three",age:30},
        {name:"four",age:90},
        {name:"five",age:60}
];
arr.sort(function(a,b)  {
        return  a.age-b.age;
});
console.log(arr);
javascript date
new Date(2016,1,31) > new Date(2016, 2, 1)//true
//month 從 0 開始算 new Date(2016,1,31) == 2016 年 2 月 31 日 然而 2 月只有 29 天 so 
new Date(2016,1,31) == 2016 年 3 月 2 日
new Date(2016,1,30) > new Date(2016, 2, 1)//false
javascript lastIndex
function filtrate() { 
var newArr = [], reg = /^s*$/g, 
str = "baidu,google, , ,baidu,google,bg"; 
arr = str.split(","); 
for (var i = 0; i < arr.length; i++) { 
//var reg = /^s*$/g; 
if (!reg.test(arr[i])) { 
newArr.push(arr[i]); 
} 
} 
return newArr;//["baidu", "google", " ", "baidu", "google", "bg"] 
} 

function filtrate2() { 
var newArr = [], reg = /^s*$/g, 
str = "baidu,google, , ,baidu,google,bg"; 
arr = str.split(","); 
for (var i = 0; i < arr.length; i++) { 
var reg = /^s*$/g; 
if (!reg.test(arr[i])) { 
newArr.push(arr[i]); 
} 
} 
return newArr; //["baidu", "google", "baidu", "google", "bg"]
}
微信瀏覽器禁止頁面下拉查看網址
var overscroll = function(el) {
  el.addEventListener("touchstart", function() {
    var top = el.scrollTop
      , totalScroll = el.scrollHeight
      , currentScroll = top + el.offsetHeight;
    //If we"re at the top or the bottom of the containers
    //scroll, push up or down one pixel.
    //
    //this prevents the scroll from "passing through" to
    //the body.
    if(top === 0) {
      el.scrollTop = 1;
    } else if(currentScroll === totalScroll) {
      el.scrollTop = top - 1;
    }
  });
  el.addEventListener("touchmove", function(evt) {
    //if the content is actually scrollable, i.e. the content is long enough
    //that scrolling can occur
    if(el.offsetHeight < el.scrollHeight)
      evt._isScroller = true;
  });
}
overscroll(document.querySelector(".scroll"));
document.body.addEventListener("touchmove", function(evt) {
  //In this case, the default behavior is scrolling the body, which
  //would result in an overflow.  Since we don"t want that, we preventDefault.
  if(!evt._isScroller) {
    evt.preventDefault();
  }
});
laravel 為 VerifyCsrfToken 添加過濾條件
//修改 app/Http/Middleware/VerifyCsrfToken.php

switch 字符串和數字會隱式轉換比較
$string="2string";

switch($string)
{
    case (string) 1:
        echo "this is 1";
        break;
    case (string) 2:
        echo "this is 2";
        break;
    case "2string":
        echo "this is a string";
        break;
}
輸出調試信息
function log(msg){
    var $body = document.querySelector("body");
    
    if( !$body.querySelector(".info_wz_852") ){
        $body.innerHTML += "
"; } var $info = $body.querySelector(".info_wz_852"); var date = new Date(), minute = ("00"+date.getMinutes()).slice(-2), second = ("00"+date.getSeconds()).slice(-2); try{ throw new Error(); }catch(e){ var loc = (e.stack.replace(/Error /).split(/ /)[1]).replace(/^(s|u00A0)+/,"").replace(/(s|u00A0)+$/,""); // var arr = loc.split(":"), // col = parseInt(arr.pop()), // line = parseInt(arr.pop()); $info.innerHTML += "

["+minute+":"+second+"] "+loc+"

"+msg+"


"; } }
對象數組互轉方法
/**
     * 數組轉換對象
     *
     * @param $arr 數組
     * @return object|void
     */
    public function arrayToObject($arr)
    {

        if (gettype($arr) != "array") return;
        foreach ($arr as $k => $v) {
            if (gettype($v) == "array" || getType($v) == "object")
                $e[$k] = (object)$this->arrayToObject($v);
        }
        return (object)$e;
    }

    /**
     * 對象轉換數組
     *
     * @param $e StdClass對象實例
     * @return array|void
     */
    public function objectToArray($s)
    {
        $s = (array)$s;
        foreach ($s as $k => $v) {
            if (gettype($v) == "resource") return;
            if (gettype($v) == "object" || gettype($v) == "array")
                $e[$k] = (array)$this->objectToArray($v);
        }
        return $e;
    }
javascript數組隨機
Array.prototype.shuffle = function(n) {
  var len = this.length , num = n?Math.min(n,len):len,arr = this.slice(0)
  arr.sort(function(a,b){
     return Math.random()-0.5
  })
  return arr.slice(0,num-1)
}
php生成不重復字符串

echo sprintf("%x",crc32(microtime()));

PHP 隨機用戶名賬號
//循環創建1萬個隨機賬號,0碰撞,10萬大約0-3個碰撞,足夠應付未來數十億級PV
function genUserNumber()
{
    $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $username = "";
    for ( $i = 0; $i < 6; $i++ )
    {
        $username .= $chars[mt_rand(0, strlen($chars))];
    }
    return strtoupper(base_convert(time() - 1420070400, 10, 36)).$username;
}
一個操作中對 Redis 服務器執行多個命令
Redis::pipeline(function ($pipe) {
  for ($i = 0; $i < 1000; $i++) {
    $pipe->set("key:$i", $i);
  } 
});
中文拼音排序
from pypinyin import lazy_pinyin

chars = ["鑫","鷺","榕","柘","珈","驊","孚","迦","瀚","濮","潯","沱","瀘","愷","怡","岷","萃","兗"]

chars.sort(key=lambda char: lazy_pinyin(char)[0][0])

print([lazy_pinyin(char) for char in chars])
print(chars)
[["cui"], ["fu"], ["hua"], ["han"], ["jia"], ["jia"], ["kai"], ["lu"], ["lu"], ["min"], ["pu"], ["rong"], ["tuo"], ["xin"], ["xun"], ["yi"], ["yan"], ["zhe"]]
["萃", "孚", "驊", "瀚", "珈", "迦", "愷", "鷺", "瀘", "岷", "濮", "榕", "沱", "鑫", "潯", "怡", "兗", "柘"]
php 金額每三位加逗號分隔
//money_format
>>> strrev(implode(",", str_split(strrev("434353222323443"), 3)) )
=> "434,353,222,323,443"
php時間格式化
function getDiffTime($timestamp) 
{
    $datetime = new DateTime(date("Y-m-d H:i:s", $timestamp));
    $datetime_now = new DateTime();
    $interval = $datetime_now->diff($datetime);
    list($y, $m, $d, $h, $i, $s) = explode("-", $interval->format("%y-%m-%d-%h-%i-%s"));
    if ((($result = $y) && ($suffix = "年前")) ||
        (($result = $m) && ($suffix = "月前")) ||
        (($result = $d) && ($suffix = "天前")) ||
        (($result = $h) && ($suffix = "小時前")) ||
        (($result = $i) && ($suffix = "分鐘前")) ||
        (($result = $s) && ($suffix = "剛剛"))) {
        return $suffix != "剛剛" ? $result . $suffix : $suffix;
    }
}
html寫入word
function word($data,$fileName=""){ 
if(empty($data)) return ""; 
$data="".$data.""; 
if(empty($fileName)) $fileName=date("YmdHis").".doc"; 
$fp=fopen($fileName,"wb"); 
fwrite($fp,$data); 
fclose($fp); 
} 
$str = "

hello daye

"; word($str);
一行代碼可以看到所有頁面元素

[].forEach.call($$("*"),function(a){a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)})
https://segmentfault.com/a/11...
http://blog.tanteng.me/2015/1...
http://joebon.cc/date-cross-b...
https://segmentfault.com/a/11...
https://segmentfault.com/q/10...
https://www.zhihu.com/questio...
http://t.cn/RqgIMWa
http://t.cn/h4tDfg
http://div.io/topic/1610
https://www.talkingcoder.com/...
http://www.w3cfuns.com/notes/...
http://www.cnblogs.com/shocke...

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/21575.html

相關文章

  • HTML拾遺

    摘要:簡介萬維網聯盟,,又稱理事會,是萬維網的主要國際標準組織。這些屬性被稱為布爾屬性,他們只能有跟它的屬性名一樣的屬性值所以不需要寫屬性值。 HTML拾遺 這篇博文用來記錄我在寫html的時候遇到的不清楚的、沒有理解的、未能察覺的、反復使用搜索引擎查詢的點和一些總結性的知識。方便查閱。不定期更新。 這篇博文內容來源為網絡,包含自己的理解總結,歡迎在評論區指出錯誤。 文章引用的內容版權歸原...

    tangr206 評論0 收藏0
  • HTML拾遺

    摘要:簡介萬維網聯盟,,又稱理事會,是萬維網的主要國際標準組織。這些屬性被稱為布爾屬性,他們只能有跟它的屬性名一樣的屬性值所以不需要寫屬性值。 HTML拾遺 這篇博文用來記錄我在寫html的時候遇到的不清楚的、沒有理解的、未能察覺的、反復使用搜索引擎查詢的點和一些總結性的知識。方便查閱。不定期更新。 這篇博文內容來源為網絡,包含自己的理解總結,歡迎在評論區指出錯誤。 文章引用的內容版權歸原...

    mgckid 評論0 收藏0
  • PHP 使用 Kafka 安裝拾遺

    摘要:最近項目開發中需要使用消息隊列。不過在環境中安裝的過程中出現了以下報錯開始以為是因為安裝缺少了一些依賴。然后使用了源碼編譯的方式進行安裝同樣報錯了。然后安裝它再執行,執行。擴展包使用純粹的編寫的客戶端,目前支持以上版本的。 最近項目開發中需要使用 Kafka 消息隊列。經過檢索,PHP下面有通用的兩種方式來調用 Kafka 。 php-rdkafka 擴展 以 PHP 擴展的形式進行...

    SimonMa 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<