开发拾遗
来源:SegmentFault
时间:2023-01-16 19:52:27 475浏览 收藏
来到golang学习网的大家,相信都是编程学习爱好者,希望在这里学习数据库相关编程知识。下面本篇文章就来带大家聊聊《开发拾遗》,介绍一下MySQL、Linux、PHP、python、javascript,希望对大家的知识积累有所帮助,助力实战开发!
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\n"; }
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
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 用 一张表中的数据更新另一张表的数据
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(/(?=\b\d\b)/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
随机数
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('/^[\pZ\pC]+|[\pZ\pC]+$/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"))),"\n"; echo date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("d")-date("w")+7-7,date("Y"))),"\n"; 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 $(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 循环和异步调用的问题
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
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
隐藏手机号
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 = '' + '著作权归作者所有。\n' + '商业转载请联系作者获得授权,非商业转载请注明出处。\n' + '作者:DIYgod\n' + '链接:' + window.location.href + '\n' + '来源:Anotherhome\n\n' + 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 0; $j--) { $zero .= 0; } echo $zero.$i.'
'; } for (var i = 0 ; i 0; j--) { zero += "0"; } console.log(zero + i); } for ($i=0;$i
判断远程图片是否存在
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
php 模拟 tail -f
$handle = popen("tail -f /var/log/nginx/access.log 2>&1", 'r'); while(!feof($handle)) { $buffer = fgets($handle); echo "$buffer\n"; 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 \GuzzleHttp\Client($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 (\GuzzleHttp\RequestException $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
微信浏览器禁止页面下拉查看网址
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
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\n/).split(/\n/)[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生成不重复字符串
//循环创建1万个随机账号,0碰撞,10万大约0-3个碰撞,足够应付未来数十亿级PV function genUserNumber() { $chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; $username = ""; for ( $i = 0; $i
一个操作中对 Redis 服务器执行多个命令
Redis::pipeline(function ($pipe) { for ($i = 0; $i 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
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...好了,本文到此结束,带大家了解了《开发拾遗》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!
声明:本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
499 收藏
-
244 收藏
-
235 收藏
-
157 收藏
-
101 收藏
最新阅读
更多>
-
335 收藏
-
467 收藏
-
303 收藏
-
176 收藏
-
368 收藏
-
475 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 507次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 484次学习
评论列表
-
- 落寞的大象
- 这篇博文出现的刚刚好,太细致了,真优秀,码住,关注师傅了!希望师傅能多写数据库相关的文章。
- 2023-04-13 06:13:23
-
- 耍酷的翅膀
- 细节满满,码起来,感谢大佬的这篇文章内容,我会继续支持!
- 2023-04-06 04:19:32
-
- 陶醉的鼠标
- 很好,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,看完之后很有帮助,总算是懂了,感谢作者分享技术贴!
- 2023-03-17 15:12:51
-
- 威武的飞鸟
- 这篇文章真及时,太细致了,赞 👍👍,收藏了,关注博主了!希望博主能多写数据库相关的文章。
- 2023-03-05 16:40:37
-
- user_1671454250
- 很好,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,看完之后很有帮助,总算是懂了,感谢师傅分享文章!
- 2023-02-21 18:41:52